Merge branch 'main' into merge-to-main
diff --git a/.bazelignore b/.bazelignore index 5c3a81c..b92bad0 100644 --- a/.bazelignore +++ b/.bazelignore
@@ -1,4 +1,5 @@ # These are fetched as external repositories. +third_party/abseil-cpp third_party/benchmark third_party/googletest _build/
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index c5d4e28..f9411a6 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -16,7 +16,7 @@ --> **What version of protobuf and what language are you using?** -Version: master/v3.6.0/v3.5.0 etc. +Version: main/v3.6.0/v3.5.0 etc. Language: C++/Java/Python/C#/Ruby/PHP/Objective-C/Javascript **What operating system (Linux, Windows, ...) and version?**
diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 497e811..41dc715 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml
@@ -13,4 +13,4 @@ with: check_filenames: true skip: ./.git,./conformance/third_party,*.snk,*.pb,*.pb.cc,*.pb.h,./src/google/protobuf/testdata,./objectivec/Tests,./python/compatibility_tests/v2.5.0/tests/google/protobuf/internal,./.github/workflows/codespell.yml - ignore_words_list: "alow,alse,ba,cleare,copyable,cloneable,dedup,dur,errorprone,files',fo,fundementals,hel,importd,inout,leapyear,nd,nin,ois,ons,parseable,process',te,testof,ue,unparseable,wasn,wee,gae,keyserver,objext,od,optin,sur" + ignore_words_list: "alow,alse,ba,cleare,copyable,cloneable,dedup,dur,errorprone,files',fo,fundementals,hel,importd,inout,leapyear,nd,nin,ois,ons,parseable,process',te,testof,ue,unparseable,wasn,wee,gae,keyserver,objext,od,optin,streem,sur"
diff --git a/.gitignore b/.gitignore index 4fe3edd..8b76496 100644 --- a/.gitignore +++ b/.gitignore
@@ -46,7 +46,7 @@ any_test.pb.* map*unittest.pb.* unittest*.pb.* -cpp_test*.pb.* +src/google/protobuf/compiler/cpp/test*.pb.* src/google/protobuf/util/**/*.pb.cc src/google/protobuf/util/**/*.pb.h @@ -89,6 +89,10 @@ # Windows native output. cmake/build build_msvc +# Directories suggested by cmake/README.md +/debug/ +/solution/ +/release/ # NuGet packages: we want the repository configuration, but not the # packages themselves.
diff --git a/.gitmodules b/.gitmodules index bcd125a..a287f07 100644 --- a/.gitmodules +++ b/.gitmodules
@@ -5,3 +5,7 @@ path = third_party/googletest url = https://github.com/google/googletest.git ignore = dirty +[submodule "third_party/abseil-cpp"] + path = third_party/abseil-cpp + url = https://github.com/abseil/abseil-cpp.git + branch = lts_2021_11_02
diff --git a/BUILD b/BUILD index 887e5e3..e437626 100644 --- a/BUILD +++ b/BUILD
@@ -2,13 +2,12 @@ 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_pkg//:pkg.bzl", "pkg_zip") -load("@rules_pkg//:mappings.bzl", "pkg_attributes", "pkg_files") load("@rules_proto//proto:defs.bzl", "proto_lang_toolchain", "proto_library") load("@rules_python//python:defs.bzl", "py_library") load("@rules_java//java:defs.bzl", "java_binary", "java_lite_proto_library", "java_proto_library") load(":cc_proto_blacklist_test.bzl", "cc_proto_blacklist_test") load(":protobuf_release.bzl", "package_naming") + licenses(["notice"]) exports_files(["LICENSE"]) @@ -159,6 +158,7 @@ "src/google/protobuf/any_lite.cc", "src/google/protobuf/arena.cc", "src/google/protobuf/arenastring.cc", + "src/google/protobuf/arenaz_sampler.cc", "src/google/protobuf/extension_set.cc", "src/google/protobuf/generated_enum_util.cc", "src/google/protobuf/generated_message_tctable_lite.cc", @@ -352,6 +352,11 @@ visibility = ["//visibility:public"], ) +exports_files( + srcs = WELL_KNOWN_PROTOS, + visibility = ["//pkg:__pkg__"], +) + filegroup( name = "lite_well_known_protos", srcs = LITE_WELL_KNOWN_PROTOS, @@ -419,21 +424,21 @@ # AUTOGEN(protoc_lib_srcs) "src/google/protobuf/compiler/code_generator.cc", "src/google/protobuf/compiler/command_line_interface.cc", - "src/google/protobuf/compiler/cpp/cpp_enum.cc", - "src/google/protobuf/compiler/cpp/cpp_enum_field.cc", - "src/google/protobuf/compiler/cpp/cpp_extension.cc", - "src/google/protobuf/compiler/cpp/cpp_field.cc", - "src/google/protobuf/compiler/cpp/cpp_file.cc", - "src/google/protobuf/compiler/cpp/cpp_generator.cc", - "src/google/protobuf/compiler/cpp/cpp_helpers.cc", - "src/google/protobuf/compiler/cpp/cpp_map_field.cc", - "src/google/protobuf/compiler/cpp/cpp_message.cc", - "src/google/protobuf/compiler/cpp/cpp_message_field.cc", - "src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc", - "src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc", - "src/google/protobuf/compiler/cpp/cpp_primitive_field.cc", - "src/google/protobuf/compiler/cpp/cpp_service.cc", - "src/google/protobuf/compiler/cpp/cpp_string_field.cc", + "src/google/protobuf/compiler/cpp/enum.cc", + "src/google/protobuf/compiler/cpp/enum_field.cc", + "src/google/protobuf/compiler/cpp/extension.cc", + "src/google/protobuf/compiler/cpp/field.cc", + "src/google/protobuf/compiler/cpp/file.cc", + "src/google/protobuf/compiler/cpp/generator.cc", + "src/google/protobuf/compiler/cpp/helpers.cc", + "src/google/protobuf/compiler/cpp/map_field.cc", + "src/google/protobuf/compiler/cpp/message.cc", + "src/google/protobuf/compiler/cpp/message_field.cc", + "src/google/protobuf/compiler/cpp/padding_optimizer.cc", + "src/google/protobuf/compiler/cpp/parse_function_generator.cc", + "src/google/protobuf/compiler/cpp/primitive_field.cc", + "src/google/protobuf/compiler/cpp/service.cc", + "src/google/protobuf/compiler/cpp/string_field.cc", "src/google/protobuf/compiler/csharp/csharp_doc_comment.cc", "src/google/protobuf/compiler/csharp/csharp_enum.cc", "src/google/protobuf/compiler/csharp/csharp_enum_field.cc", @@ -450,35 +455,35 @@ "src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc", "src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc", "src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc", - "src/google/protobuf/compiler/java/java_context.cc", - "src/google/protobuf/compiler/java/java_doc_comment.cc", - "src/google/protobuf/compiler/java/java_enum.cc", - "src/google/protobuf/compiler/java/java_enum_field.cc", - "src/google/protobuf/compiler/java/java_enum_field_lite.cc", - "src/google/protobuf/compiler/java/java_enum_lite.cc", - "src/google/protobuf/compiler/java/java_extension.cc", - "src/google/protobuf/compiler/java/java_extension_lite.cc", - "src/google/protobuf/compiler/java/java_field.cc", - "src/google/protobuf/compiler/java/java_file.cc", - "src/google/protobuf/compiler/java/java_generator.cc", - "src/google/protobuf/compiler/java/java_generator_factory.cc", - "src/google/protobuf/compiler/java/java_helpers.cc", - "src/google/protobuf/compiler/java/java_kotlin_generator.cc", - "src/google/protobuf/compiler/java/java_map_field.cc", - "src/google/protobuf/compiler/java/java_map_field_lite.cc", - "src/google/protobuf/compiler/java/java_message.cc", - "src/google/protobuf/compiler/java/java_message_builder.cc", - "src/google/protobuf/compiler/java/java_message_builder_lite.cc", - "src/google/protobuf/compiler/java/java_message_field.cc", - "src/google/protobuf/compiler/java/java_message_field_lite.cc", - "src/google/protobuf/compiler/java/java_message_lite.cc", - "src/google/protobuf/compiler/java/java_name_resolver.cc", - "src/google/protobuf/compiler/java/java_primitive_field.cc", - "src/google/protobuf/compiler/java/java_primitive_field_lite.cc", - "src/google/protobuf/compiler/java/java_service.cc", - "src/google/protobuf/compiler/java/java_shared_code_generator.cc", - "src/google/protobuf/compiler/java/java_string_field.cc", - "src/google/protobuf/compiler/java/java_string_field_lite.cc", + "src/google/protobuf/compiler/java/context.cc", + "src/google/protobuf/compiler/java/doc_comment.cc", + "src/google/protobuf/compiler/java/enum.cc", + "src/google/protobuf/compiler/java/enum_field.cc", + "src/google/protobuf/compiler/java/enum_field_lite.cc", + "src/google/protobuf/compiler/java/enum_lite.cc", + "src/google/protobuf/compiler/java/extension.cc", + "src/google/protobuf/compiler/java/extension_lite.cc", + "src/google/protobuf/compiler/java/field.cc", + "src/google/protobuf/compiler/java/file.cc", + "src/google/protobuf/compiler/java/generator.cc", + "src/google/protobuf/compiler/java/generator_factory.cc", + "src/google/protobuf/compiler/java/helpers.cc", + "src/google/protobuf/compiler/java/kotlin_generator.cc", + "src/google/protobuf/compiler/java/map_field.cc", + "src/google/protobuf/compiler/java/map_field_lite.cc", + "src/google/protobuf/compiler/java/message.cc", + "src/google/protobuf/compiler/java/message_builder.cc", + "src/google/protobuf/compiler/java/message_builder_lite.cc", + "src/google/protobuf/compiler/java/message_field.cc", + "src/google/protobuf/compiler/java/message_field_lite.cc", + "src/google/protobuf/compiler/java/message_lite.cc", + "src/google/protobuf/compiler/java/name_resolver.cc", + "src/google/protobuf/compiler/java/primitive_field.cc", + "src/google/protobuf/compiler/java/primitive_field_lite.cc", + "src/google/protobuf/compiler/java/service.cc", + "src/google/protobuf/compiler/java/shared_code_generator.cc", + "src/google/protobuf/compiler/java/string_field.cc", + "src/google/protobuf/compiler/java/string_field_lite.cc", "src/google/protobuf/compiler/js/js_generator.cc", "src/google/protobuf/compiler/js/well_known_types_embed.cc", "src/google/protobuf/compiler/objectivec/objectivec_enum.cc", @@ -496,9 +501,9 @@ "src/google/protobuf/compiler/php/php_generator.cc", "src/google/protobuf/compiler/plugin.cc", "src/google/protobuf/compiler/plugin.pb.cc", - "src/google/protobuf/compiler/python/python_generator.cc", - "src/google/protobuf/compiler/python/python_helpers.cc", - "src/google/protobuf/compiler/python/python_pyi_generator.cc", + "src/google/protobuf/compiler/python/generator.cc", + "src/google/protobuf/compiler/python/helpers.cc", + "src/google/protobuf/compiler/python/pyi_generator.cc", "src/google/protobuf/compiler/ruby/ruby_generator.cc", "src/google/protobuf/compiler/subprocess.cc", "src/google/protobuf/compiler/zip_writer.cc", @@ -518,70 +523,6 @@ deps = [":protoc_lib"], ) - -################################################################################ -# Generates protoc release artifacts. -################################################################################ - -genrule( - name = "protoc_readme", - visibility = ["//visibility:private"], - cmd = """ -echo "Protocol Buffers - Google's data interchange format -Copyright 2008 Google Inc. -https://developers.google.com/protocol-buffers/ -This package contains a precompiled binary version of the protocol buffer -compiler (protoc). This binary is intended for users who want to use Protocol -Buffers in languages other than C++ but do not want to compile protoc -themselves. To install, simply place this binary somewhere in your PATH. -If you intend to use the included well known types then don't forget to -copy the contents of the 'include' directory somewhere as well, for example -into '/usr/local/include/'. -Please refer to our official github site for more installation instructions: - https://github.com/protocolbuffers/protobuf" > $@ - """, - outs = ["readme.txt"], -) - -# plugin.proto is excluded from this list because it belongs in a nested folder (protobuf/compiler/plugin.proto) -pkg_files( - name = "wkt_protos_files", - srcs = [value[0] for value in WELL_KNOWN_PROTO_MAP.values() if not value[0].endswith("plugin.proto")], - visibility = ["//visibility:private"], - prefix = "include/google/protobuf", -) - -pkg_files( - name = "compiler_plugin_protos_files", - srcs = ["src/google/protobuf/compiler/plugin.proto"], - visibility = ["//visibility:private"], - prefix = "include/google/protobuf/compiler", -) - -pkg_files( - name = "protoc_files", - srcs = [":protoc"], - attributes = pkg_attributes(mode = "0555"), - visibility = ["//visibility:private"], - prefix = "bin/", -) - -package_naming( - name = "protoc_pkg_naming", -) - -pkg_zip( - name = "protoc_release", - package_file_name = "protoc-{version}-{platform}.zip", - package_variables = ":protoc_pkg_naming", - srcs = [ - ":protoc_files", - ":wkt_protos_files", - ":compiler_plugin_protos_files", - "readme.txt", - ], -) - ################################################################################ # Tests ################################################################################ @@ -605,8 +546,8 @@ RELATIVE_TEST_PROTOS = [ # AUTOGEN(test_protos) "google/protobuf/any_test.proto", - "google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto", - "google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto", + "google/protobuf/compiler/cpp/test_bad_identifiers.proto", + "google/protobuf/compiler/cpp/test_large_enum_value.proto", "google/protobuf/map_proto2_unittest.proto", "google/protobuf/map_unittest.proto", "google/protobuf/unittest.proto", @@ -765,23 +706,24 @@ "src/google/protobuf/any_test.cc", "src/google/protobuf/arena_unittest.cc", "src/google/protobuf/arenastring_unittest.cc", + "src/google/protobuf/arenaz_sampler_test.cc", "src/google/protobuf/compiler/annotation_test_util.cc", "src/google/protobuf/compiler/command_line_interface_unittest.cc", - "src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc", - "src/google/protobuf/compiler/cpp/cpp_move_unittest.cc", - "src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc", - "src/google/protobuf/compiler/cpp/cpp_unittest.cc", - "src/google/protobuf/compiler/cpp/cpp_unittest.inc", + "src/google/protobuf/compiler/cpp/bootstrap_unittest.cc", "src/google/protobuf/compiler/cpp/metadata_test.cc", + "src/google/protobuf/compiler/cpp/move_unittest.cc", + "src/google/protobuf/compiler/cpp/plugin_unittest.cc", + "src/google/protobuf/compiler/cpp/unittest.cc", + "src/google/protobuf/compiler/cpp/unittest.inc", "src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc", "src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc", "src/google/protobuf/compiler/importer_unittest.cc", - "src/google/protobuf/compiler/java/java_doc_comment_unittest.cc", - "src/google/protobuf/compiler/java/java_plugin_unittest.cc", + "src/google/protobuf/compiler/java/doc_comment_unittest.cc", + "src/google/protobuf/compiler/java/plugin_unittest.cc", "src/google/protobuf/compiler/mock_code_generator.cc", "src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc", "src/google/protobuf/compiler/parser_unittest.cc", - "src/google/protobuf/compiler/python/python_plugin_unittest.cc", + "src/google/protobuf/compiler/python/plugin_unittest.cc", "src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc", "src/google/protobuf/descriptor_database_unittest.cc", "src/google/protobuf/descriptor_unittest.cc", @@ -789,6 +731,7 @@ "src/google/protobuf/dynamic_message_unittest.cc", "src/google/protobuf/extension_set_unittest.cc", "src/google/protobuf/generated_message_reflection_unittest.cc", + "src/google/protobuf/generated_message_tctable_lite_test.cc", "src/google/protobuf/inlined_string_field_unittest.cc", "src/google/protobuf/io/coded_stream_unittest.cc", "src/google/protobuf/io/io_win32_unittest.cc", @@ -902,10 +845,10 @@ internal_gen_kt_protos( name = "gen_well_known_protos_kotlinlite", + lite = True, visibility = [ "//java:__subpackages__", ], - lite = True, deps = [proto + "_proto" for proto in LITE_WELL_KNOWN_PROTO_MAP.keys()], ) @@ -1337,17 +1280,16 @@ # ], # ) - java_proto_library( name = "java_test_protos", - deps = [":generic_test_protos"], visibility = ["//java:__subpackages__"], + deps = [":generic_test_protos"], ) java_lite_proto_library( name = "java_lite_test_protos", - deps = [":generic_test_protos"], visibility = ["//java:__subpackages__"], + deps = [":generic_test_protos"], ) java_proto_library( @@ -1449,57 +1391,57 @@ proto_library( name = "kt_unittest_lite", srcs = [ - "src/google/protobuf/unittest_lite.proto", + "src/google/protobuf/map_lite_unittest.proto", "src/google/protobuf/unittest_import_lite.proto", "src/google/protobuf/unittest_import_public_lite.proto", - "src/google/protobuf/map_lite_unittest.proto", + "src/google/protobuf/unittest_lite.proto", ], strip_import_prefix = "src", ) internal_gen_kt_protos( name = "gen_kotlin_unittest_lite", - deps = [":kt_unittest_lite"], lite = True, visibility = ["//java:__subpackages__"], + deps = [":kt_unittest_lite"], ) proto_library( name = "kt_unittest", srcs = [ + "src/google/protobuf/map_proto2_unittest.proto", "src/google/protobuf/unittest.proto", "src/google/protobuf/unittest_import.proto", "src/google/protobuf/unittest_import_public.proto", - "src/google/protobuf/map_proto2_unittest.proto", ], strip_import_prefix = "src", ) internal_gen_kt_protos( name = "gen_kotlin_unittest", - deps = [":kt_unittest"], visibility = ["//java:__subpackages__"], + deps = [":kt_unittest"], ) proto_library( name = "kt_proto3_unittest", srcs = [ - "src/google/protobuf/unittest_proto3.proto", "src/google/protobuf/unittest_import.proto", "src/google/protobuf/unittest_import_public.proto", + "src/google/protobuf/unittest_proto3.proto", ], strip_import_prefix = "src", ) internal_gen_kt_protos( name = "gen_kotlin_proto3_unittest_lite", - deps = [":kt_proto3_unittest"], lite = True, visibility = ["//java:__subpackages__"], + deps = [":kt_proto3_unittest"], ) internal_gen_kt_protos( name = "gen_kotlin_proto3_unittest", - deps = [":kt_proto3_unittest"], visibility = ["//java:__subpackages__"], + deps = [":kt_proto3_unittest"], )
diff --git a/CHANGES.txt b/CHANGES.txt index d01440a..5f6e297 100644 --- a/CHANGES.txt +++ b/CHANGES.txt
@@ -1,4 +1,4 @@ -2022-04-05 version 3.20.1 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) +Unreleased Changes (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) PHP * Fix building packaged PHP extension (#9727) @@ -10,6 +10,32 @@ Other * Fix versioning issues in 3.20.0 + C++ + * Refactor generated message class layout + * Optimize tokenizer ParseInteger by removing division + * Reserve exactly the right amount of capacity in ExtensionSet::MergeFrom + + Compiler + * Protoc outputs the list of suggested field numbers when invalid field + numbers are specified in the .proto file. + * Require package names to be less than 512 bytes in length + + Java + * 6x speedup in ArrayEncoder.writeUInt32NotTag + + Python + * Added UnknownFieldSet(message) for pure Python. The old + message.UnknownFields() will be deprecated after UnknownFieldSet(message) is + added for cpp extension. + +2022-04-21 version 3.20.1 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) + + PHP + * Fix building packaged PHP extension (#9727) + + Other + * Fix versioning issues in 3.20.0 + 2022-03-04 version 3.20.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript) Ruby
diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..7693c3c --- /dev/null +++ b/CMakeLists.txt
@@ -0,0 +1,361 @@ +# Minimum CMake required +cmake_minimum_required(VERSION 3.5) + +if(protobuf_VERBOSE) + message(STATUS "Protocol Buffers Configuring...") +endif() + +# CMake policies +cmake_policy(SET CMP0022 NEW) +# On MacOS use @rpath/ for target's install name prefix path +if (POLICY CMP0042) + cmake_policy(SET CMP0042 NEW) +endif () +# Clear VERSION variables when no VERSION is given to project() +if(POLICY CMP0048) + cmake_policy(SET CMP0048 NEW) +endif() +# MSVC runtime library flags are selected by an abstraction. +if(POLICY CMP0091) + cmake_policy(SET CMP0091 NEW) +endif() + +# Project +project(protobuf C CXX) + +if(protobuf_DEPRECATED_CMAKE_SUBDIRECTORY_USAGE) + if(CMAKE_PROJECT_NAME STREQUAL "protobuf") + get_filename_component(CMAKE_SOURCE_DIR ${CMAKE_SOURCE_DIR} DIRECTORY) + endif() + get_filename_component(CMAKE_CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} DIRECTORY) + get_filename_component(PROJECT_SOURCE_DIR ${PROJECT_SOURCE_DIR} DIRECTORY) + get_filename_component(protobuf_SOURCE_DIR ${protobuf_SOURCE_DIR} DIRECTORY) +endif() + +# Add c++11 flags +if (CYGWIN) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11") +else() + set(CMAKE_CXX_STANDARD 11) + set(CMAKE_CXX_STANDARD_REQUIRED ON) + set(CMAKE_CXX_EXTENSIONS OFF) +endif() + +# The Intel compiler isn't able to deal with noinline member functions of +# template classes 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 +option(protobuf_INSTALL "Install protobuf binaries and files" ON) +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) +option(protobuf_BUILD_PROTOC_BINARIES "Build libprotoc and protoc compiler" ON) +option(protobuf_BUILD_LIBPROTOC "Build libprotoc" OFF) +option(protobuf_DISABLE_RTTI "Remove runtime type information in the binaries" OFF) +if (BUILD_SHARED_LIBS) + set(protobuf_BUILD_SHARED_LIBS_DEFAULT ON) +else (BUILD_SHARED_LIBS) + set(protobuf_BUILD_SHARED_LIBS_DEFAULT OFF) +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" + CACHE STRING "Default debug postfix") +mark_as_advanced(protobuf_DEBUG_POSTFIX) +# User options +include(${protobuf_SOURCE_DIR}/cmake/protobuf-options.cmake) + +# Overrides for option dependencies +if (protobuf_BUILD_PROTOC_BINARIES OR protobuf_BUILD_TESTS) + set(protobuf_BUILD_LIBPROTOC ON) +endif () +# Path to main configure script +set(protobuf_CONFIGURE_SCRIPT "${protobuf_SOURCE_DIR}/configure.ac") + +# Parse configure script +set(protobuf_AC_INIT_REGEX + "^AC_INIT\\(\\[([^]]+)\\],\\[([^]]+)\\],\\[([^]]+)\\],\\[([^]]+)\\]\\)$") +file(STRINGS "${protobuf_CONFIGURE_SCRIPT}" protobuf_AC_INIT_LINE + LIMIT_COUNT 1 REGEX "^AC_INIT") +# Description +string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\1" + protobuf_DESCRIPTION "${protobuf_AC_INIT_LINE}") +# Version +string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\2" + protobuf_VERSION_STRING "${protobuf_AC_INIT_LINE}") +# Contact +string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\3" + protobuf_CONTACT "${protobuf_AC_INIT_LINE}") +# Parse version tweaks +set(protobuf_VERSION_REGEX "^([0-9]+)\\.([0-9]+)\\.([0-9]+)([-]rc[-]|\\.)?([0-9]*)$") +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\1" + protobuf_VERSION_MAJOR "${protobuf_VERSION_STRING}") +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\2" + protobuf_VERSION_MINOR "${protobuf_VERSION_STRING}") +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\3" + protobuf_VERSION_PATCH "${protobuf_VERSION_STRING}") +string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\5" + protobuf_VERSION_PRERELEASE "${protobuf_VERSION_STRING}") + +message(STATUS "${protobuf_VERSION_PRERELEASE}") + +# Package version +set(protobuf_VERSION + "${protobuf_VERSION_MAJOR}.${protobuf_VERSION_MINOR}.${protobuf_VERSION_PATCH}") + +if(protobuf_VERSION_PRERELEASE) + set(protobuf_VERSION "${protobuf_VERSION}.${protobuf_VERSION_PRERELEASE}") +else() + set(protobuf_VERSION "${protobuf_VERSION}.0") +endif() +message(STATUS "${protobuf_VERSION}") + +if(protobuf_VERBOSE) + message(STATUS "Configuration script parsing status [") + message(STATUS " Description : ${protobuf_DESCRIPTION}") + message(STATUS " Version : ${protobuf_VERSION} (${protobuf_VERSION_STRING})") + message(STATUS " Contact : ${protobuf_CONTACT}") + message(STATUS "]") +endif() + +add_definitions(-DGOOGLE_PROTOBUF_CMAKE_BUILD) + +if (protobuf_DISABLE_RTTI) + add_definitions(-DGOOGLE_PROTOBUF_NO_RTTI=1) +endif() + +file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/cmaketest.map +"{ + global: + main; + local: + *; +};") +# CheckLinkerFlag module available in CMake >=3.18. +if(${CMAKE_VERSION} VERSION_GREATER 3.18 OR ${CMAKE_VERSION} VERSION_EQUAL 3.18) + include(CheckLinkerFlag) + check_linker_flag(CXX -Wl,--version-script=${CMAKE_CURRENT_BINARY_DIR}/cmaketest.map protobuf_HAVE_LD_VERSION_SCRIPT) +else() + include(CheckCXXSourceCompiles) + set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) + set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS} -Wl,--version-script=${CMAKE_CURRENT_BINARY_DIR}/cmaketest.map) + check_cxx_source_compiles(" + int main() { + return 0; + } + " protobuf_HAVE_LD_VERSION_SCRIPT) + set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) +endif() +file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/cmaketest.map) + +find_package(Threads REQUIRED) + +# We can install dependencies from submodules if we're running +# CMake v3.13 or newer. +if(CMAKE_VERSION VERSION_LESS 3.13) + set(_protobuf_INSTALL_SUPPORTED_FROM_MODULE OFF) +else() + set(_protobuf_INSTALL_SUPPORTED_FROM_MODULE ON) +endif() + + +set(_protobuf_FIND_ZLIB) +if (protobuf_WITH_ZLIB) + find_package(ZLIB) + if (ZLIB_FOUND) + set(HAVE_ZLIB 1) + # FindZLIB module define ZLIB_INCLUDE_DIRS variable + # Set ZLIB_INCLUDE_DIRECTORIES for compatible + set(ZLIB_INCLUDE_DIRECTORIES ${ZLIB_INCLUDE_DIRECTORIES} ${ZLIB_INCLUDE_DIRS}) + # Using imported target if exists + if (TARGET ZLIB::ZLIB) + set(ZLIB_LIBRARIES ZLIB::ZLIB) + set(_protobuf_FIND_ZLIB "if(NOT ZLIB_FOUND)\n find_package(ZLIB)\nendif()") + endif (TARGET ZLIB::ZLIB) + else (ZLIB_FOUND) + set(HAVE_ZLIB 0) + # Explicitly set these to empty (override NOT_FOUND) so cmake doesn't + # complain when we use them later. + set(ZLIB_INCLUDE_DIRECTORIES) + set(ZLIB_LIBRARIES) + endif (ZLIB_FOUND) +endif (protobuf_WITH_ZLIB) + +if (HAVE_ZLIB) + add_definitions(-DHAVE_ZLIB) +endif (HAVE_ZLIB) + +# We need to link with libatomic on systems that do not have builtin atomics, or +# don't have builtin support for 8 byte atomics +set(protobuf_LINK_LIBATOMIC false) +if (NOT MSVC) + include(CheckCXXSourceCompiles) + set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) + set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS} -std=c++11) + check_cxx_source_compiles(" + #include <atomic> + int main() { + return std::atomic<int64_t>{}; + } + " protobuf_HAVE_BUILTIN_ATOMICS) + if (NOT protobuf_HAVE_BUILTIN_ATOMICS) + set(protobuf_LINK_LIBATOMIC true) + endif (NOT protobuf_HAVE_BUILTIN_ATOMICS) + set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) +endif (NOT MSVC) + +if (protobuf_BUILD_SHARED_LIBS) + set(protobuf_SHARED_OR_STATIC "SHARED") +else (protobuf_BUILD_SHARED_LIBS) + set(protobuf_SHARED_OR_STATIC "STATIC") + # The CMAKE_<LANG>_FLAGS(_<BUILD_TYPE>)? is meant to be user controlled. + # Prior to CMake 3.15, the MSVC runtime library was pushed into the same flags + # making programmatic control difficult. Prefer the functionality in newer + # CMake versions when available. + if(${CMAKE_VERSION} VERSION_GREATER 3.15 OR ${CMAKE_VERSION} VERSION_EQUAL 3.15) + if (protobuf_MSVC_STATIC_RUNTIME) + set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>) + else() + set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>DLL) + endif() + else() + # 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() +endif (protobuf_BUILD_SHARED_LIBS) + +if (MSVC) + if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + # Build with multiple processes + add_definitions(/MP) + endif() + # Set source file and execution character sets to UTF-8 + add_definitions(/utf-8) + # MSVC warning suppressions + add_definitions( + /wd4065 # switch statement contains 'default' but no 'case' labels + /wd4244 # 'conversion' conversion from 'type1' to 'type2', possible loss of data + /wd4251 # 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' + /wd4267 # 'var' : conversion from 'size_t' to 'type', possible loss of data + /wd4305 # 'identifier' : truncation from 'type1' to 'type2' + /wd4307 # 'operator' : integral constant overflow + /wd4309 # 'conversion' : truncation of constant value + /wd4334 # 'operator' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?) + /wd4355 # 'this' : used in base member initializer list + /wd4506 # no definition for inline function 'function' + /wd4800 # 'type' : forcing value to bool 'true' or 'false' (performance warning) + /wd4996 # The compiler encountered a deprecated declaration. + ) + # Allow big object + add_definitions(/bigobj) + string(REPLACE "/" "\\" PROTOBUF_SOURCE_WIN32_PATH ${protobuf_SOURCE_DIR}) + string(REPLACE "/" "\\" PROTOBUF_BINARY_WIN32_PATH ${protobuf_BINARY_DIR}) + string(REPLACE "." "," protobuf_RC_FILEVERSION "${protobuf_VERSION}") + configure_file(${protobuf_SOURCE_DIR}/cmake/extract_includes.bat.in extract_includes.bat) + + # Suppress linker warnings about files with no symbols defined. + set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} /ignore:4221") + + if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + # Configure Resource Compiler + enable_language(RC) + # use English language (0x409) in resource compiler + set(rc_flags "/l0x409") + # fix rc.exe invocations because of usage of add_definitions() + set(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> ${rc_flags} <DEFINES> /fo<OBJECT> <SOURCE>") + endif() + + configure_file(${protobuf_SOURCE_DIR}/cmake/version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY) +endif (MSVC) + +include_directories( + ${ZLIB_INCLUDE_DIRECTORIES} + ${protobuf_BINARY_DIR} + ${protobuf_SOURCE_DIR}/src) + +if (MSVC) + # Add the "lib" prefix for generated .lib outputs. + set(LIB_PREFIX lib) +else (MSVC) + # When building with "make", "lib" prefix will be added automatically by + # the build tool. + set(LIB_PREFIX) +endif (MSVC) + +if (protobuf_UNICODE) + add_definitions(-DUNICODE -D_UNICODE) +endif (protobuf_UNICODE) + +set(protobuf_ABSL_PROVIDER "module" CACHE STRING "Provider of absl library") +set_property(CACHE protobuf_ABSL_PROVIDER PROPERTY STRINGS "module" "package") + +include(${protobuf_SOURCE_DIR}/cmake/abseil-cpp.cmake) +include(${protobuf_SOURCE_DIR}/cmake/libprotobuf-lite.cmake) +include(${protobuf_SOURCE_DIR}/cmake/libprotobuf.cmake) +if (protobuf_BUILD_LIBPROTOC) + include(${protobuf_SOURCE_DIR}/cmake/libprotoc.cmake) +endif (protobuf_BUILD_LIBPROTOC) +if (protobuf_BUILD_PROTOC_BINARIES) + include(${protobuf_SOURCE_DIR}/cmake/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) + enable_testing() + include(${protobuf_SOURCE_DIR}/cmake/tests.cmake) +endif (protobuf_BUILD_TESTS) + +if (protobuf_BUILD_CONFORMANCE) + include(${protobuf_SOURCE_DIR}/cmake/conformance.cmake) +endif (protobuf_BUILD_CONFORMANCE) + +if (protobuf_INSTALL) + include(${protobuf_SOURCE_DIR}/cmake/install.cmake) +endif (protobuf_INSTALL) + +if (protobuf_BUILD_EXAMPLES) + include(${protobuf_SOURCE_DIR}/cmake/examples.cmake) +endif (protobuf_BUILD_EXAMPLES) + +if(protobuf_VERBOSE) + message(STATUS "Protocol Buffers Configuring done") +endif(protobuf_VERBOSE)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8ef5dd2..a16d63c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md
@@ -53,11 +53,11 @@ ## Contributing Process -Most pull requests should go to the master branch and the change will be +Most pull requests should go to the main branch and the change will be included in the next major/minor version release (e.g., 3.6.0 release). If you need to include a bug fix in a patch release (e.g., 3.5.2), make sure it’s -already merged to master, and then create a pull request cherry-picking the -commits from master branch to the release branch (e.g., branch 3.5.x). +already merged to main, and then create a pull request cherry-picking the +commits from main branch to the release branch (e.g., branch 3.5.x). For each pull request, a protobuf team member will be assigned to review the pull request. For minor cleanups, the pull request may be merged right away @@ -96,9 +96,9 @@ of inactivity. * Maintain clean commit history and use meaningful commit messages. PRs with messy commit history are difficult to review and won't be merged. Use rebase - -i upstream/master to curate your commit history and/or to bring in latest - changes from master (but avoid rebasing in the middle of a code review). -* Keep your PR up to date with upstream/master (if there are merge conflicts, + -i upstream/main to curate your commit history and/or to bring in latest + changes from main (but avoid rebasing in the middle of a code review). +* Keep your PR up to date with upstream/main (if there are merge conflicts, we can't really merge your change). * All tests need to be passing before your change can be merged. We recommend you run tests locally before creating your PR to catch breakages early on.
diff --git a/Makefile.am b/Makefile.am index 828262d..dcc2107 100644 --- a/Makefile.am +++ b/Makefile.am
@@ -50,6 +50,7 @@ csharp_EXTRA_DIST= \ global.json \ + csharp/.editorconfig \ csharp/.gitignore \ csharp/CHANGES.txt \ csharp/Google.Protobuf.Tools.targets \ @@ -837,9 +838,11 @@ php/ext/google/protobuf/package.xml \ php/ext/google/protobuf/php-upb.c \ php/ext/google/protobuf/php-upb.h \ + php/ext/google/protobuf/php_protobuf.h \ php/ext/google/protobuf/protobuf.c \ php/ext/google/protobuf/protobuf.h \ php/ext/google/protobuf/wkt.inc \ + php/ext/google/protobuf/tests/unnecessary_zval.phpt \ php/generate_descriptor_protos.sh \ php/generate_test_protos.sh \ php/release.sh \ @@ -1112,6 +1115,8 @@ python/google/protobuf/pyext/repeated_scalar_container.h \ python/google/protobuf/pyext/safe_numerics.h \ python/google/protobuf/pyext/scoped_pyobject_ptr.h \ + python/google/protobuf/pyext/unknown_field_set.cc \ + python/google/protobuf/pyext/unknown_field_set.h \ python/google/protobuf/python_protobuf.h \ python/google/protobuf/reflection.py \ python/google/protobuf/service.py \ @@ -1119,6 +1124,7 @@ python/google/protobuf/symbol_database.py \ python/google/protobuf/text_encoding.py \ python/google/protobuf/text_format.py \ + python/google/protobuf/unknown_fields.py \ python/google/protobuf/util/__init__.py \ python/release.sh \ python/mox.py \ @@ -1396,6 +1402,8 @@ update_file_lists.sh \ BUILD \ WORKSPACE \ + CMakeLists.txt \ + cmake/abseil-cpp.cmake \ cmake/CMakeLists.txt \ cmake/README.md \ cmake/conformance.cmake \
diff --git a/README.md b/README.md index 618dc2a..fe3430b 100644 --- a/README.md +++ b/README.md
@@ -38,7 +38,7 @@ [https://repo1.maven.org/maven2/com/google/protobuf/protoc/](https://repo1.maven.org/maven2/com/google/protobuf/protoc/) These pre-built binaries are only provided for released versions. If you want -to use the github master version at HEAD, or you need to modify protobuf code, +to use the github main version at HEAD, or you need to modify protobuf code, or you are using C++, it's recommended to build your own protoc binary from source.
diff --git a/benchmarks/README.md b/benchmarks/README.md index 13a8843..70c3596 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md
@@ -5,7 +5,7 @@ can use to test a variety of performance scenarios against your protobuf language runtime. If you are looking for performance numbers of officially supported languages, see [Protobuf Performance]( -https://github.com/protocolbuffers/protobuf/blob/master/docs/performance.md). +https://github.com/protocolbuffers/protobuf/blob/main/docs/performance.md). ## Prerequisite @@ -61,7 +61,7 @@ include PHP protobuf's src and build the c extension if required. ### Node.js -Node.js benchmark need [node](https://nodejs.org/en/)(higher than V6) and [npm](https://www.npmjs.com/) package manager installed. This benchmark is using the [benchmark](https://www.npmjs.com/package/benchmark) framework to test, which needn't to manually install. And another prerequisite is [protobuf js](https://github.com/protocolbuffers/protobuf/tree/master/js), which needn't to manually install either +Node.js benchmark need [node](https://nodejs.org/en/)(higher than V6) and [npm](https://www.npmjs.com/) package manager installed. This benchmark is using the [benchmark](https://www.npmjs.com/package/benchmark) framework to test, which needn't to manually install. And another prerequisite is [protobuf js](https://github.com/protocolbuffers/protobuf/tree/main/js), which needn't to manually install either ### C# The C# benchmark code is built as part of the main Google.Protobuf @@ -69,18 +69,6 @@ [BenchmarkDotNet](https://github.com/dotnet/BenchmarkDotNet), which will be downloaded automatically. -### Big data - -There's some optional big testing data which is not included in the directory -initially, you need to run the following command to download the testing data: - -``` -$ ./download_data.sh -``` - -After doing this the big data file will automatically generated in the -benchmark directory. - ## Run instructions To run all the benchmark dataset:
diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt index ac92442..4e39573 100644 --- a/cmake/CMakeLists.txt +++ b/cmake/CMakeLists.txt
@@ -1,342 +1,9 @@ -# Minimum CMake required cmake_minimum_required(VERSION 3.5) -if(protobuf_VERBOSE) - message(STATUS "Protocol Buffers Configuring...") -endif() +message(WARNING "Calling of cmake with source directory set to \"cmake\" subdirectory of Protocol Buffers project is deprecated. Top-level directory of Protocol Buffers project should be used instead.") -# CMake policies -cmake_policy(SET CMP0022 NEW) -# On MacOS use @rpath/ for target's install name prefix path -if (POLICY CMP0042) - cmake_policy(SET CMP0042 NEW) -endif () -# Clear VERSION variables when no VERSION is given to project() -if(POLICY CMP0048) - cmake_policy(SET CMP0048 NEW) -endif() -# MSVC runtime library flags are selected by an abstraction. -if(POLICY CMP0091) - cmake_policy(SET CMP0091 NEW) -endif() - -# Project project(protobuf C CXX) -# Add c++11 flags -if (CYGWIN) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11") -else() - set(CMAKE_CXX_STANDARD 11) - set(CMAKE_CXX_STANDARD_REQUIRED ON) - set(CMAKE_CXX_EXTENSIONS OFF) -endif() +set(protobuf_DEPRECATED_CMAKE_SUBDIRECTORY_USAGE TRUE) -# The Intel compiler isn't able to deal with noinline member functions of -# template classes 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 -option(protobuf_INSTALL "Install protobuf binaries and files" ON) -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) -option(protobuf_BUILD_PROTOC_BINARIES "Build libprotoc and protoc compiler" ON) -option(protobuf_BUILD_LIBPROTOC "Build libprotoc" OFF) -option(protobuf_DISABLE_RTTI "Remove runtime type information in the binaries" OFF) -if (BUILD_SHARED_LIBS) - set(protobuf_BUILD_SHARED_LIBS_DEFAULT ON) -else (BUILD_SHARED_LIBS) - set(protobuf_BUILD_SHARED_LIBS_DEFAULT OFF) -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" - CACHE STRING "Default debug postfix") -mark_as_advanced(protobuf_DEBUG_POSTFIX) -# User options -include(protobuf-options.cmake) - -# Overrides for option dependencies -if (protobuf_BUILD_PROTOC_BINARIES OR protobuf_BUILD_TESTS) - set(protobuf_BUILD_LIBPROTOC ON) -endif () -# Path to main configure script -set(protobuf_CONFIGURE_SCRIPT "../configure.ac") - -# Parse configure script -set(protobuf_AC_INIT_REGEX - "^AC_INIT\\(\\[([^]]+)\\],\\[([^]]+)\\],\\[([^]]+)\\],\\[([^]]+)\\]\\)$") -file(STRINGS "${protobuf_CONFIGURE_SCRIPT}" protobuf_AC_INIT_LINE - LIMIT_COUNT 1 REGEX "^AC_INIT") -# Description -string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\1" - protobuf_DESCRIPTION "${protobuf_AC_INIT_LINE}") -# Version -string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\2" - protobuf_VERSION_STRING "${protobuf_AC_INIT_LINE}") -# Contact -string(REGEX REPLACE "${protobuf_AC_INIT_REGEX}" "\\3" - protobuf_CONTACT "${protobuf_AC_INIT_LINE}") -# Parse version tweaks -set(protobuf_VERSION_REGEX "^([0-9]+)\\.([0-9]+)\\.([0-9]+)([-]rc[-]|\\.)?([0-9]*)$") -string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\1" - protobuf_VERSION_MAJOR "${protobuf_VERSION_STRING}") -string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\2" - protobuf_VERSION_MINOR "${protobuf_VERSION_STRING}") -string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\3" - protobuf_VERSION_PATCH "${protobuf_VERSION_STRING}") -string(REGEX REPLACE "${protobuf_VERSION_REGEX}" "\\5" - protobuf_VERSION_PRERELEASE "${protobuf_VERSION_STRING}") - -message(STATUS "${protobuf_VERSION_PRERELEASE}") - -# Package version -set(protobuf_VERSION - "${protobuf_VERSION_MAJOR}.${protobuf_VERSION_MINOR}.${protobuf_VERSION_PATCH}") - -if(protobuf_VERSION_PRERELEASE) - set(protobuf_VERSION "${protobuf_VERSION}.${protobuf_VERSION_PRERELEASE}") -else() - set(protobuf_VERSION "${protobuf_VERSION}.0") -endif() -message(STATUS "${protobuf_VERSION}") - -if(protobuf_VERBOSE) - message(STATUS "Configuration script parsing status [") - message(STATUS " Description : ${protobuf_DESCRIPTION}") - message(STATUS " Version : ${protobuf_VERSION} (${protobuf_VERSION_STRING})") - message(STATUS " Contact : ${protobuf_CONTACT}") - message(STATUS "]") -endif() - -add_definitions(-DGOOGLE_PROTOBUF_CMAKE_BUILD) - -if (protobuf_DISABLE_RTTI) - add_definitions(-DGOOGLE_PROTOBUF_NO_RTTI=1) -endif() - -file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/cmaketest.map -"{ - global: - main; - local: - *; -};") -# CheckLinkerFlag module available in CMake >=3.18. -if(${CMAKE_VERSION} VERSION_GREATER 3.18 OR ${CMAKE_VERSION} VERSION_EQUAL 3.18) - include(CheckLinkerFlag) - check_linker_flag(CXX -Wl,--version-script=${CMAKE_CURRENT_BINARY_DIR}/cmaketest.map protobuf_HAVE_LD_VERSION_SCRIPT) -else() - include(CheckCXXSourceCompiles) - set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) - set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS} -Wl,--version-script=${CMAKE_CURRENT_BINARY_DIR}/cmaketest.map) - check_cxx_source_compiles(" - int main() { - return 0; - } - " protobuf_HAVE_LD_VERSION_SCRIPT) - set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) -endif() -file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/cmaketest.map) - -find_package(Threads REQUIRED) - -set(_protobuf_FIND_ZLIB) -if (protobuf_WITH_ZLIB) - find_package(ZLIB) - if (ZLIB_FOUND) - set(HAVE_ZLIB 1) - # FindZLIB module define ZLIB_INCLUDE_DIRS variable - # Set ZLIB_INCLUDE_DIRECTORIES for compatible - set(ZLIB_INCLUDE_DIRECTORIES ${ZLIB_INCLUDE_DIRECTORIES} ${ZLIB_INCLUDE_DIRS}) - # Using imported target if exists - if (TARGET ZLIB::ZLIB) - set(ZLIB_LIBRARIES ZLIB::ZLIB) - set(_protobuf_FIND_ZLIB "if(NOT ZLIB_FOUND)\n find_package(ZLIB)\nendif()") - endif (TARGET ZLIB::ZLIB) - else (ZLIB_FOUND) - set(HAVE_ZLIB 0) - # Explicitly set these to empty (override NOT_FOUND) so cmake doesn't - # complain when we use them later. - set(ZLIB_INCLUDE_DIRECTORIES) - set(ZLIB_LIBRARIES) - endif (ZLIB_FOUND) -endif (protobuf_WITH_ZLIB) - -if (HAVE_ZLIB) - add_definitions(-DHAVE_ZLIB) -endif (HAVE_ZLIB) - -# We need to link with libatomic on systems that do not have builtin atomics, or -# don't have builtin support for 8 byte atomics -set(protobuf_LINK_LIBATOMIC false) -if (NOT MSVC) - include(CheckCXXSourceCompiles) - set(OLD_CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) - set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS} -std=c++11) - check_cxx_source_compiles(" - #include <atomic> - int main() { - return std::atomic<int64_t>{}; - } - " protobuf_HAVE_BUILTIN_ATOMICS) - if (NOT protobuf_HAVE_BUILTIN_ATOMICS) - set(protobuf_LINK_LIBATOMIC true) - endif (NOT protobuf_HAVE_BUILTIN_ATOMICS) - set(CMAKE_REQUIRED_FLAGS ${OLD_CMAKE_REQUIRED_FLAGS}) -endif (NOT MSVC) - -if (protobuf_BUILD_SHARED_LIBS) - set(protobuf_SHARED_OR_STATIC "SHARED") -else (protobuf_BUILD_SHARED_LIBS) - set(protobuf_SHARED_OR_STATIC "STATIC") - # The CMAKE_<LANG>_FLAGS(_<BUILD_TYPE>)? is meant to be user controlled. - # Prior to CMake 3.15, the MSVC runtime library was pushed into the same flags - # making programmatic control difficult. Prefer the functionality in newer - # CMake versions when available. - if(${CMAKE_VERSION} VERSION_GREATER 3.15 OR ${CMAKE_VERSION} VERSION_EQUAL 3.15) - if (protobuf_MSVC_STATIC_RUNTIME) - set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>) - else() - set(CMAKE_MSVC_RUNTIME_LIBRARY MultiThreaded$<$<CONFIG:Debug>:Debug>DLL) - endif() - else() - # 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() -endif (protobuf_BUILD_SHARED_LIBS) - -if (MSVC) - if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - # Build with multiple processes - add_definitions(/MP) - endif() - # Set source file and execution character sets to UTF-8 - add_definitions(/utf-8) - # MSVC warning suppressions - add_definitions( - /wd4065 # switch statement contains 'default' but no 'case' labels - /wd4244 # 'conversion' conversion from 'type1' to 'type2', possible loss of data - /wd4251 # 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' - /wd4267 # 'var' : conversion from 'size_t' to 'type', possible loss of data - /wd4305 # 'identifier' : truncation from 'type1' to 'type2' - /wd4307 # 'operator' : integral constant overflow - /wd4309 # 'conversion' : truncation of constant value - /wd4334 # 'operator' : result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?) - /wd4355 # 'this' : used in base member initializer list - /wd4506 # no definition for inline function 'function' - /wd4800 # 'type' : forcing value to bool 'true' or 'false' (performance warning) - /wd4996 # The compiler encountered a deprecated declaration. - ) - # Allow big object - add_definitions(/bigobj) - string(REPLACE "/" "\\" PROTOBUF_SOURCE_WIN32_PATH ${protobuf_SOURCE_DIR}) - string(REPLACE "/" "\\" PROTOBUF_BINARY_WIN32_PATH ${protobuf_BINARY_DIR}) - string(REPLACE "." "," protobuf_RC_FILEVERSION "${protobuf_VERSION}") - configure_file(extract_includes.bat.in extract_includes.bat) - - # Suppress linker warnings about files with no symbols defined. - set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} /ignore:4221") - - if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - # Configure Resource Compiler - enable_language(RC) - # use English language (0x409) in resource compiler - set(rc_flags "/l0x409") - # fix rc.exe invocations because of usage of add_definitions() - set(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> ${rc_flags} <DEFINES> /fo<OBJECT> <SOURCE>") - endif() - - configure_file(version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY) -endif (MSVC) - - -get_filename_component(protobuf_source_dir ${protobuf_SOURCE_DIR} PATH) - -include_directories( - ${ZLIB_INCLUDE_DIRECTORIES} - ${protobuf_BINARY_DIR} - ${protobuf_source_dir}/src) - -if (MSVC) - # Add the "lib" prefix for generated .lib outputs. - set(LIB_PREFIX lib) -else (MSVC) - # When building with "make", "lib" prefix will be added automatically by - # the build tool. - set(LIB_PREFIX) -endif (MSVC) - -if (protobuf_UNICODE) - add_definitions(-DUNICODE -D_UNICODE) -endif (protobuf_UNICODE) - -include(libprotobuf-lite.cmake) -include(libprotobuf.cmake) -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) - enable_testing() - include(tests.cmake) -endif (protobuf_BUILD_TESTS) - -if (protobuf_BUILD_CONFORMANCE) - include(conformance.cmake) -endif (protobuf_BUILD_CONFORMANCE) - -if (protobuf_INSTALL) - include(install.cmake) -endif (protobuf_INSTALL) - -if (protobuf_BUILD_EXAMPLES) - include(examples.cmake) -endif (protobuf_BUILD_EXAMPLES) - -if(protobuf_VERBOSE) - message(STATUS "Protocol Buffers Configuring done") -endif(protobuf_VERBOSE) +include(../CMakeLists.txt)
diff --git a/cmake/README.md b/cmake/README.md index 3fee4a0..ce3e680 100644 --- a/cmake/README.md +++ b/cmake/README.md
@@ -59,7 +59,7 @@ C:\Path\to> mkdir src & cd src C:\Path\to\src> git clone -b [release_tag] https://github.com/protocolbuffers/protobuf.git -Where *[release_tag]* is a git tag like *v3.0.0-beta-1* or a branch name like *master* +Where *[release_tag]* is a git tag like *v3.0.0-beta-1* or a branch name like *main* if you want to get the latest code. Go to the project folder:
diff --git a/cmake/abseil-cpp.cmake b/cmake/abseil-cpp.cmake new file mode 100644 index 0000000..10e7e5c --- /dev/null +++ b/cmake/abseil-cpp.cmake
@@ -0,0 +1,28 @@ +if(protobuf_ABSL_PROVIDER STREQUAL "module") + if(NOT ABSL_ROOT_DIR) + set(ABSL_ROOT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/third_party/abseil-cpp) + endif() + if(EXISTS "${ABSL_ROOT_DIR}/CMakeLists.txt") + if(protobuf_INSTALL) + # When protobuf_INSTALL is enabled and Abseil will be built as a module, + # Abseil will be installed along with protobuf for convenience. + set(ABSL_ENABLE_INSTALL ON) + endif() + add_subdirectory(${ABSL_ROOT_DIR} third_party/abseil-cpp) + else() + message(WARNING "protobuf_ABSL_PROVIDER is \"module\" but ABSL_ROOT_DIR is wrong") + endif() + if(protobuf_INSTALL AND NOT _protobuf_INSTALL_SUPPORTED_FROM_MODULE) + message(WARNING "protobuf_INSTALL will be forced to FALSE because protobuf_ABSL_PROVIDER is \"module\" and CMake version (${CMAKE_VERSION}) is less than 3.13.") + set(protobuf_INSTALL FALSE) + endif() +elseif(protobuf_ABSL_PROVIDER STREQUAL "package") + # Use "CONFIG" as there is no built-in cmake module for absl. + find_package(absl REQUIRED CONFIG) +endif() +set(_protobuf_FIND_ABSL "if(NOT TARGET absl::strings)\n find_package(absl CONFIG)\nendif()") + +set(protobuf_ABSL_USED_TARGETS + absl::strings + absl::strings_internal +)
diff --git a/cmake/conformance.cmake b/cmake/conformance.cmake index b9485ff..d6c435a 100644 --- a/cmake/conformance.cmake +++ b/cmake/conformance.cmake
@@ -1,49 +1,49 @@ add_custom_command( - OUTPUT ${protobuf_source_dir}/conformance/conformance.pb.cc - 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 + OUTPUT ${protobuf_SOURCE_DIR}/conformance/conformance.pb.cc + 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 ) 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 ${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 + OUTPUT ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.cc + 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 ) add_executable(conformance_test_runner - ${protobuf_source_dir}/conformance/binary_json_conformance_suite.cc - ${protobuf_source_dir}/conformance/binary_json_conformance_suite.h - ${protobuf_source_dir}/conformance/conformance.pb.cc - ${protobuf_source_dir}/conformance/conformance_test.cc - ${protobuf_source_dir}/conformance/conformance_test_runner.cc - ${protobuf_source_dir}/conformance/third_party/jsoncpp/json.h - ${protobuf_source_dir}/conformance/third_party/jsoncpp/jsoncpp.cpp - ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc - ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc + ${protobuf_SOURCE_DIR}/conformance/binary_json_conformance_suite.cc + ${protobuf_SOURCE_DIR}/conformance/binary_json_conformance_suite.h + ${protobuf_SOURCE_DIR}/conformance/conformance.pb.cc + ${protobuf_SOURCE_DIR}/conformance/conformance_test.cc + ${protobuf_SOURCE_DIR}/conformance/conformance_test_runner.cc + ${protobuf_SOURCE_DIR}/conformance/third_party/jsoncpp/json.h + ${protobuf_SOURCE_DIR}/conformance/third_party/jsoncpp/jsoncpp.cpp + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.cc ) add_executable(conformance_cpp - ${protobuf_source_dir}/conformance/conformance.pb.cc - ${protobuf_source_dir}/conformance/conformance_cpp.cc - ${protobuf_source_dir}/src/google/protobuf/test_messages_proto2.pb.cc - ${protobuf_source_dir}/src/google/protobuf/test_messages_proto3.pb.cc + ${protobuf_SOURCE_DIR}/conformance/conformance.pb.cc + ${protobuf_SOURCE_DIR}/conformance/conformance_cpp.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto2.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_messages_proto3.pb.cc ) target_include_directories( conformance_test_runner - PUBLIC ${protobuf_source_dir}/conformance) + PUBLIC ${protobuf_SOURCE_DIR}/conformance) target_include_directories( conformance_cpp - PUBLIC ${protobuf_source_dir}/conformance) + PUBLIC ${protobuf_SOURCE_DIR}/conformance) target_link_libraries(conformance_test_runner libprotobuf) target_link_libraries(conformance_cpp libprotobuf)
diff --git a/cmake/examples.cmake b/cmake/examples.cmake index e5cad63..3b83d2b 100644 --- a/cmake/examples.cmake +++ b/cmake/examples.cmake
@@ -2,7 +2,7 @@ message(STATUS "Protocol Buffers Examples Configuring...") endif() -get_filename_component(examples_dir "../examples" ABSOLUTE) +get_filename_component(examples_dir "${protobuf_SOURCE_DIR}/examples" ABSOLUTE) if(protobuf_VERBOSE) message(STATUS "Protocol Buffers Examples Configuring done")
diff --git a/cmake/extract_includes.bat.in b/cmake/extract_includes.bat.in index 8e910e9..41d4556 100644 --- a/cmake/extract_includes.bat.in +++ b/cmake/extract_includes.bat.in
@@ -22,18 +22,18 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\arenaz_sampler.h" include\google\protobuf\arenaz_sampler.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\code_generator.h" include\google\protobuf\compiler\code_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\command_line_interface.h" include\google\protobuf\compiler\command_line_interface.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\cpp_file.h" include\google\protobuf\compiler\cpp\cpp_file.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\cpp_generator.h" include\google\protobuf\compiler\cpp\cpp_generator.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\cpp_helpers.h" include\google\protobuf\compiler\cpp\cpp_helpers.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\cpp_names.h" include\google\protobuf\compiler\cpp\cpp_names.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\file.h" include\google\protobuf\compiler\cpp\file.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\generator.h" include\google\protobuf\compiler\cpp\generator.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\helpers.h" include\google\protobuf\compiler\cpp\helpers.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\names.h" include\google\protobuf\compiler\cpp\names.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_doc_comment.h" include\google\protobuf\compiler\csharp\csharp_doc_comment.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_generator.h" include\google\protobuf\compiler\csharp\csharp_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_names.h" include\google\protobuf\compiler\csharp\csharp_names.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_options.h" include\google\protobuf\compiler\csharp\csharp_options.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\importer.h" include\google\protobuf\compiler\importer.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_generator.h" include\google\protobuf\compiler\java\java_generator.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_kotlin_generator.h" include\google\protobuf\compiler\java\java_kotlin_generator.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_names.h" include\google\protobuf\compiler\java\java_names.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\generator.h" include\google\protobuf\compiler\java\generator.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\kotlin_generator.h" include\google\protobuf\compiler\java\kotlin_generator.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\names.h" include\google\protobuf\compiler\java\names.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\js\js_generator.h" include\google\protobuf\compiler\js\js_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_generator.h" include\google\protobuf\compiler\objectivec\objectivec_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\objectivec\objectivec_helpers.h" include\google\protobuf\compiler\objectivec\objectivec_helpers.h @@ -41,9 +41,8 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\php\php_generator.h" include\google\protobuf\compiler\php\php_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.h" include\google\protobuf\compiler\plugin.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\plugin.pb.h" include\google\protobuf\compiler\plugin.pb.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\python\python_generator.h" include\google\protobuf\compiler\python\python_generator.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\python\python_pyi_generator.h" include\google\protobuf\compiler\python\python_pyi_generator.h -copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\python\python_helpers.h" include\google\protobuf\compiler\python\python_helpers.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\python\generator.h" include\google\protobuf\compiler\python\generator.h +copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\python\pyi_generator.h" include\google\protobuf\compiler\python\pyi_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\ruby\ruby_generator.h" include\google\protobuf\compiler\ruby\ruby_generator.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor.h" include\google\protobuf\descriptor.h copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor.pb.h" include\google\protobuf\descriptor.pb.h
diff --git a/cmake/install.cmake b/cmake/install.cmake index 4e1c5de..c1f6f4a 100644 --- a/cmake/install.cmake +++ b/cmake/install.cmake
@@ -1,8 +1,8 @@ include(GNUInstallDirs) -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/protobuf.pc.cmake +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/protobuf.pc.cmake ${CMAKE_CURRENT_BINARY_DIR}/protobuf.pc @ONLY) -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/protobuf-lite.pc.cmake +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/protobuf-lite.pc.cmake ${CMAKE_CURRENT_BINARY_DIR}/protobuf-lite.pc @ONLY) set(_protobuf_libraries libprotobuf-lite libprotobuf) @@ -13,7 +13,7 @@ foreach(_library ${_protobuf_libraries}) set_property(TARGET ${_library} PROPERTY INTERFACE_INCLUDE_DIRECTORIES - $<BUILD_INTERFACE:${protobuf_source_dir}/src> + $<BUILD_INTERFACE:${protobuf_SOURCE_DIR}/src> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>) if (UNIX AND NOT APPLE) set_property(TARGET ${_library} @@ -43,15 +43,15 @@ install(FILES ${CMAKE_CURRENT_BINARY_DIR}/protobuf.pc ${CMAKE_CURRENT_BINARY_DIR}/protobuf-lite.pc DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") -file(STRINGS extract_includes.bat.in _extract_strings +file(STRINGS ${protobuf_SOURCE_DIR}/cmake/extract_includes.bat.in _extract_strings REGEX "^copy") foreach(_extract_string ${_extract_strings}) string(REGEX REPLACE "^.* .+ include\\\\(.+)$" "\\1" _header ${_extract_string}) string(REPLACE "\\" "/" _header ${_header}) - get_filename_component(_extract_from "${protobuf_SOURCE_DIR}/../src/${_header}" ABSOLUTE) + get_filename_component(_extract_from "${protobuf_SOURCE_DIR}/src/${_header}" ABSOLUTE) get_filename_component(_extract_name ${_header} NAME) - get_filename_component(_extract_to "${CMAKE_INSTALL_INCLUDEDIR}/${_header}" PATH) + get_filename_component(_extract_to "${CMAKE_INSTALL_INCLUDEDIR}/${_header}" DIRECTORY) if(EXISTS "${_extract_from}") install(FILES "${_extract_from}" DESTINATION "${_extract_to}" @@ -84,19 +84,19 @@ endfunction() # Install well-known type proto files -_protobuf_auto_list("../src/Makefile.am" nobase_dist_proto_DATA) +_protobuf_auto_list("${protobuf_SOURCE_DIR}/src/Makefile.am" nobase_dist_proto_DATA) foreach(_file ${nobase_dist_proto_DATA}) - get_filename_component(_file_from "../src/${_file}" ABSOLUTE) + get_filename_component(_file_from "${protobuf_SOURCE_DIR}/src/${_file}" ABSOLUTE) get_filename_component(_file_name ${_file} NAME) - get_filename_component(_file_path ${_file} PATH) + get_filename_component(_dir ${_file} DIRECTORY) if(EXISTS "${_file_from}") install(FILES "${_file_from}" - DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${_file_path}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${_dir}" COMPONENT protobuf-protos RENAME "${_file_name}") else() message(AUTHOR_WARNING "The file \"${_file_from}\" is listed in " - "\"${protobuf_SOURCE_DIR}/../src/Makefile.am\" as nobase_dist_proto_DATA " + "\"${protobuf_SOURCE_DIR}/src/Makefile.am\" as nobase_dist_proto_DATA " "but there not exists. The file will not be installed.") endif() endforeach() @@ -114,13 +114,13 @@ mark_as_advanced(CMAKE_INSTALL_CMAKEDIR) mark_as_advanced(CMAKE_INSTALL_EXAMPLEDIR) -configure_file(protobuf-config.cmake.in +configure_file(${protobuf_SOURCE_DIR}/cmake/protobuf-config.cmake.in ${CMAKE_INSTALL_CMAKEDIR}/protobuf-config.cmake @ONLY) -configure_file(protobuf-config-version.cmake.in +configure_file(${protobuf_SOURCE_DIR}/cmake/protobuf-config-version.cmake.in ${CMAKE_INSTALL_CMAKEDIR}/protobuf-config-version.cmake @ONLY) -configure_file(protobuf-module.cmake.in +configure_file(${protobuf_SOURCE_DIR}/cmake/protobuf-module.cmake.in ${CMAKE_INSTALL_CMAKEDIR}/protobuf-module.cmake @ONLY) -configure_file(protobuf-options.cmake +configure_file(${protobuf_SOURCE_DIR}/cmake/protobuf-options.cmake ${CMAKE_INSTALL_CMAKEDIR}/protobuf-options.cmake @ONLY) # Allows the build directory to be used as a find directory. @@ -128,29 +128,25 @@ if (protobuf_BUILD_PROTOC_BINARIES) export(TARGETS libprotobuf-lite libprotobuf libprotoc protoc NAMESPACE protobuf:: - FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake + FILE ${CMAKE_CURRENT_BINARY_DIR}/cmake/protobuf/protobuf-targets.cmake ) else (protobuf_BUILD_PROTOC_BINARIES) export(TARGETS libprotobuf-lite libprotobuf NAMESPACE protobuf:: - FILE ${CMAKE_INSTALL_CMAKEDIR}/protobuf-targets.cmake + FILE ${CMAKE_CURRENT_BINARY_DIR}/cmake/protobuf/protobuf-targets.cmake ) endif (protobuf_BUILD_PROTOC_BINARIES) install(EXPORT protobuf-targets + FILE protobuf-targets.cmake DESTINATION "${CMAKE_INSTALL_CMAKEDIR}" NAMESPACE protobuf:: - COMPONENT protobuf-export) - -install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_INSTALL_CMAKEDIR}/ - DESTINATION "${CMAKE_INSTALL_CMAKEDIR}" COMPONENT protobuf-export - PATTERN protobuf-targets.cmake EXCLUDE ) option(protobuf_INSTALL_EXAMPLES "Install the examples folder" OFF) if(protobuf_INSTALL_EXAMPLES) - install(DIRECTORY ../examples/ + install(DIRECTORY examples/ DESTINATION "${CMAKE_INSTALL_EXAMPLEDIR}" COMPONENT protobuf-examples) endif()
diff --git a/cmake/libprotobuf-lite.cmake b/cmake/libprotobuf-lite.cmake index 9376099..0f32955 100644 --- a/cmake/libprotobuf-lite.cmake +++ b/cmake/libprotobuf-lite.cmake
@@ -1,88 +1,89 @@ set(libprotobuf_lite_files - ${protobuf_source_dir}/src/google/protobuf/any_lite.cc - ${protobuf_source_dir}/src/google/protobuf/arena.cc - ${protobuf_source_dir}/src/google/protobuf/arenastring.cc - ${protobuf_source_dir}/src/google/protobuf/arenaz_sampler.cc - ${protobuf_source_dir}/src/google/protobuf/extension_set.cc - ${protobuf_source_dir}/src/google/protobuf/generated_enum_util.cc - ${protobuf_source_dir}/src/google/protobuf/generated_message_tctable_lite.cc - ${protobuf_source_dir}/src/google/protobuf/generated_message_util.cc - ${protobuf_source_dir}/src/google/protobuf/implicit_weak_message.cc - ${protobuf_source_dir}/src/google/protobuf/inlined_string_field.cc - ${protobuf_source_dir}/src/google/protobuf/io/coded_stream.cc - ${protobuf_source_dir}/src/google/protobuf/io/io_win32.cc - ${protobuf_source_dir}/src/google/protobuf/io/strtod.cc - ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream.cc - ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl.cc - ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.cc - ${protobuf_source_dir}/src/google/protobuf/map.cc - ${protobuf_source_dir}/src/google/protobuf/message_lite.cc - ${protobuf_source_dir}/src/google/protobuf/parse_context.cc - ${protobuf_source_dir}/src/google/protobuf/repeated_field.cc - ${protobuf_source_dir}/src/google/protobuf/repeated_ptr_field.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/common.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/int128.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/status.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/statusor.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/stringprintf.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/structurally_valid.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/strutil.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/time.cc - ${protobuf_source_dir}/src/google/protobuf/wire_format_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/any_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/arena.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/arenastring.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/arenaz_sampler.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/extension_set.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_enum_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_tctable_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/implicit_weak_message.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/inlined_string_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/coded_stream.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/io_win32.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/strtod.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/zero_copy_stream.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/zero_copy_stream_impl.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/zero_copy_stream_impl_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/map.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/message_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/parse_context.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/repeated_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/repeated_ptr_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/bytestream.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/common.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/int128.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/status.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/statusor.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringpiece.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringprintf.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/structurally_valid.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/strutil.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/time.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format_lite.cc ) set(libprotobuf_lite_includes - ${protobuf_source_dir}/src/google/protobuf/any.h - ${protobuf_source_dir}/src/google/protobuf/arena.h - ${protobuf_source_dir}/src/google/protobuf/arena_impl.h - ${protobuf_source_dir}/src/google/protobuf/arenastring.h - ${protobuf_source_dir}/src/google/protobuf/arenaz_sampler.h - ${protobuf_source_dir}/src/google/protobuf/explicitly_constructed.h - ${protobuf_source_dir}/src/google/protobuf/extension_set.h - ${protobuf_source_dir}/src/google/protobuf/extension_set_inl.h - ${protobuf_source_dir}/src/google/protobuf/generated_enum_util.h - ${protobuf_source_dir}/src/google/protobuf/generated_message_tctable_decl.h - ${protobuf_source_dir}/src/google/protobuf/generated_message_tctable_impl.h - ${protobuf_source_dir}/src/google/protobuf/generated_message_util.h - ${protobuf_source_dir}/src/google/protobuf/has_bits.h - ${protobuf_source_dir}/src/google/protobuf/implicit_weak_message.h - ${protobuf_source_dir}/src/google/protobuf/inlined_string_field.h - ${protobuf_source_dir}/src/google/protobuf/io/coded_stream.h - ${protobuf_source_dir}/src/google/protobuf/io/io_win32.h - ${protobuf_source_dir}/src/google/protobuf/io/strtod.h - ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream.h - ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl.h - ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_impl_lite.h - ${protobuf_source_dir}/src/google/protobuf/map.h - ${protobuf_source_dir}/src/google/protobuf/map_entry_lite.h - ${protobuf_source_dir}/src/google/protobuf/map_field_lite.h - ${protobuf_source_dir}/src/google/protobuf/map_type_handler.h - ${protobuf_source_dir}/src/google/protobuf/message_lite.h - ${protobuf_source_dir}/src/google/protobuf/metadata_lite.h - ${protobuf_source_dir}/src/google/protobuf/parse_context.h - ${protobuf_source_dir}/src/google/protobuf/port.h - ${protobuf_source_dir}/src/google/protobuf/repeated_field.h - ${protobuf_source_dir}/src/google/protobuf/repeated_ptr_field.h - ${protobuf_source_dir}/src/google/protobuf/stubs/bytestream.h - ${protobuf_source_dir}/src/google/protobuf/stubs/callback.h - ${protobuf_source_dir}/src/google/protobuf/stubs/casts.h - ${protobuf_source_dir}/src/google/protobuf/stubs/common.h - ${protobuf_source_dir}/src/google/protobuf/stubs/hash.h - ${protobuf_source_dir}/src/google/protobuf/stubs/logging.h - ${protobuf_source_dir}/src/google/protobuf/stubs/macros.h - ${protobuf_source_dir}/src/google/protobuf/stubs/map_util.h - ${protobuf_source_dir}/src/google/protobuf/stubs/mutex.h - ${protobuf_source_dir}/src/google/protobuf/stubs/once.h - ${protobuf_source_dir}/src/google/protobuf/stubs/platform_macros.h - ${protobuf_source_dir}/src/google/protobuf/stubs/port.h - ${protobuf_source_dir}/src/google/protobuf/stubs/status.h - ${protobuf_source_dir}/src/google/protobuf/stubs/stl_util.h - ${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece.h - ${protobuf_source_dir}/src/google/protobuf/stubs/strutil.h - ${protobuf_source_dir}/src/google/protobuf/stubs/template_util.h - ${protobuf_source_dir}/src/google/protobuf/wire_format_lite.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/any.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/arena.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/arena_impl.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/arenastring.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/arenaz_sampler.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/endian.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/explicitly_constructed.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/extension_set.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/extension_set_inl.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_enum_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_tctable_decl.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_tctable_impl.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/has_bits.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/implicit_weak_message.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/inlined_string_field.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/coded_stream.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/io_win32.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/strtod.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/zero_copy_stream.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/zero_copy_stream_impl.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/zero_copy_stream_impl_lite.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/map.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_entry_lite.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_field_lite.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_type_handler.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/message_lite.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/metadata_lite.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/parse_context.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/port.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/repeated_field.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/repeated_ptr_field.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/bytestream.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/callback.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/casts.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/common.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/hash.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/logging.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/macros.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/map_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/mutex.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/once.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/platform_macros.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/port.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/status.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stl_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringpiece.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/strutil.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/template_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format_lite.h ) if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") @@ -95,21 +96,24 @@ ${libprotobuf_lite_files} ${libprotobuf_lite_includes} ${libprotobuf_lite_rc_files}) if(protobuf_HAVE_LD_VERSION_SCRIPT) if(${CMAKE_VERSION} VERSION_GREATER 3.13 OR ${CMAKE_VERSION} VERSION_EQUAL 3.13) - target_link_options(libprotobuf-lite PRIVATE -Wl,--version-script=${protobuf_source_dir}/src/libprotobuf-lite.map) + target_link_options(libprotobuf-lite PRIVATE -Wl,--version-script=${protobuf_SOURCE_DIR}/src/libprotobuf-lite.map) elseif(protobuf_BUILD_SHARED_LIBS) - target_link_libraries(libprotobuf-lite PRIVATE -Wl,--version-script=${protobuf_source_dir}/src/libprotobuf-lite.map) + target_link_libraries(libprotobuf-lite PRIVATE -Wl,--version-script=${protobuf_SOURCE_DIR}/src/libprotobuf-lite.map) endif() set_target_properties(libprotobuf-lite PROPERTIES - LINK_DEPENDS ${protobuf_source_dir}/src/libprotobuf-lite.map) + LINK_DEPENDS ${protobuf_SOURCE_DIR}/src/libprotobuf-lite.map) endif() target_link_libraries(libprotobuf-lite PRIVATE ${CMAKE_THREAD_LIBS_INIT}) +target_include_directories(libprotobuf-lite + PRIVATE ${ABSL_ROOT_DIR} +) if(protobuf_LINK_LIBATOMIC) target_link_libraries(libprotobuf-lite PRIVATE atomic) endif() if(${CMAKE_SYSTEM_NAME} STREQUAL "Android") target_link_libraries(libprotobuf-lite PRIVATE log) endif() -target_include_directories(libprotobuf-lite PUBLIC ${protobuf_source_dir}/src) +target_include_directories(libprotobuf-lite PUBLIC ${protobuf_SOURCE_DIR}/src) if(protobuf_BUILD_SHARED_LIBS) target_compile_definitions(libprotobuf-lite PUBLIC PROTOBUF_USE_DLLS
diff --git a/cmake/libprotobuf.cmake b/cmake/libprotobuf.cmake index 448baea..49f31c5 100644 --- a/cmake/libprotobuf.cmake +++ b/cmake/libprotobuf.cmake
@@ -1,102 +1,102 @@ set(libprotobuf_files - ${protobuf_source_dir}/src/google/protobuf/any.cc - ${protobuf_source_dir}/src/google/protobuf/any.pb.cc - ${protobuf_source_dir}/src/google/protobuf/api.pb.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/importer.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/parser.cc - ${protobuf_source_dir}/src/google/protobuf/descriptor.cc - ${protobuf_source_dir}/src/google/protobuf/descriptor.pb.cc - ${protobuf_source_dir}/src/google/protobuf/descriptor_database.cc - ${protobuf_source_dir}/src/google/protobuf/duration.pb.cc - ${protobuf_source_dir}/src/google/protobuf/dynamic_message.cc - ${protobuf_source_dir}/src/google/protobuf/empty.pb.cc - ${protobuf_source_dir}/src/google/protobuf/extension_set_heavy.cc - ${protobuf_source_dir}/src/google/protobuf/field_mask.pb.cc - ${protobuf_source_dir}/src/google/protobuf/generated_message_bases.cc - ${protobuf_source_dir}/src/google/protobuf/generated_message_reflection.cc - ${protobuf_source_dir}/src/google/protobuf/generated_message_tctable_full.cc - ${protobuf_source_dir}/src/google/protobuf/io/gzip_stream.cc - ${protobuf_source_dir}/src/google/protobuf/io/printer.cc - ${protobuf_source_dir}/src/google/protobuf/io/tokenizer.cc - ${protobuf_source_dir}/src/google/protobuf/map_field.cc - ${protobuf_source_dir}/src/google/protobuf/message.cc - ${protobuf_source_dir}/src/google/protobuf/reflection_internal.h - ${protobuf_source_dir}/src/google/protobuf/reflection_ops.cc - ${protobuf_source_dir}/src/google/protobuf/service.cc - ${protobuf_source_dir}/src/google/protobuf/source_context.pb.cc - ${protobuf_source_dir}/src/google/protobuf/struct.pb.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/substitute.cc - ${protobuf_source_dir}/src/google/protobuf/text_format.cc - ${protobuf_source_dir}/src/google/protobuf/timestamp.pb.cc - ${protobuf_source_dir}/src/google/protobuf/type.pb.cc - ${protobuf_source_dir}/src/google/protobuf/unknown_field_set.cc - ${protobuf_source_dir}/src/google/protobuf/util/delimited_message_util.cc - ${protobuf_source_dir}/src/google/protobuf/util/field_comparator.cc - ${protobuf_source_dir}/src/google/protobuf/util/field_mask_util.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/datapiece.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/default_value_objectwriter.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/error_listener.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/field_mask_utility.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/json_escaping.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/json_objectwriter.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/json_stream_parser.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/object_writer.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/proto_writer.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/protostream_objectsource.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/protostream_objectwriter.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/type_info.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/utility.cc - ${protobuf_source_dir}/src/google/protobuf/util/json_util.cc - ${protobuf_source_dir}/src/google/protobuf/util/message_differencer.cc - ${protobuf_source_dir}/src/google/protobuf/util/time_util.cc - ${protobuf_source_dir}/src/google/protobuf/util/type_resolver_util.cc - ${protobuf_source_dir}/src/google/protobuf/wire_format.cc - ${protobuf_source_dir}/src/google/protobuf/wrappers.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/any.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/any.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/api.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/importer.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/parser.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor_database.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/duration.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/dynamic_message.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/empty.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/extension_set_heavy.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/field_mask.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_bases.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_reflection.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_tctable_full.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/gzip_stream.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/printer.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/tokenizer.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/message.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_ops.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/service.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/source_context.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/struct.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/substitute.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/text_format.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/timestamp.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/type.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/unknown_field_set.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/delimited_message_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/field_comparator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/field_mask_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/datapiece.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/default_value_objectwriter.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/error_listener.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/field_mask_utility.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/json_escaping.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/json_objectwriter.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/json_stream_parser.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/object_writer.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/proto_writer.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/protostream_objectsource.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/protostream_objectwriter.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/type_info.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/utility.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/json_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/message_differencer.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/time_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/type_resolver_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/wrappers.pb.cc ) set(libprotobuf_includes - ${protobuf_source_dir}/src/google/protobuf/any.pb.h - ${protobuf_source_dir}/src/google/protobuf/api.pb.h - ${protobuf_source_dir}/src/google/protobuf/compiler/importer.h - ${protobuf_source_dir}/src/google/protobuf/compiler/parser.h - ${protobuf_source_dir}/src/google/protobuf/descriptor.h - ${protobuf_source_dir}/src/google/protobuf/descriptor.pb.h - ${protobuf_source_dir}/src/google/protobuf/descriptor_database.h - ${protobuf_source_dir}/src/google/protobuf/duration.pb.h - ${protobuf_source_dir}/src/google/protobuf/dynamic_message.h - ${protobuf_source_dir}/src/google/protobuf/empty.pb.h - ${protobuf_source_dir}/src/google/protobuf/field_access_listener.h - ${protobuf_source_dir}/src/google/protobuf/field_mask.pb.h - ${protobuf_source_dir}/src/google/protobuf/generated_enum_reflection.h - ${protobuf_source_dir}/src/google/protobuf/generated_message_bases.h - ${protobuf_source_dir}/src/google/protobuf/generated_message_reflection.h - ${protobuf_source_dir}/src/google/protobuf/io/gzip_stream.h - ${protobuf_source_dir}/src/google/protobuf/io/printer.h - ${protobuf_source_dir}/src/google/protobuf/io/tokenizer.h - ${protobuf_source_dir}/src/google/protobuf/map_entry.h - ${protobuf_source_dir}/src/google/protobuf/map_field.h - ${protobuf_source_dir}/src/google/protobuf/map_field_inl.h - ${protobuf_source_dir}/src/google/protobuf/message.h - ${protobuf_source_dir}/src/google/protobuf/metadata.h - ${protobuf_source_dir}/src/google/protobuf/reflection.h - ${protobuf_source_dir}/src/google/protobuf/reflection_ops.h - ${protobuf_source_dir}/src/google/protobuf/service.h - ${protobuf_source_dir}/src/google/protobuf/source_context.pb.h - ${protobuf_source_dir}/src/google/protobuf/struct.pb.h - ${protobuf_source_dir}/src/google/protobuf/text_format.h - ${protobuf_source_dir}/src/google/protobuf/timestamp.pb.h - ${protobuf_source_dir}/src/google/protobuf/type.pb.h - ${protobuf_source_dir}/src/google/protobuf/unknown_field_set.h - ${protobuf_source_dir}/src/google/protobuf/util/delimited_message_util.h - ${protobuf_source_dir}/src/google/protobuf/util/field_comparator.h - ${protobuf_source_dir}/src/google/protobuf/util/field_mask_util.h - ${protobuf_source_dir}/src/google/protobuf/util/json_util.h - ${protobuf_source_dir}/src/google/protobuf/util/message_differencer.h - ${protobuf_source_dir}/src/google/protobuf/util/time_util.h - ${protobuf_source_dir}/src/google/protobuf/util/type_resolver.h - ${protobuf_source_dir}/src/google/protobuf/util/type_resolver_util.h - ${protobuf_source_dir}/src/google/protobuf/wire_format.h - ${protobuf_source_dir}/src/google/protobuf/wrappers.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/any.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/api.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/importer.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/parser.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor_database.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/duration.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/dynamic_message.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/empty.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/field_access_listener.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/field_mask.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_enum_reflection.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_bases.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_reflection.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/gzip_stream.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/printer.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/tokenizer.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_entry.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_field.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_field_inl.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/message.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/metadata.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_internal.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_ops.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/service.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/source_context.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/struct.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/text_format.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/timestamp.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/type.pb.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/unknown_field_set.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/delimited_message_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/field_comparator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/field_mask_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/json_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/message_differencer.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/time_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/type_resolver.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/type_resolver_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/wrappers.pb.h ) if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") @@ -109,14 +109,17 @@ ${libprotobuf_lite_files} ${libprotobuf_files} ${libprotobuf_includes} ${libprotobuf_rc_files}) if(protobuf_HAVE_LD_VERSION_SCRIPT) if(${CMAKE_VERSION} VERSION_GREATER 3.13 OR ${CMAKE_VERSION} VERSION_EQUAL 3.13) - target_link_options(libprotobuf PRIVATE -Wl,--version-script=${protobuf_source_dir}/src/libprotobuf.map) + target_link_options(libprotobuf PRIVATE -Wl,--version-script=${protobuf_SOURCE_DIR}/src/libprotobuf.map) elseif(protobuf_BUILD_SHARED_LIBS) - target_link_libraries(libprotobuf PRIVATE -Wl,--version-script=${protobuf_source_dir}/src/libprotobuf.map) + target_link_libraries(libprotobuf PRIVATE -Wl,--version-script=${protobuf_SOURCE_DIR}/src/libprotobuf.map) endif() set_target_properties(libprotobuf PROPERTIES - LINK_DEPENDS ${protobuf_source_dir}/src/libprotobuf.map) + LINK_DEPENDS ${protobuf_SOURCE_DIR}/src/libprotobuf.map) endif() target_link_libraries(libprotobuf PRIVATE ${CMAKE_THREAD_LIBS_INIT}) +target_include_directories(libprotobuf + PRIVATE ${ABSL_ROOT_DIR} +) if(protobuf_WITH_ZLIB) target_link_libraries(libprotobuf PRIVATE ${ZLIB_LIBRARIES}) endif() @@ -126,7 +129,7 @@ if(${CMAKE_SYSTEM_NAME} STREQUAL "Android") target_link_libraries(libprotobuf PRIVATE log) endif() -target_include_directories(libprotobuf PUBLIC ${protobuf_source_dir}/src) +target_include_directories(libprotobuf PUBLIC ${protobuf_SOURCE_DIR}/src) if(protobuf_BUILD_SHARED_LIBS) target_compile_definitions(libprotobuf PUBLIC PROTOBUF_USE_DLLS
diff --git a/cmake/libprotoc.cmake b/cmake/libprotoc.cmake index 92dff13..b098b94 100644 --- a/cmake/libprotoc.cmake +++ b/cmake/libprotoc.cmake
@@ -1,126 +1,113 @@ set(libprotoc_files - ${protobuf_source_dir}/src/google/protobuf/compiler/code_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/command_line_interface.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_enum_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_extension.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_file.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_helpers.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_map_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_message_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_service.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_string_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_field_base.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_helpers.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_map_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_context.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_doc_comment.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_field_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_extension.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_extension_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_file.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator_factory.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_helpers.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_kotlin_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_map_field_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_builder.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_builder_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_field_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_message_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_name_resolver.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_primitive_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_primitive_field_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_service.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_shared_code_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_string_field_lite.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/js/js_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/js/well_known_types_embed.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_enum_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_extension.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_extension.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_file.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_file.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_map_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_message_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_nsobject_methods.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_oneof.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.h - ${protobuf_source_dir}/src/google/protobuf/compiler/php/php_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.pb.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_helpers.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_pyi_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/subprocess.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/zip_writer.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/code_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/command_line_interface.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/enum.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/enum_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/extension.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/file.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/helpers.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/map_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/message.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/message_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/padding_optimizer.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/parse_function_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/primitive_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/service.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/string_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_doc_comment.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_enum.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_enum_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_field_base.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_helpers.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_map_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_message.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_message_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_reflection_class.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/context.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/doc_comment.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/enum.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/enum_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/enum_field_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/enum_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/extension.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/extension_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/file.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/generator_factory.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/helpers.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/kotlin_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/map_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/map_field_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/message.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/message_builder.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/message_builder_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/message_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/message_field_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/message_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/name_resolver.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/primitive_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/primitive_field_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/service.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/shared_code_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/string_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/string_field_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/js/js_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/js/well_known_types_embed.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_enum.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_enum_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_extension.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_file.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_helpers.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_map_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_message.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_message_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_oneof.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_primitive_field.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/php/php_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/plugin.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/plugin.pb.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/python/generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/python/helpers.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/python/pyi_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/ruby/ruby_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/subprocess.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/zip_writer.cc ) set(libprotoc_headers - ${protobuf_source_dir}/src/google/protobuf/compiler/code_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/command_line_interface.h - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_file.h - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_helpers.h - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_names.h - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_doc_comment.h - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_names.h - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_options.h - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_kotlin_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_names.h - ${protobuf_source_dir}/src/google/protobuf/compiler/js/js_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_helpers.h - ${protobuf_source_dir}/src/google/protobuf/compiler/php/php_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/plugin.h - ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_pyi_generator.h - ${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/code_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/command_line_interface.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/file.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/helpers.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/names.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_doc_comment.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_names.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_options.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/kotlin_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/names.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/js/js_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_helpers.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/php/php_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/plugin.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/python/generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/python/pyi_generator.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/ruby/ruby_generator.h ) if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") @@ -133,14 +120,17 @@ ${libprotoc_files} ${libprotoc_headers} ${libprotoc_rc_files}) if(protobuf_HAVE_LD_VERSION_SCRIPT) if(${CMAKE_VERSION} VERSION_GREATER 3.13 OR ${CMAKE_VERSION} VERSION_EQUAL 3.13) - target_link_options(libprotoc PRIVATE -Wl,--version-script=${protobuf_source_dir}/src/libprotoc.map) + target_link_options(libprotoc PRIVATE -Wl,--version-script=${protobuf_SOURCE_DIR}/src/libprotoc.map) elseif(protobuf_BUILD_SHARED_LIBS) - target_link_libraries(libprotoc PRIVATE -Wl,--version-script=${protobuf_source_dir}/src/libprotoc.map) + target_link_libraries(libprotoc PRIVATE -Wl,--version-script=${protobuf_SOURCE_DIR}/src/libprotoc.map) endif() set_target_properties(libprotoc PROPERTIES - LINK_DEPENDS ${protobuf_source_dir}/src/libprotoc.map) + LINK_DEPENDS ${protobuf_SOURCE_DIR}/src/libprotoc.map) endif() target_link_libraries(libprotoc PRIVATE libprotobuf) +target_include_directories(libprotoc + PRIVATE ${ABSL_ROOT_DIR} +) if(protobuf_BUILD_SHARED_LIBS) target_compile_definitions(libprotoc PUBLIC PROTOBUF_USE_DLLS
diff --git a/cmake/protobuf-config.cmake.in b/cmake/protobuf-config.cmake.in index b433209..597f588 100644 --- a/cmake/protobuf-config.cmake.in +++ b/cmake/protobuf-config.cmake.in
@@ -3,6 +3,7 @@ # Depend packages @_protobuf_FIND_ZLIB@ +@_protobuf_FIND_ABSL@ # Imported targets include("${CMAKE_CURRENT_LIST_DIR}/protobuf-targets.cmake") @@ -84,10 +85,10 @@ # Create an include path for each file specified foreach(_file ${protobuf_generate_PROTOS}) get_filename_component(_abs_file ${_file} ABSOLUTE) - get_filename_component(_abs_path ${_abs_file} PATH) - list(FIND _protobuf_include_path ${_abs_path} _contains_already) + get_filename_component(_abs_dir ${_abs_file} DIRECTORY) + list(FIND _protobuf_include_path ${_abs_dir} _contains_already) if(${_contains_already} EQUAL -1) - list(APPEND _protobuf_include_path -I ${_abs_path}) + list(APPEND _protobuf_include_path -I ${_abs_dir}) endif() endforeach() endif()
diff --git a/cmake/protoc.cmake b/cmake/protoc.cmake index c86d662..7d04196 100644 --- a/cmake/protoc.cmake +++ b/cmake/protoc.cmake
@@ -1,5 +1,5 @@ set(protoc_files - ${protobuf_source_dir}/src/google/protobuf/compiler/main.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/main.cc ) if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") @@ -9,7 +9,11 @@ endif() add_executable(protoc ${protoc_files} ${protoc_rc_files}) -target_link_libraries(protoc libprotoc libprotobuf) +target_link_libraries(protoc + libprotoc + libprotobuf + ${protobuf_ABSL_USED_TARGETS} +) add_executable(protobuf::protoc ALIAS protoc) set_target_properties(protoc PROPERTIES
diff --git a/cmake/tests.cmake b/cmake/tests.cmake index 0b0e1be..04b013d 100644 --- a/cmake/tests.cmake +++ b/cmake/tests.cmake
@@ -1,5 +1,7 @@ option(protobuf_USE_EXTERNAL_GTEST "Use external Google Test (i.e. not the one in third_party/googletest)" OFF) +option(protobuf_TEST_XML_OUTDIR "Output directory for XML logs from tests." "") + option(protobuf_ABSOLUTE_TEST_PLUGIN_PATH "Using absolute test_plugin path in tests" ON) mark_as_advanced(protobuf_ABSOLUTE_TEST_PLUGIN_PATH) @@ -7,7 +9,7 @@ if (protobuf_USE_EXTERNAL_GTEST) find_package(GTest REQUIRED) else() - if (NOT EXISTS "${PROJECT_SOURCE_DIR}/../third_party/googletest/CMakeLists.txt") + if (NOT EXISTS "${protobuf_SOURCE_DIR}/third_party/googletest/CMakeLists.txt") message(FATAL_ERROR "Cannot find third_party/googletest directory that's needed to " "build tests. If you use git, make sure you have cloned submodules:\n" @@ -16,9 +18,10 @@ " cmake -Dprotobuf_BUILD_TESTS=OFF\n") endif() - set(googlemock_source_dir "${protobuf_source_dir}/third_party/googletest/googlemock") - set(googletest_source_dir "${protobuf_source_dir}/third_party/googletest/googletest") + set(googlemock_source_dir "${protobuf_SOURCE_DIR}/third_party/googletest/googlemock") + set(googletest_source_dir "${protobuf_SOURCE_DIR}/third_party/googletest/googletest") include_directories( + ${ABSL_ROOT_DIR} ${googlemock_source_dir} ${googletest_source_dir} ${googletest_source_dir}/include @@ -46,8 +49,8 @@ set(tests_protos google/protobuf/any_test.proto - google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto - google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto + google/protobuf/compiler/cpp/test_bad_identifiers.proto + google/protobuf/compiler/cpp/test_large_enum_value.proto google/protobuf/map_proto2_unittest.proto google/protobuf/map_unittest.proto google/protobuf/unittest.proto @@ -56,6 +59,7 @@ google/protobuf/unittest_drop_unknown_fields.proto google/protobuf/unittest_embed_optimize_for.proto google/protobuf/unittest_empty.proto + google/protobuf/unittest_enormous_descriptor.proto google/protobuf/unittest_import.proto google/protobuf/unittest_import_public.proto google/protobuf/unittest_lazy_dependencies.proto @@ -95,11 +99,11 @@ get_filename_component(dirname ${filename} PATH) get_filename_component(basename ${filename} NAME_WE) add_custom_command( - OUTPUT ${protobuf_source_dir}/src/${dirname}/${basename}.pb.cc - 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 + OUTPUT ${protobuf_SOURCE_DIR}/src/${dirname}/${basename}.pb.cc + 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) @@ -109,7 +113,7 @@ compile_proto_file(${proto_file}) string(REPLACE .proto .pb.cc pb_file ${proto_file}) set(lite_test_proto_files ${lite_test_proto_files} - ${protobuf_source_dir}/src/${pb_file}) + ${protobuf_SOURCE_DIR}/src/${pb_file}) endforeach(proto_file) set(tests_proto_files) @@ -117,104 +121,113 @@ compile_proto_file(${proto_file}) string(REPLACE .proto .pb.cc pb_file ${proto_file}) set(tests_proto_files ${tests_proto_files} - ${protobuf_source_dir}/src/${pb_file}) + ${protobuf_SOURCE_DIR}/src/${pb_file}) endforeach(proto_file) set(common_lite_test_files - ${protobuf_source_dir}/src/google/protobuf/arena_test_util.cc - ${protobuf_source_dir}/src/google/protobuf/map_lite_test_util.cc - ${protobuf_source_dir}/src/google/protobuf/test_util_lite.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/arena_test_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_lite_test_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_util_lite.cc ) +add_library(protobuf-lite-test-common STATIC + ${common_lite_test_files} ${lite_test_proto_files}) +target_link_libraries(protobuf-lite-test-common libprotobuf-lite GTest::gmock) + set(common_test_files ${common_lite_test_files} - ${protobuf_source_dir}/src/google/protobuf/compiler/mock_code_generator.cc - ${protobuf_source_dir}/src/google/protobuf/map_test_util.inc - ${protobuf_source_dir}/src/google/protobuf/reflection_tester.cc - ${protobuf_source_dir}/src/google/protobuf/test_util.cc - ${protobuf_source_dir}/src/google/protobuf/testing/file.cc - ${protobuf_source_dir}/src/google/protobuf/testing/googletest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/mock_code_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_test_util.inc + ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_tester.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/test_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/file.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/googletest.cc ) +add_library(protobuf-test-common STATIC + ${common_test_files} ${tests_proto_files}) +target_link_libraries(protobuf-test-common libprotobuf GTest::gmock) + set(tests_files - ${protobuf_source_dir}/src/google/protobuf/any_test.cc - ${protobuf_source_dir}/src/google/protobuf/arena_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/arenastring_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/arenaz_sampler_test.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/annotation_test_util.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/annotation_test_util.h - ${protobuf_source_dir}/src/google/protobuf/compiler/command_line_interface_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_unittest.inc - ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/metadata_test.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/importer_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_doc_comment_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_plugin_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/parser_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/python/python_plugin_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/descriptor_database_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/descriptor_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/drop_unknown_fields_test.cc - ${protobuf_source_dir}/src/google/protobuf/dynamic_message_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/extension_set_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/generated_message_reflection_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/generated_message_tctable_lite_test.cc - ${protobuf_source_dir}/src/google/protobuf/inlined_string_field_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/io/coded_stream_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/io/io_win32_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/io/printer_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/io/tokenizer_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/io/zero_copy_stream_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/map_field_test.cc - ${protobuf_source_dir}/src/google/protobuf/map_test.cc - ${protobuf_source_dir}/src/google/protobuf/map_test.inc - ${protobuf_source_dir}/src/google/protobuf/message_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/message_unittest.inc - ${protobuf_source_dir}/src/google/protobuf/no_field_presence_test.cc - ${protobuf_source_dir}/src/google/protobuf/preserve_unknown_enum_test.cc - ${protobuf_source_dir}/src/google/protobuf/proto3_arena_lite_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/proto3_arena_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/proto3_lite_unittest.inc - ${protobuf_source_dir}/src/google/protobuf/reflection_ops_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/repeated_field_reflection_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/repeated_field_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/bytestream_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/common_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/int128_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/status_test.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/statusor_test.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/stringpiece_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/stringprintf_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/structurally_valid_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/strutil_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/template_util_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/stubs/time_test.cc - ${protobuf_source_dir}/src/google/protobuf/text_format_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/unknown_field_set_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/util/delimited_message_util_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/field_comparator_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/field_mask_util_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/default_value_objectwriter_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/json_objectwriter_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/json_stream_parser_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/protostream_objectsource_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/protostream_objectwriter_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/internal/type_info_test_helper.cc - ${protobuf_source_dir}/src/google/protobuf/util/json_util_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/message_differencer_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/util/time_util_test.cc - ${protobuf_source_dir}/src/google/protobuf/util/type_resolver_util_test.cc - ${protobuf_source_dir}/src/google/protobuf/well_known_types_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/wire_format_unittest.cc - ${protobuf_source_dir}/src/google/protobuf/wire_format_unittest.inc + ${protobuf_SOURCE_DIR}/src/google/protobuf/any_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/arena_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/arenastring_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/arenaz_sampler_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/annotation_test_util.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/annotation_test_util.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/command_line_interface_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/bootstrap_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/message_size_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/metadata_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/move_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/plugin_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/cpp/unittest.inc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/csharp/csharp_generator_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/importer_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/doc_comment_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/java/plugin_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/parser_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/python/plugin_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/ruby/ruby_generator_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor_database_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/descriptor_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/drop_unknown_fields_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/dynamic_message_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/extension_set_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_reflection_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/generated_message_tctable_lite_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/inlined_string_field_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/coded_stream_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/io_win32_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/printer_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/tokenizer_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/io/zero_copy_stream_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_field_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/map_test.inc + ${protobuf_SOURCE_DIR}/src/google/protobuf/message_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/message_unittest.inc + ${protobuf_SOURCE_DIR}/src/google/protobuf/no_field_presence_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/preserve_unknown_enum_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/proto3_arena_lite_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/proto3_arena_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/proto3_lite_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/proto3_lite_unittest.inc + ${protobuf_SOURCE_DIR}/src/google/protobuf/reflection_ops_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/repeated_field_reflection_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/repeated_field_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/bytestream_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/common_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/int128_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/status_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/statusor_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringpiece_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/stringprintf_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/structurally_valid_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/strutil_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/template_util_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/stubs/time_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/text_format_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/unknown_field_set_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/delimited_message_util_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/field_comparator_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/field_mask_util_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/default_value_objectwriter_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/json_objectwriter_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/json_stream_parser_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/protostream_objectsource_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/protostream_objectwriter_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/internal/type_info_test_helper.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/json_util_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/message_differencer_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/time_util_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/util/type_resolver_util_test.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/well_known_types_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/wire_format_unittest.inc ) if(protobuf_ABSOLUTE_TEST_PLUGIN_PATH) @@ -232,41 +245,66 @@ endif() -add_executable(tests ${tests_files} ${common_test_files} ${tests_proto_files} ${lite_test_proto_files}) +if(protobuf_TEST_XML_OUTDIR) + if(NOT "${protobuf_TEST_XML_OUTDIR}" MATCHES "[/\\]$") + string(APPEND protobuf_TEST_XML_OUTDIR "/") + endif() + set(protobuf_GTEST_ARGS "--gtest_output=xml:${protobuf_TEST_XML_OUTDIR}") +endif() + +add_executable(tests ${tests_files}) if (MSVC) target_compile_options(tests PRIVATE /wd4146 # unary minus operator applied to unsigned type, result still unsigned ) endif() -target_link_libraries(tests libprotoc libprotobuf GTest::gmock_main) +target_link_libraries(tests + protobuf-lite-test-common + protobuf-test-common + libprotoc + libprotobuf + GTest::gmock_main + ${protobuf_ABSL_USED_TARGETS} +) set(test_plugin_files - ${protobuf_source_dir}/src/google/protobuf/compiler/mock_code_generator.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/test_plugin.cc - ${protobuf_source_dir}/src/google/protobuf/testing/file.cc - ${protobuf_source_dir}/src/google/protobuf/testing/file.h + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/mock_code_generator.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/compiler/test_plugin.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/file.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/testing/file.h ) add_executable(test_plugin ${test_plugin_files}) -target_link_libraries(test_plugin libprotoc libprotobuf GTest::gmock) +target_link_libraries(test_plugin + libprotoc + libprotobuf + GTest::gmock + ${protobuf_ABSL_USED_TARGETS} +) set(lite_test_files - ${protobuf_source_dir}/src/google/protobuf/lite_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/lite_unittest.cc ) -add_executable(lite-test ${lite_test_files} ${common_lite_test_files} ${lite_test_proto_files}) -target_link_libraries(lite-test libprotobuf-lite GTest::gmock_main) +add_executable(lite-test ${lite_test_files}) +target_link_libraries(lite-test protobuf-lite-test-common libprotobuf-lite GTest::gmock_main) + +add_test(NAME lite-test + COMMAND lite-test ${protobuf_GTEST_ARGS}) set(lite_arena_test_files - ${protobuf_source_dir}/src/google/protobuf/lite_arena_unittest.cc + ${protobuf_SOURCE_DIR}/src/google/protobuf/lite_arena_unittest.cc ) -add_executable(lite-arena-test ${lite_arena_test_files} ${common_lite_test_files} ${lite_test_proto_files}) -target_link_libraries(lite-arena-test libprotobuf-lite GTest::gmock_main) +add_executable(lite-arena-test ${lite_arena_test_files}) +target_link_libraries(lite-arena-test protobuf-lite-test-common libprotobuf-lite GTest::gmock_main) + +add_test(NAME lite-arena-test + COMMAND lite-arena-test ${protobuf_GTEST_ARGS}) add_custom_target(check COMMAND tests DEPENDS tests test_plugin - WORKING_DIRECTORY ${protobuf_source_dir}) + WORKING_DIRECTORY ${protobuf_SOURCE_DIR}) add_test(NAME check - COMMAND tests - WORKING_DIRECTORY "${protobuf_source_dir}") + COMMAND tests ${protobuf_GTEST_ARGS} + WORKING_DIRECTORY "${protobuf_SOURCE_DIR}")
diff --git a/conformance/README.md b/conformance/README.md index 06925db..0637660 100644 --- a/conformance/README.md +++ b/conformance/README.md
@@ -57,10 +57,10 @@ To run these tests against a new Protocol Buffers implementation, write a program in your language that uses the protobuf implementation you want to test. This program should implement the testing protocol defined in -[conformance.proto](https://github.com/protocolbuffers/protobuf/blob/master/conformance/conformance.proto). +[conformance.proto](https://github.com/protocolbuffers/protobuf/blob/main/conformance/conformance.proto). This is designed to be as easy as possible: the C++ version is only 150 lines and is a good example for what this program should look like -(see [conformance_cpp.cc](https://github.com/protocolbuffers/protobuf/blob/master/conformance/conformance_cpp.cc)). +(see [conformance_cpp.cc](https://github.com/protocolbuffers/protobuf/blob/main/conformance/conformance_cpp.cc)). The program only needs to be able to read from stdin and write to stdout. Portability
diff --git a/conformance/binary_json_conformance_suite.cc b/conformance/binary_json_conformance_suite.cc index b12978f..9b1548d 100644 --- a/conformance/binary_json_conformance_suite.cc +++ b/conformance/binary_json_conformance_suite.cc
@@ -2226,11 +2226,11 @@ "optional_aliased_enum: ALIAS_BAZ"); RunValidJsonTest( "EnumFieldWithAliasUseAlias", REQUIRED, - R"({"optionalAliasedEnum": "QUX"})", + R"({"optionalAliasedEnum": "MOO"})", "optional_aliased_enum: ALIAS_BAZ"); RunValidJsonTest( "EnumFieldWithAliasLowerCase", REQUIRED, - R"({"optionalAliasedEnum": "qux"})", + R"({"optionalAliasedEnum": "moo"})", "optional_aliased_enum: ALIAS_BAZ"); RunValidJsonTest( "EnumFieldWithAliasDifferentCase", REQUIRED,
diff --git a/csharp/.editorconfig b/csharp/.editorconfig new file mode 100644 index 0000000..5e2afd0 --- /dev/null +++ b/csharp/.editorconfig
@@ -0,0 +1,17 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = lf +insert_final_newline = false +trim_trailing_whitespace = true \ No newline at end of file
diff --git a/csharp/Google.Protobuf.Tools.nuspec b/csharp/Google.Protobuf.Tools.nuspec index 278c472..1d34a5e 100644 --- a/csharp/Google.Protobuf.Tools.nuspec +++ b/csharp/Google.Protobuf.Tools.nuspec
@@ -8,7 +8,7 @@ <version>3.20.1</version> <authors>Google Inc.</authors> <owners>protobuf-packages</owners> - <licenseUrl>https://github.com/protocolbuffers/protobuf/blob/master/LICENSE</licenseUrl> + <licenseUrl>https://github.com/protocolbuffers/protobuf/blob/main/LICENSE</licenseUrl> <projectUrl>https://github.com/protocolbuffers/protobuf</projectUrl> <requireLicenseAcceptance>false</requireLicenseAcceptance> <releaseNotes>Tools for Protocol Buffers</releaseNotes>
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs index 685e130..8935b78 100644 --- a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs +++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/ByteStringTest.cs
@@ -1,171 +1,171 @@ -#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.Text; -using NUnit.Framework; - -namespace Google.Protobuf -{ - public class ByteStringTest - { - [Test] - public void Equality() - { - ByteString b1 = ByteString.CopyFrom(1, 2, 3); - ByteString b2 = ByteString.CopyFrom(1, 2, 3); - ByteString b3 = ByteString.CopyFrom(1, 2, 4); - ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); - EqualityTester.AssertEquality(b1, b1); - EqualityTester.AssertEquality(b1, b2); - EqualityTester.AssertInequality(b1, b3); - EqualityTester.AssertInequality(b1, b4); - EqualityTester.AssertInequality(b1, null); -#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) - Assert.IsTrue(b1 == b1); - Assert.IsTrue(b1 == b2); - Assert.IsFalse(b1 == b3); - Assert.IsFalse(b1 == b4); - Assert.IsFalse(b1 == null); - Assert.IsTrue((ByteString) null == null); - Assert.IsFalse(b1 != b1); - Assert.IsFalse(b1 != b2); -#pragma warning disable 1718 - Assert.IsTrue(b1 != b3); - Assert.IsTrue(b1 != b4); - Assert.IsTrue(b1 != null); - Assert.IsFalse((ByteString) null != null); - } - - [Test] - public void EmptyByteStringHasZeroSize() - { - Assert.AreEqual(0, ByteString.Empty.Length); - } - - [Test] - public void CopyFromStringWithExplicitEncoding() - { - ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); - Assert.AreEqual(4, bs.Length); - Assert.AreEqual(65, bs[0]); - Assert.AreEqual(0, bs[1]); - Assert.AreEqual(66, bs[2]); - Assert.AreEqual(0, bs[3]); - } - - [Test] - public void IsEmptyWhenEmpty() - { - Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); - } - - [Test] - public void IsEmptyWhenNotEmpty() - { - Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); - } - - [Test] - public void CopyFromByteArrayCopiesContents() - { - byte[] data = new byte[1]; - data[0] = 10; - ByteString bs = ByteString.CopyFrom(data); - Assert.AreEqual(10, bs[0]); - data[0] = 5; - Assert.AreEqual(10, bs[0]); - } - - [Test] - public void ToByteArrayCopiesContents() - { - ByteString bs = ByteString.CopyFromUtf8("Hello"); - byte[] data = bs.ToByteArray(); - Assert.AreEqual((byte)'H', data[0]); - Assert.AreEqual((byte)'H', bs[0]); - data[0] = 0; - Assert.AreEqual(0, data[0]); - Assert.AreEqual((byte)'H', bs[0]); - } - - [Test] - public void CopyFromUtf8UsesUtf8() - { - ByteString bs = ByteString.CopyFromUtf8("\u20ac"); - Assert.AreEqual(3, bs.Length); - Assert.AreEqual(0xe2, bs[0]); - Assert.AreEqual(0x82, bs[1]); - Assert.AreEqual(0xac, bs[2]); - } - - [Test] - public void CopyFromPortion() - { - byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; - ByteString bs = ByteString.CopyFrom(data, 2, 3); - Assert.AreEqual(3, bs.Length); - Assert.AreEqual(2, bs[0]); - Assert.AreEqual(3, bs[1]); - } - - [Test] - public void ToStringUtf8() - { - ByteString bs = ByteString.CopyFromUtf8("\u20ac"); - Assert.AreEqual("\u20ac", bs.ToStringUtf8()); - } - - [Test] - public void ToStringWithExplicitEncoding() - { - ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); - Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); - } - - [Test] - public void FromBase64_WithText() - { - byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; - string base64 = Convert.ToBase64String(data); - ByteString bs = ByteString.FromBase64(base64); - Assert.AreEqual(data, bs.ToByteArray()); - } - - [Test] - public void FromBase64_Empty() - { - // Optimization which also fixes issue 61. - Assert.AreSame(ByteString.Empty, ByteString.FromBase64("")); - } - } +#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.Text; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class ByteStringTest + { + [Test] + public void Equality() + { + ByteString b1 = ByteString.CopyFrom(1, 2, 3); + ByteString b2 = ByteString.CopyFrom(1, 2, 3); + ByteString b3 = ByteString.CopyFrom(1, 2, 4); + ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); + EqualityTester.AssertEquality(b1, b1); + EqualityTester.AssertEquality(b1, b2); + EqualityTester.AssertInequality(b1, b3); + EqualityTester.AssertInequality(b1, b4); + EqualityTester.AssertInequality(b1, null); +#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) + Assert.IsTrue(b1 == b1); + Assert.IsTrue(b1 == b2); + Assert.IsFalse(b1 == b3); + Assert.IsFalse(b1 == b4); + Assert.IsFalse(b1 == null); + Assert.IsTrue((ByteString) null == null); + Assert.IsFalse(b1 != b1); + Assert.IsFalse(b1 != b2); +#pragma warning disable 1718 + Assert.IsTrue(b1 != b3); + Assert.IsTrue(b1 != b4); + Assert.IsTrue(b1 != null); + Assert.IsFalse((ByteString) null != null); + } + + [Test] + public void EmptyByteStringHasZeroSize() + { + Assert.AreEqual(0, ByteString.Empty.Length); + } + + [Test] + public void CopyFromStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); + Assert.AreEqual(4, bs.Length); + Assert.AreEqual(65, bs[0]); + Assert.AreEqual(0, bs[1]); + Assert.AreEqual(66, bs[2]); + Assert.AreEqual(0, bs[3]); + } + + [Test] + public void IsEmptyWhenEmpty() + { + Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); + } + + [Test] + public void IsEmptyWhenNotEmpty() + { + Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); + } + + [Test] + public void CopyFromByteArrayCopiesContents() + { + byte[] data = new byte[1]; + data[0] = 10; + ByteString bs = ByteString.CopyFrom(data); + Assert.AreEqual(10, bs[0]); + data[0] = 5; + Assert.AreEqual(10, bs[0]); + } + + [Test] + public void ToByteArrayCopiesContents() + { + ByteString bs = ByteString.CopyFromUtf8("Hello"); + byte[] data = bs.ToByteArray(); + Assert.AreEqual((byte)'H', data[0]); + Assert.AreEqual((byte)'H', bs[0]); + data[0] = 0; + Assert.AreEqual(0, data[0]); + Assert.AreEqual((byte)'H', bs[0]); + } + + [Test] + public void CopyFromUtf8UsesUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(0xe2, bs[0]); + Assert.AreEqual(0x82, bs[1]); + Assert.AreEqual(0xac, bs[2]); + } + + [Test] + public void CopyFromPortion() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + ByteString bs = ByteString.CopyFrom(data, 2, 3); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(2, bs[0]); + Assert.AreEqual(3, bs[1]); + } + + [Test] + public void ToStringUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual("\u20ac", bs.ToStringUtf8()); + } + + [Test] + public void ToStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); + Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); + } + + [Test] + public void FromBase64_WithText() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + string base64 = Convert.ToBase64String(data); + ByteString bs = ByteString.FromBase64(base64); + Assert.AreEqual(data, bs.ToByteArray()); + } + + [Test] + public void FromBase64_Empty() + { + // Optimization which also fixes issue 61. + Assert.AreSame(ByteString.Empty, ByteString.FromBase64("")); + } + } } \ No newline at end of file
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 11d06f1..5ac8c71 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
@@ -1,598 +1,598 @@ -#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.IO; -using Google.Protobuf.TestProtos; -using NUnit.Framework; - -namespace Google.Protobuf -{ - public class CodedInputStreamTest - { - /// <summary> - /// Helper to construct a byte array from a bunch of bytes. The inputs are - /// actually ints so that I can use hex notation and not get stupid errors - /// about precision. - /// </summary> - private static byte[] Bytes(params int[] bytesAsInts) - { - byte[] bytes = new byte[bytesAsInts.Length]; - for (int i = 0; i < bytesAsInts.Length; i++) - { - bytes[i] = (byte) bytesAsInts[i]; - } - return bytes; - } - - /// <summary> - /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() - /// </summary> - private static void AssertReadVarint(byte[] data, ulong value) - { - CodedInputStream input = new CodedInputStream(data); - Assert.AreEqual((uint) value, input.ReadRawVarint32()); - - input = new CodedInputStream(data); - Assert.AreEqual(value, input.ReadRawVarint64()); - Assert.IsTrue(input.IsAtEnd); - - // Try different block sizes. - for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) - { - input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); - Assert.AreEqual((uint) value, input.ReadRawVarint32()); - - input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); - Assert.AreEqual(value, input.ReadRawVarint64()); - Assert.IsTrue(input.IsAtEnd); - } - - // Try reading directly from a MemoryStream. We want to verify that it - // doesn't read past the end of the input, so write an extra byte - this - // lets us test the position at the end. - MemoryStream memoryStream = new MemoryStream(); - memoryStream.Write(data, 0, data.Length); - memoryStream.WriteByte(0); - memoryStream.Position = 0; - Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream)); - Assert.AreEqual(data.Length, memoryStream.Position); - } - - /// <summary> - /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and - /// expects them to fail with an InvalidProtocolBufferException whose - /// description matches the given one. - /// </summary> - private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) - { - CodedInputStream input = new CodedInputStream(data); - var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32()); - Assert.AreEqual(expected.Message, exception.Message); - - input = new CodedInputStream(data); - exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64()); - Assert.AreEqual(expected.Message, exception.Message); - - // 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); - } - - [Test] - public void ReadVarint() - { - AssertReadVarint(Bytes(0x00), 0); - AssertReadVarint(Bytes(0x01), 1); - AssertReadVarint(Bytes(0x7f), 127); - // 14882 - AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7)); - // 2961488830 - AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x0bL << 28)); - - // 64-bit - // 7256456126 - AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x1bL << 28)); - // 41256202580718336 - AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | - (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49)); - // 11964378330978735131 - AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), - (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) | - (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63)); - - // Failures - AssertReadVarintFailure( - InvalidProtocolBufferException.MalformedVarint(), - Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x00)); - AssertReadVarintFailure( - InvalidProtocolBufferException.TruncatedMessage(), - Bytes(0x80)); - } - - /// <summary> - /// Parses the given bytes using ReadRawLittleEndian32() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertReadLittleEndian32(byte[] data, uint value) - { - CodedInputStream input = new CodedInputStream(data); - Assert.AreEqual(value, input.ReadRawLittleEndian32()); - Assert.IsTrue(input.IsAtEnd); - - // Try different block sizes. - for (int blockSize = 1; blockSize <= 16; blockSize *= 2) - { - input = new CodedInputStream( - new SmallBlockInputStream(data, blockSize)); - Assert.AreEqual(value, input.ReadRawLittleEndian32()); - Assert.IsTrue(input.IsAtEnd); - } - } - - /// <summary> - /// Parses the given bytes using ReadRawLittleEndian64() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertReadLittleEndian64(byte[] data, ulong value) - { - CodedInputStream input = new CodedInputStream(data); - Assert.AreEqual(value, input.ReadRawLittleEndian64()); - Assert.IsTrue(input.IsAtEnd); - - // Try different block sizes. - for (int blockSize = 1; blockSize <= 16; blockSize *= 2) - { - input = new CodedInputStream( - new SmallBlockInputStream(data, blockSize)); - Assert.AreEqual(value, input.ReadRawLittleEndian64()); - Assert.IsTrue(input.IsAtEnd); - } - } - - [Test] - public void ReadLittleEndian() - { - AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678); - AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0); - - AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), - 0x123456789abcdef0L); - AssertReadLittleEndian64( - Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL); - } - - [Test] - public void DecodeZigZag32() - { - 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, 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] - public void ReadWholeMessage_VaryingBlockSizes() - { - TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); - - byte[] rawBytes = message.ToByteArray(); - Assert.AreEqual(rawBytes.Length, message.CalculateSize()); - TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); - Assert.AreEqual(message, message2); - - // Try different block sizes. - for (int blockSize = 1; blockSize < 256; blockSize *= 2) - { - message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); - Assert.AreEqual(message, message2); - } - } - - [Test] - public void ReadHugeBlob() - { - // Allocate and initialize a 1MB blob. - byte[] blob = new byte[1 << 20]; - for (int i = 0; i < blob.Length; i++) - { - blob[i] = (byte) i; - } - - // Make a message containing it. - var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) }; - - // Serialize and parse it. Make sure to parse from an InputStream, not - // directly from a ByteString, so that CodedInputStream uses buffered - // reading. - TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString()); - - Assert.AreEqual(message, message2); - } - - [Test] - public void ReadMaliciouslyLargeBlob() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteRawVarint32(0x7FFFFFFF); - output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms); - Assert.AreEqual(tag, input.ReadTag()); - - Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); - } - - internal static TestRecursiveMessage MakeRecursiveMessage(int depth) - { - if (depth == 0) - { - return new TestRecursiveMessage { I = 5 }; - } - else - { - return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) }; - } - } - - internal static void AssertMessageDepth(TestRecursiveMessage message, int depth) - { - if (depth == 0) - { - Assert.IsNull(message.A); - Assert.AreEqual(5, message.I); - } - else - { - Assert.IsNotNull(message.A); - AssertMessageDepth(message.A, depth - 1); - } - } - - [Test] - public void MaliciousRecursion() - { - ByteString atRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit).ToByteString(); - ByteString beyondRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit + 1).ToByteString(); - - AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(atRecursiveLimit), CodedInputStream.DefaultRecursionLimit); - - Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(beyondRecursiveLimit)); - - CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(atRecursiveLimit.ToByteArray()), 1000000, CodedInputStream.DefaultRecursionLimit - 1); - Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input)); - } - - [Test] - public void SizeLimit() - { - // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't - // apply to the latter case. - MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray()); - CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100); - Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input)); - } - - /// <summary> - /// Tests that if we read an string that contains invalid UTF-8, no exception - /// is thrown. Instead, the invalid bytes are replaced with the Unicode - /// "replacement character" U+FFFD. - /// </summary> - [Test] - public void ReadInvalidUtf8() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteRawVarint32(1); - output.WriteRawBytes(new byte[] {0x80}); - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms); - - Assert.AreEqual(tag, input.ReadTag()); - string text = input.ReadString(); - Assert.AreEqual('\ufffd', text[0]); - } - - /// <summary> - /// A stream which limits the number of bytes it reads at a time. - /// We use this to make sure that CodedInputStream doesn't screw up when - /// reading in small blocks. - /// </summary> - private sealed class SmallBlockInputStream : MemoryStream - { - private readonly int blockSize; - - public SmallBlockInputStream(byte[] data, int blockSize) - : base(data) - { - this.blockSize = blockSize; - } - - public override int Read(byte[] buffer, int offset, int count) - { - return base.Read(buffer, offset, Math.Min(count, blockSize)); - } - } - - [Test] - public void TestNegativeEnum() - { - byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; - CodedInputStream input = new CodedInputStream(bytes); - Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum()); - Assert.IsTrue(input.IsAtEnd); - } - - //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily - [Test] - public void TestSlowPathAvoidance() - { - using (var ms = new MemoryStream()) - { - CodedOutputStream output = new CodedOutputStream(ms); - output.WriteTag(1, WireFormat.WireType.LengthDelimited); - output.WriteBytes(ByteString.CopyFrom(new byte[100])); - output.WriteTag(2, WireFormat.WireType.LengthDelimited); - output.WriteBytes(ByteString.CopyFrom(new byte[100])); - output.Flush(); - - ms.Position = 0; - CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false); - - uint tag = input.ReadTag(); - Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); - Assert.AreEqual(100, input.ReadBytes().Length); - - tag = input.ReadTag(); - Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); - Assert.AreEqual(100, input.ReadBytes().Length); - } - } - - [Test] - public void Tag0Throws() - { - var input = new CodedInputStream(new byte[] { 0 }); - Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag()); - } - - [Test] - public void SkipGroup() - { - // Create an output stream with a group in: - // Field 1: string "field 1" - // Field 2: group containing: - // Field 1: fixed int32 value 100 - // Field 2: string "ignore me" - // Field 3: nested group containing - // Field 1: fixed int64 value 1000 - // Field 3: string "field 3" - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - output.WriteTag(1, WireFormat.WireType.LengthDelimited); - output.WriteString("field 1"); - - // The outer group... - output.WriteTag(2, WireFormat.WireType.StartGroup); - output.WriteTag(1, WireFormat.WireType.Fixed32); - output.WriteFixed32(100); - output.WriteTag(2, WireFormat.WireType.LengthDelimited); - output.WriteString("ignore me"); - // The nested group... - output.WriteTag(3, WireFormat.WireType.StartGroup); - output.WriteTag(1, WireFormat.WireType.Fixed64); - output.WriteFixed64(1000); - // Note: Not sure the field number is relevant for end group... - output.WriteTag(3, WireFormat.WireType.EndGroup); - - // End the outer group - output.WriteTag(2, WireFormat.WireType.EndGroup); - - output.WriteTag(3, WireFormat.WireType.LengthDelimited); - output.WriteString("field 3"); - output.Flush(); - stream.Position = 0; - - // Now act like a generated client - var input = new CodedInputStream(stream); - Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); - Assert.AreEqual("field 1", input.ReadString()); - Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); - input.SkipLastField(); // Should consume the whole group, including the nested one. - Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag()); - Assert.AreEqual("field 3", input.ReadString()); - } - - [Test] - public void SkipGroup_WrongEndGroupTag() - { - // Create an output stream with: - // Field 1: string "field 1" - // Start group 2 - // Field 3: fixed int32 - // End group 4 (should give an error) - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - output.WriteTag(1, WireFormat.WireType.LengthDelimited); - output.WriteString("field 1"); - - // The outer group... - output.WriteTag(2, WireFormat.WireType.StartGroup); - output.WriteTag(3, WireFormat.WireType.Fixed32); - output.WriteFixed32(100); - output.WriteTag(4, WireFormat.WireType.EndGroup); - output.Flush(); - stream.Position = 0; - - // Now act like a generated client - var input = new CodedInputStream(stream); - Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); - Assert.AreEqual("field 1", input.ReadString()); - Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); - Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); - } - - [Test] - public void RogueEndGroupTag() - { - // If we have an end-group tag without a leading start-group tag, generated - // code will just call SkipLastField... so that should fail. - - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - output.WriteTag(1, WireFormat.WireType.EndGroup); - output.Flush(); - stream.Position = 0; - - var input = new CodedInputStream(stream); - Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag()); - Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); - } - - [Test] - public void EndOfStreamReachedWhileSkippingGroup() - { - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - output.WriteTag(1, WireFormat.WireType.StartGroup); - output.WriteTag(2, WireFormat.WireType.StartGroup); - output.WriteTag(2, WireFormat.WireType.EndGroup); - - output.Flush(); - stream.Position = 0; - - // Now act like a generated client - var input = new CodedInputStream(stream); - input.ReadTag(); - Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); - } - - [Test] - public void RecursionLimitAppliedWhileSkippingGroup() - { - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) - { - output.WriteTag(1, WireFormat.WireType.StartGroup); - } - for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) - { - output.WriteTag(1, WireFormat.WireType.EndGroup); - } - output.Flush(); - stream.Position = 0; - - // Now act like a generated client - var input = new CodedInputStream(stream); - Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag()); - Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); - } - - [Test] - public void Construction_Invalid() - { - Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null)); - Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0)); - Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null)); - Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0)); - Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10)); - } - - [Test] - public void CreateWithLimits_InvalidLimits() - { - var stream = new MemoryStream(); - Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1)); - Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0)); - } - - [Test] - public void Dispose_DisposesUnderlyingStream() - { - var memoryStream = new MemoryStream(); - Assert.IsTrue(memoryStream.CanRead); - using (var cis = new CodedInputStream(memoryStream)) - { - } - Assert.IsFalse(memoryStream.CanRead); // Disposed - } - - [Test] - public void Dispose_WithLeaveOpen() - { - var memoryStream = new MemoryStream(); - Assert.IsTrue(memoryStream.CanRead); - using (var cis = new CodedInputStream(memoryStream, true)) - { - } - Assert.IsTrue(memoryStream.CanRead); // We left the stream open - } - } +#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.IO; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class CodedInputStreamTest + { + /// <summary> + /// Helper to construct a byte array from a bunch of bytes. The inputs are + /// actually ints so that I can use hex notation and not get stupid errors + /// about precision. + /// </summary> + private static byte[] Bytes(params int[] bytesAsInts) + { + byte[] bytes = new byte[bytesAsInts.Length]; + for (int i = 0; i < bytesAsInts.Length; i++) + { + bytes[i] = (byte) bytesAsInts[i]; + } + return bytes; + } + + /// <summary> + /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() + /// </summary> + private static void AssertReadVarint(byte[] data, ulong value) + { + CodedInputStream input = new CodedInputStream(data); + Assert.AreEqual((uint) value, input.ReadRawVarint32()); + + input = new CodedInputStream(data); + Assert.AreEqual(value, input.ReadRawVarint64()); + Assert.IsTrue(input.IsAtEnd); + + // Try different block sizes. + for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) + { + input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); + Assert.AreEqual((uint) value, input.ReadRawVarint32()); + + input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); + Assert.AreEqual(value, input.ReadRawVarint64()); + Assert.IsTrue(input.IsAtEnd); + } + + // Try reading directly from a MemoryStream. We want to verify that it + // doesn't read past the end of the input, so write an extra byte - this + // lets us test the position at the end. + MemoryStream memoryStream = new MemoryStream(); + memoryStream.Write(data, 0, data.Length); + memoryStream.WriteByte(0); + memoryStream.Position = 0; + Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream)); + Assert.AreEqual(data.Length, memoryStream.Position); + } + + /// <summary> + /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and + /// expects them to fail with an InvalidProtocolBufferException whose + /// description matches the given one. + /// </summary> + private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) + { + CodedInputStream input = new CodedInputStream(data); + var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32()); + Assert.AreEqual(expected.Message, exception.Message); + + input = new CodedInputStream(data); + exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint64()); + Assert.AreEqual(expected.Message, exception.Message); + + // 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); + } + + [Test] + public void ReadVarint() + { + AssertReadVarint(Bytes(0x00), 0); + AssertReadVarint(Bytes(0x01), 1); + AssertReadVarint(Bytes(0x7f), 127); + // 14882 + AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7)); + // 2961488830 + AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x0bL << 28)); + + // 64-bit + // 7256456126 + AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x1bL << 28)); + // 41256202580718336 + AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), + (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | + (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49)); + // 11964378330978735131 + AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), + (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | + (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) | + (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63)); + + // Failures + AssertReadVarintFailure( + InvalidProtocolBufferException.MalformedVarint(), + Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x00)); + AssertReadVarintFailure( + InvalidProtocolBufferException.TruncatedMessage(), + Bytes(0x80)); + } + + /// <summary> + /// Parses the given bytes using ReadRawLittleEndian32() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertReadLittleEndian32(byte[] data, uint value) + { + CodedInputStream input = new CodedInputStream(data); + Assert.AreEqual(value, input.ReadRawLittleEndian32()); + Assert.IsTrue(input.IsAtEnd); + + // Try different block sizes. + for (int blockSize = 1; blockSize <= 16; blockSize *= 2) + { + input = new CodedInputStream( + new SmallBlockInputStream(data, blockSize)); + Assert.AreEqual(value, input.ReadRawLittleEndian32()); + Assert.IsTrue(input.IsAtEnd); + } + } + + /// <summary> + /// Parses the given bytes using ReadRawLittleEndian64() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertReadLittleEndian64(byte[] data, ulong value) + { + CodedInputStream input = new CodedInputStream(data); + Assert.AreEqual(value, input.ReadRawLittleEndian64()); + Assert.IsTrue(input.IsAtEnd); + + // Try different block sizes. + for (int blockSize = 1; blockSize <= 16; blockSize *= 2) + { + input = new CodedInputStream( + new SmallBlockInputStream(data, blockSize)); + Assert.AreEqual(value, input.ReadRawLittleEndian64()); + Assert.IsTrue(input.IsAtEnd); + } + } + + [Test] + public void ReadLittleEndian() + { + AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678); + AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0); + + AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), + 0x123456789abcdef0L); + AssertReadLittleEndian64( + Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL); + } + + [Test] + public void DecodeZigZag32() + { + 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, 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] + public void ReadWholeMessage_VaryingBlockSizes() + { + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + + byte[] rawBytes = message.ToByteArray(); + Assert.AreEqual(rawBytes.Length, message.CalculateSize()); + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); + Assert.AreEqual(message, message2); + + // Try different block sizes. + for (int blockSize = 1; blockSize < 256; blockSize *= 2) + { + message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); + Assert.AreEqual(message, message2); + } + } + + [Test] + public void ReadHugeBlob() + { + // Allocate and initialize a 1MB blob. + byte[] blob = new byte[1 << 20]; + for (int i = 0; i < blob.Length; i++) + { + blob[i] = (byte) i; + } + + // Make a message containing it. + var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) }; + + // Serialize and parse it. Make sure to parse from an InputStream, not + // directly from a ByteString, so that CodedInputStream uses buffered + // reading. + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString()); + + Assert.AreEqual(message, message2); + } + + [Test] + public void ReadMaliciouslyLargeBlob() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteRawVarint32(0x7FFFFFFF); + output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + Assert.AreEqual(tag, input.ReadTag()); + + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); + } + + internal static TestRecursiveMessage MakeRecursiveMessage(int depth) + { + if (depth == 0) + { + return new TestRecursiveMessage { I = 5 }; + } + else + { + return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) }; + } + } + + internal static void AssertMessageDepth(TestRecursiveMessage message, int depth) + { + if (depth == 0) + { + Assert.IsNull(message.A); + Assert.AreEqual(5, message.I); + } + else + { + Assert.IsNotNull(message.A); + AssertMessageDepth(message.A, depth - 1); + } + } + + [Test] + public void MaliciousRecursion() + { + ByteString atRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit).ToByteString(); + ByteString beyondRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit + 1).ToByteString(); + + AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(atRecursiveLimit), CodedInputStream.DefaultRecursionLimit); + + Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(beyondRecursiveLimit)); + + CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(atRecursiveLimit.ToByteArray()), 1000000, CodedInputStream.DefaultRecursionLimit - 1); + Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input)); + } + + [Test] + public void SizeLimit() + { + // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't + // apply to the latter case. + MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray()); + CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100); + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input)); + } + + /// <summary> + /// Tests that if we read an string that contains invalid UTF-8, no exception + /// is thrown. Instead, the invalid bytes are replaced with the Unicode + /// "replacement character" U+FFFD. + /// </summary> + [Test] + public void ReadInvalidUtf8() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteRawVarint32(1); + output.WriteRawBytes(new byte[] {0x80}); + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + + Assert.AreEqual(tag, input.ReadTag()); + string text = input.ReadString(); + Assert.AreEqual('\ufffd', text[0]); + } + + /// <summary> + /// A stream which limits the number of bytes it reads at a time. + /// We use this to make sure that CodedInputStream doesn't screw up when + /// reading in small blocks. + /// </summary> + private sealed class SmallBlockInputStream : MemoryStream + { + private readonly int blockSize; + + public SmallBlockInputStream(byte[] data, int blockSize) + : base(data) + { + this.blockSize = blockSize; + } + + public override int Read(byte[] buffer, int offset, int count) + { + return base.Read(buffer, offset, Math.Min(count, blockSize)); + } + } + + [Test] + public void TestNegativeEnum() + { + byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; + CodedInputStream input = new CodedInputStream(bytes); + Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum()); + Assert.IsTrue(input.IsAtEnd); + } + + //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily + [Test] + public void TestSlowPathAvoidance() + { + using (var ms = new MemoryStream()) + { + CodedOutputStream output = new CodedOutputStream(ms); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteBytes(ByteString.CopyFrom(new byte[100])); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteBytes(ByteString.CopyFrom(new byte[100])); + output.Flush(); + + ms.Position = 0; + CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false); + + uint tag = input.ReadTag(); + Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); + Assert.AreEqual(100, input.ReadBytes().Length); + + tag = input.ReadTag(); + Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); + Assert.AreEqual(100, input.ReadBytes().Length); + } + } + + [Test] + public void Tag0Throws() + { + var input = new CodedInputStream(new byte[] { 0 }); + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag()); + } + + [Test] + public void SkipGroup() + { + // Create an output stream with a group in: + // Field 1: string "field 1" + // Field 2: group containing: + // Field 1: fixed int32 value 100 + // Field 2: string "ignore me" + // Field 3: nested group containing + // Field 1: fixed int64 value 1000 + // Field 3: string "field 3" + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString("field 1"); + + // The outer group... + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(1, WireFormat.WireType.Fixed32); + output.WriteFixed32(100); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteString("ignore me"); + // The nested group... + output.WriteTag(3, WireFormat.WireType.StartGroup); + output.WriteTag(1, WireFormat.WireType.Fixed64); + output.WriteFixed64(1000); + // Note: Not sure the field number is relevant for end group... + output.WriteTag(3, WireFormat.WireType.EndGroup); + + // End the outer group + output.WriteTag(2, WireFormat.WireType.EndGroup); + + output.WriteTag(3, WireFormat.WireType.LengthDelimited); + output.WriteString("field 3"); + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 1", input.ReadString()); + Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); + input.SkipLastField(); // Should consume the whole group, including the nested one. + Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 3", input.ReadString()); + } + + [Test] + public void SkipGroup_WrongEndGroupTag() + { + // Create an output stream with: + // Field 1: string "field 1" + // Start group 2 + // Field 3: fixed int32 + // End group 4 (should give an error) + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString("field 1"); + + // The outer group... + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(3, WireFormat.WireType.Fixed32); + output.WriteFixed32(100); + output.WriteTag(4, WireFormat.WireType.EndGroup); + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 1", input.ReadString()); + Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void RogueEndGroupTag() + { + // If we have an end-group tag without a leading start-group tag, generated + // code will just call SkipLastField... so that should fail. + + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.EndGroup); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void EndOfStreamReachedWhileSkippingGroup() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.StartGroup); + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(2, WireFormat.WireType.EndGroup); + + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + input.ReadTag(); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void RecursionLimitAppliedWhileSkippingGroup() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) + { + output.WriteTag(1, WireFormat.WireType.StartGroup); + } + for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) + { + output.WriteTag(1, WireFormat.WireType.EndGroup); + } + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void Construction_Invalid() + { + Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null)); + Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0)); + Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null)); + Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0)); + Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10)); + } + + [Test] + public void CreateWithLimits_InvalidLimits() + { + var stream = new MemoryStream(); + Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1)); + Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0)); + } + + [Test] + public void Dispose_DisposesUnderlyingStream() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanRead); + using (var cis = new CodedInputStream(memoryStream)) + { + } + Assert.IsFalse(memoryStream.CanRead); // Disposed + } + + [Test] + public void Dispose_WithLeaveOpen() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanRead); + using (var cis = new CodedInputStream(memoryStream, true)) + { + } + Assert.IsTrue(memoryStream.CanRead); // We left the stream open + } + } } \ No newline at end of file
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 e9b4ea8..4890417 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
@@ -1,419 +1,419 @@ -#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.IO; -using Google.Protobuf.TestProtos; -using NUnit.Framework; - -namespace Google.Protobuf -{ - public class CodedOutputStreamTest - { - /// <summary> - /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and - /// checks that the result matches the given bytes - /// </summary> - private static void AssertWriteVarint(byte[] data, ulong value) - { - // Only do 32-bit write if the value fits in 32 bits. - if ((value >> 32) == 0) - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput); - output.WriteRawVarint32((uint) value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - // Also try computing size. - Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value)); - } - - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput); - output.WriteRawVarint64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - // Also try computing size. - Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value)); - } - - // Try different buffer sizes. - for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) - { - // Only do 32-bit write if the value fits in 32 bits. - if ((value >> 32) == 0) - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = - new CodedOutputStream(rawOutput, bufferSize); - output.WriteRawVarint32((uint) value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - } - - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize); - output.WriteRawVarint64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - } - } - } - - /// <summary> - /// Tests WriteRawVarint32() and WriteRawVarint64() - /// </summary> - [Test] - public void WriteVarint() - { - AssertWriteVarint(new byte[] {0x00}, 0); - AssertWriteVarint(new byte[] {0x01}, 1); - AssertWriteVarint(new byte[] {0x7f}, 127); - // 14882 - AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7)); - // 2961488830 - AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b}, - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x0bL << 28)); - - // 64-bit - // 7256456126 - AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b}, - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x1bL << 28)); - // 41256202580718336 - AssertWriteVarint( - new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | - (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49)); - // 11964378330978735131 - AssertWriteVarint( - new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, - unchecked((ulong) - ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) | - (0x05L << 49) | (0x26L << 56) | (0x01L << 63)))); - } - - /// <summary> - /// Parses the given bytes using WriteRawLittleEndian32() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertWriteLittleEndian32(byte[] data, uint value) - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput); - output.WriteRawLittleEndian32(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - // Try different buffer sizes. - for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) - { - rawOutput = new MemoryStream(); - output = new CodedOutputStream(rawOutput, bufferSize); - output.WriteRawLittleEndian32(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - } - } - - /// <summary> - /// Parses the given bytes using WriteRawLittleEndian64() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertWriteLittleEndian64(byte[] data, ulong value) - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput); - output.WriteRawLittleEndian64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - // Try different block sizes. - for (int blockSize = 1; blockSize <= 16; blockSize *= 2) - { - rawOutput = new MemoryStream(); - output = new CodedOutputStream(rawOutput, blockSize); - output.WriteRawLittleEndian64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - } - } - - /// <summary> - /// Tests writeRawLittleEndian32() and writeRawLittleEndian64(). - /// </summary> - [Test] - public void WriteLittleEndian() - { - AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678); - AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0); - - AssertWriteLittleEndian64( - new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}, - 0x123456789abcdef0L); - AssertWriteLittleEndian64( - new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a}, - 0x9abcdef012345678UL); - } - - [Test] - public void WriteWholeMessage_VaryingBlockSizes() - { - TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); - - byte[] rawBytes = message.ToByteArray(); - - // Try different block sizes. - for (int blockSize = 1; blockSize < 256; blockSize *= 2) - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize); - message.WriteTo(output); - output.Flush(); - Assert.AreEqual(rawBytes, rawOutput.ToArray()); - } - } - - [Test] - public void EncodeZigZag32() - { - Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag32(0)); - Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag32(-1)); - Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag32(1)); - Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag32(-2)); - Assert.AreEqual(0x7FFFFFFEu, WritingPrimitives.EncodeZigZag32(0x3FFFFFFF)); - Assert.AreEqual(0x7FFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0xC0000000))); - Assert.AreEqual(0xFFFFFFFEu, WritingPrimitives.EncodeZigZag32(0x7FFFFFFF)); - Assert.AreEqual(0xFFFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0x80000000))); - } - - [Test] - public void EncodeZigZag64() - { - Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag64(0)); - Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag64(-1)); - Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag64(1)); - Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag64(-2)); - Assert.AreEqual(0x000000007FFFFFFEuL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL))); - Assert.AreEqual(0x000000007FFFFFFFuL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL))); - Assert.AreEqual(0x00000000FFFFFFFEuL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL))); - Assert.AreEqual(0x00000000FFFFFFFFuL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL))); - Assert.AreEqual(0xFFFFFFFFFFFFFFFEL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL))); - Assert.AreEqual(0xFFFFFFFFFFFFFFFFL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0x8000000000000000UL))); - } - - [Test] - public void RoundTripZigZag32() - { - // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) - // were chosen semi-randomly via keyboard bashing. - Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(0))); - Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(1))); - Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-1))); - Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(14927))); - Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-3612))); - } - - [Test] - public void RoundTripZigZag64() - { - Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(0))); - Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(1))); - Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-1))); - Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(14927))); - Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-3612))); - - Assert.AreEqual(856912304801416L, - ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(856912304801416L))); - Assert.AreEqual(-75123905439571256L, - ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-75123905439571256L))); - } - - [Test] - public void TestNegativeEnumNoTag() - { - Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2)); - Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue)); - - byte[] bytes = new byte[10]; - CodedOutputStream output = new CodedOutputStream(bytes); - output.WriteEnum((int) SampleEnum.NegativeValue); - - Assert.AreEqual(0, output.SpaceLeft); - Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); - } - - [Test] - public void TestCodedInputOutputPosition() - { - byte[] content = new byte[110]; - for (int i = 0; i < content.Length; i++) - content[i] = (byte)i; - - byte[] child = new byte[120]; - { - MemoryStream ms = new MemoryStream(child); - CodedOutputStream cout = new CodedOutputStream(ms, 20); - // Field 11: numeric value: 500 - cout.WriteTag(11, WireFormat.WireType.Varint); - Assert.AreEqual(1, cout.Position); - cout.WriteInt32(500); - Assert.AreEqual(3, cout.Position); - //Field 12: length delimited 120 bytes - cout.WriteTag(12, WireFormat.WireType.LengthDelimited); - Assert.AreEqual(4, cout.Position); - cout.WriteBytes(ByteString.CopyFrom(content)); - Assert.AreEqual(115, cout.Position); - // Field 13: fixed numeric value: 501 - cout.WriteTag(13, WireFormat.WireType.Fixed32); - Assert.AreEqual(116, cout.Position); - cout.WriteSFixed32(501); - Assert.AreEqual(120, cout.Position); - cout.Flush(); - } - - byte[] bytes = new byte[130]; - { - CodedOutputStream cout = new CodedOutputStream(bytes); - // Field 1: numeric value: 500 - cout.WriteTag(1, WireFormat.WireType.Varint); - Assert.AreEqual(1, cout.Position); - cout.WriteInt32(500); - Assert.AreEqual(3, cout.Position); - //Field 2: length delimited 120 bytes - cout.WriteTag(2, WireFormat.WireType.LengthDelimited); - Assert.AreEqual(4, cout.Position); - cout.WriteBytes(ByteString.CopyFrom(child)); - Assert.AreEqual(125, cout.Position); - // Field 3: fixed numeric value: 500 - cout.WriteTag(3, WireFormat.WireType.Fixed32); - Assert.AreEqual(126, cout.Position); - cout.WriteSFixed32(501); - Assert.AreEqual(130, cout.Position); - cout.Flush(); - } - // Now test Input stream: - { - CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false); - Assert.AreEqual(0, cin.Position); - // Field 1: - uint tag = cin.ReadTag(); - Assert.AreEqual(1, tag >> 3); - Assert.AreEqual(1, cin.Position); - Assert.AreEqual(500, cin.ReadInt32()); - Assert.AreEqual(3, cin.Position); - //Field 2: - tag = cin.ReadTag(); - Assert.AreEqual(2, tag >> 3); - Assert.AreEqual(4, cin.Position); - int childlen = cin.ReadLength(); - Assert.AreEqual(120, childlen); - Assert.AreEqual(5, cin.Position); - int oldlimit = cin.PushLimit((int)childlen); - Assert.AreEqual(5, cin.Position); - // Now we are reading child message - { - // Field 11: numeric value: 500 - tag = cin.ReadTag(); - Assert.AreEqual(11, tag >> 3); - Assert.AreEqual(6, cin.Position); - Assert.AreEqual(500, cin.ReadInt32()); - Assert.AreEqual(8, cin.Position); - //Field 12: length delimited 120 bytes - tag = cin.ReadTag(); - Assert.AreEqual(12, tag >> 3); - Assert.AreEqual(9, cin.Position); - ByteString bstr = cin.ReadBytes(); - Assert.AreEqual(110, bstr.Length); - Assert.AreEqual((byte) 109, bstr[109]); - Assert.AreEqual(120, cin.Position); - // Field 13: fixed numeric value: 501 - tag = cin.ReadTag(); - Assert.AreEqual(13, tag >> 3); - // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit - Assert.AreEqual(121, cin.Position); - Assert.AreEqual(501, cin.ReadSFixed32()); - Assert.AreEqual(125, cin.Position); - Assert.IsTrue(cin.IsAtEnd); - } - cin.PopLimit(oldlimit); - Assert.AreEqual(125, cin.Position); - // Field 3: fixed numeric value: 501 - tag = cin.ReadTag(); - Assert.AreEqual(3, tag >> 3); - Assert.AreEqual(126, cin.Position); - Assert.AreEqual(501, cin.ReadSFixed32()); - Assert.AreEqual(130, cin.Position); - Assert.IsTrue(cin.IsAtEnd); - } - } - - [Test] - public void Dispose_DisposesUnderlyingStream() - { - var memoryStream = new MemoryStream(); - Assert.IsTrue(memoryStream.CanWrite); - using (var cos = new CodedOutputStream(memoryStream)) - { - cos.WriteRawBytes(new byte[] {0}); - Assert.AreEqual(0, memoryStream.Position); // Not flushed yet - } - Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream - Assert.IsFalse(memoryStream.CanWrite); // Disposed - } - - [Test] - public void Dispose_WithLeaveOpen() - { - var memoryStream = new MemoryStream(); - Assert.IsTrue(memoryStream.CanWrite); - using (var cos = new CodedOutputStream(memoryStream, true)) - { - cos.WriteRawBytes(new byte[] {0}); - Assert.AreEqual(0, memoryStream.Position); // Not flushed yet - } - Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream - Assert.IsTrue(memoryStream.CanWrite); // We left the stream open - } - } +#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.IO; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class CodedOutputStreamTest + { + /// <summary> + /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and + /// checks that the result matches the given bytes + /// </summary> + private static void AssertWriteVarint(byte[] data, ulong value) + { + // Only do 32-bit write if the value fits in 32 bits. + if ((value >> 32) == 0) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawVarint32((uint) value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + // Also try computing size. + Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value)); + } + + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawVarint64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + // Also try computing size. + Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value)); + } + + // Try different buffer sizes. + for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) + { + // Only do 32-bit write if the value fits in 32 bits. + if ((value >> 32) == 0) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = + new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawVarint32((uint) value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + } + + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawVarint64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + } + } + } + + /// <summary> + /// Tests WriteRawVarint32() and WriteRawVarint64() + /// </summary> + [Test] + public void WriteVarint() + { + AssertWriteVarint(new byte[] {0x00}, 0); + AssertWriteVarint(new byte[] {0x01}, 1); + AssertWriteVarint(new byte[] {0x7f}, 127); + // 14882 + AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7)); + // 2961488830 + AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b}, + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x0bL << 28)); + + // 64-bit + // 7256456126 + AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b}, + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x1bL << 28)); + // 41256202580718336 + AssertWriteVarint( + new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, + (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | + (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49)); + // 11964378330978735131 + AssertWriteVarint( + new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, + unchecked((ulong) + ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | + (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) | + (0x05L << 49) | (0x26L << 56) | (0x01L << 63)))); + } + + /// <summary> + /// Parses the given bytes using WriteRawLittleEndian32() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertWriteLittleEndian32(byte[] data, uint value) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawLittleEndian32(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + // Try different buffer sizes. + for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) + { + rawOutput = new MemoryStream(); + output = new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawLittleEndian32(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + } + } + + /// <summary> + /// Parses the given bytes using WriteRawLittleEndian64() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertWriteLittleEndian64(byte[] data, ulong value) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawLittleEndian64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + // Try different block sizes. + for (int blockSize = 1; blockSize <= 16; blockSize *= 2) + { + rawOutput = new MemoryStream(); + output = new CodedOutputStream(rawOutput, blockSize); + output.WriteRawLittleEndian64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + } + } + + /// <summary> + /// Tests writeRawLittleEndian32() and writeRawLittleEndian64(). + /// </summary> + [Test] + public void WriteLittleEndian() + { + AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678); + AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0); + + AssertWriteLittleEndian64( + new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}, + 0x123456789abcdef0L); + AssertWriteLittleEndian64( + new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a}, + 0x9abcdef012345678UL); + } + + [Test] + public void WriteWholeMessage_VaryingBlockSizes() + { + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + + byte[] rawBytes = message.ToByteArray(); + + // Try different block sizes. + for (int blockSize = 1; blockSize < 256; blockSize *= 2) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize); + message.WriteTo(output); + output.Flush(); + Assert.AreEqual(rawBytes, rawOutput.ToArray()); + } + } + + [Test] + public void EncodeZigZag32() + { + Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag32(0)); + Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag32(-1)); + Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag32(1)); + Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag32(-2)); + Assert.AreEqual(0x7FFFFFFEu, WritingPrimitives.EncodeZigZag32(0x3FFFFFFF)); + Assert.AreEqual(0x7FFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0xC0000000))); + Assert.AreEqual(0xFFFFFFFEu, WritingPrimitives.EncodeZigZag32(0x7FFFFFFF)); + Assert.AreEqual(0xFFFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0x80000000))); + } + + [Test] + public void EncodeZigZag64() + { + Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag64(0)); + Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag64(-1)); + Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag64(1)); + Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag64(-2)); + Assert.AreEqual(0x000000007FFFFFFEuL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL))); + Assert.AreEqual(0x000000007FFFFFFFuL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL))); + Assert.AreEqual(0x00000000FFFFFFFEuL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL))); + Assert.AreEqual(0x00000000FFFFFFFFuL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL))); + Assert.AreEqual(0xFFFFFFFFFFFFFFFEL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL))); + Assert.AreEqual(0xFFFFFFFFFFFFFFFFL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0x8000000000000000UL))); + } + + [Test] + public void RoundTripZigZag32() + { + // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) + // were chosen semi-randomly via keyboard bashing. + Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(0))); + Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(1))); + Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-1))); + Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(14927))); + Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-3612))); + } + + [Test] + public void RoundTripZigZag64() + { + Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(0))); + Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(1))); + Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-1))); + Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(14927))); + Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-3612))); + + Assert.AreEqual(856912304801416L, + ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(856912304801416L))); + Assert.AreEqual(-75123905439571256L, + ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-75123905439571256L))); + } + + [Test] + public void TestNegativeEnumNoTag() + { + Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2)); + Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue)); + + byte[] bytes = new byte[10]; + CodedOutputStream output = new CodedOutputStream(bytes); + output.WriteEnum((int) SampleEnum.NegativeValue); + + Assert.AreEqual(0, output.SpaceLeft); + Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); + } + + [Test] + public void TestCodedInputOutputPosition() + { + byte[] content = new byte[110]; + for (int i = 0; i < content.Length; i++) + content[i] = (byte)i; + + byte[] child = new byte[120]; + { + MemoryStream ms = new MemoryStream(child); + CodedOutputStream cout = new CodedOutputStream(ms, 20); + // Field 11: numeric value: 500 + cout.WriteTag(11, WireFormat.WireType.Varint); + Assert.AreEqual(1, cout.Position); + cout.WriteInt32(500); + Assert.AreEqual(3, cout.Position); + //Field 12: length delimited 120 bytes + cout.WriteTag(12, WireFormat.WireType.LengthDelimited); + Assert.AreEqual(4, cout.Position); + cout.WriteBytes(ByteString.CopyFrom(content)); + Assert.AreEqual(115, cout.Position); + // Field 13: fixed numeric value: 501 + cout.WriteTag(13, WireFormat.WireType.Fixed32); + Assert.AreEqual(116, cout.Position); + cout.WriteSFixed32(501); + Assert.AreEqual(120, cout.Position); + cout.Flush(); + } + + byte[] bytes = new byte[130]; + { + CodedOutputStream cout = new CodedOutputStream(bytes); + // Field 1: numeric value: 500 + cout.WriteTag(1, WireFormat.WireType.Varint); + Assert.AreEqual(1, cout.Position); + cout.WriteInt32(500); + Assert.AreEqual(3, cout.Position); + //Field 2: length delimited 120 bytes + cout.WriteTag(2, WireFormat.WireType.LengthDelimited); + Assert.AreEqual(4, cout.Position); + cout.WriteBytes(ByteString.CopyFrom(child)); + Assert.AreEqual(125, cout.Position); + // Field 3: fixed numeric value: 500 + cout.WriteTag(3, WireFormat.WireType.Fixed32); + Assert.AreEqual(126, cout.Position); + cout.WriteSFixed32(501); + Assert.AreEqual(130, cout.Position); + cout.Flush(); + } + // Now test Input stream: + { + CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false); + Assert.AreEqual(0, cin.Position); + // Field 1: + uint tag = cin.ReadTag(); + Assert.AreEqual(1, tag >> 3); + Assert.AreEqual(1, cin.Position); + Assert.AreEqual(500, cin.ReadInt32()); + Assert.AreEqual(3, cin.Position); + //Field 2: + tag = cin.ReadTag(); + Assert.AreEqual(2, tag >> 3); + Assert.AreEqual(4, cin.Position); + int childlen = cin.ReadLength(); + Assert.AreEqual(120, childlen); + Assert.AreEqual(5, cin.Position); + int oldlimit = cin.PushLimit((int)childlen); + Assert.AreEqual(5, cin.Position); + // Now we are reading child message + { + // Field 11: numeric value: 500 + tag = cin.ReadTag(); + Assert.AreEqual(11, tag >> 3); + Assert.AreEqual(6, cin.Position); + Assert.AreEqual(500, cin.ReadInt32()); + Assert.AreEqual(8, cin.Position); + //Field 12: length delimited 120 bytes + tag = cin.ReadTag(); + Assert.AreEqual(12, tag >> 3); + Assert.AreEqual(9, cin.Position); + ByteString bstr = cin.ReadBytes(); + Assert.AreEqual(110, bstr.Length); + Assert.AreEqual((byte) 109, bstr[109]); + Assert.AreEqual(120, cin.Position); + // Field 13: fixed numeric value: 501 + tag = cin.ReadTag(); + Assert.AreEqual(13, tag >> 3); + // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit + Assert.AreEqual(121, cin.Position); + Assert.AreEqual(501, cin.ReadSFixed32()); + Assert.AreEqual(125, cin.Position); + Assert.IsTrue(cin.IsAtEnd); + } + cin.PopLimit(oldlimit); + Assert.AreEqual(125, cin.Position); + // Field 3: fixed numeric value: 501 + tag = cin.ReadTag(); + Assert.AreEqual(3, tag >> 3); + Assert.AreEqual(126, cin.Position); + Assert.AreEqual(501, cin.ReadSFixed32()); + Assert.AreEqual(130, cin.Position); + Assert.IsTrue(cin.IsAtEnd); + } + } + + [Test] + public void Dispose_DisposesUnderlyingStream() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanWrite); + using (var cos = new CodedOutputStream(memoryStream)) + { + cos.WriteRawBytes(new byte[] {0}); + Assert.AreEqual(0, memoryStream.Position); // Not flushed yet + } + Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream + Assert.IsFalse(memoryStream.CanWrite); // Disposed + } + + [Test] + public void Dispose_WithLeaveOpen() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanWrite); + using (var cos = new CodedOutputStream(memoryStream, true)) + { + cos.WriteRawBytes(new byte[] {0}); + Assert.AreEqual(0, memoryStream.Position); // Not flushed yet + } + Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream + Assert.IsTrue(memoryStream.CanWrite); // We left the stream open + } + } } \ No newline at end of file
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs index 34d5b9f..fd041e0 100644 --- a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs +++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/DeprecatedMemberTest.cs
@@ -1,55 +1,55 @@ -#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 System; -using System.Reflection; -using Google.Protobuf.TestProtos; -using NUnit.Framework; - -namespace Google.Protobuf -{ - public class DeprecatedMemberTest - { - private static void AssertIsDeprecated(MemberInfo member) - { - Assert.NotNull(member); - Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member); - } - - [Test] - public void TestDepreatedPrimitiveValue() - { - AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); - } - - } -} +#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 System; +using System.Reflection; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class DeprecatedMemberTest + { + private static void AssertIsDeprecated(MemberInfo member) + { + Assert.NotNull(member); + Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member); + } + + [Test] + public void TestDepreatedPrimitiveValue() + { + AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); + } + + } +}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs index 429c51f..61f3abb 100644 --- a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs +++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/GeneratedMessageTest.cs
@@ -1,725 +1,725 @@ -#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 System; -using System.IO; -using Google.Protobuf.TestProtos; -using NUnit.Framework; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Google.Protobuf.WellKnownTypes; - -namespace Google.Protobuf -{ - /// <summary> - /// Tests around the generated TestAllTypes message. - /// </summary> - public class GeneratedMessageTest - { - [Test] - public void EmptyMessageFieldDistinctFromMissingMessageField() - { - // This demonstrates what we're really interested in... - var message1 = new TestAllTypes { SingleForeignMessage = new ForeignMessage() }; - var message2 = new TestAllTypes(); // SingleForeignMessage is null - EqualityTester.AssertInequality(message1, message2); - } - - [Test] - public void DefaultValues() - { - // Single fields - var message = new TestAllTypes(); - Assert.AreEqual(false, message.SingleBool); - Assert.AreEqual(ByteString.Empty, message.SingleBytes); - Assert.AreEqual(0.0, message.SingleDouble); - Assert.AreEqual(0, message.SingleFixed32); - Assert.AreEqual(0L, message.SingleFixed64); - Assert.AreEqual(0.0f, message.SingleFloat); - Assert.AreEqual(ForeignEnum.ForeignUnspecified, message.SingleForeignEnum); - Assert.IsNull(message.SingleForeignMessage); - Assert.AreEqual(ImportEnum.Unspecified, message.SingleImportEnum); - Assert.IsNull(message.SingleImportMessage); - Assert.AreEqual(0, message.SingleInt32); - Assert.AreEqual(0L, message.SingleInt64); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.Unspecified, message.SingleNestedEnum); - Assert.IsNull(message.SingleNestedMessage); - Assert.IsNull(message.SinglePublicImportMessage); - Assert.AreEqual(0, message.SingleSfixed32); - Assert.AreEqual(0L, message.SingleSfixed64); - Assert.AreEqual(0, message.SingleSint32); - Assert.AreEqual(0L, message.SingleSint64); - Assert.AreEqual("", message.SingleString); - Assert.AreEqual(0U, message.SingleUint32); - Assert.AreEqual(0UL, message.SingleUint64); - - // Repeated fields - Assert.AreEqual(0, message.RepeatedBool.Count); - Assert.AreEqual(0, message.RepeatedBytes.Count); - Assert.AreEqual(0, message.RepeatedDouble.Count); - Assert.AreEqual(0, message.RepeatedFixed32.Count); - Assert.AreEqual(0, message.RepeatedFixed64.Count); - Assert.AreEqual(0, message.RepeatedFloat.Count); - Assert.AreEqual(0, message.RepeatedForeignEnum.Count); - Assert.AreEqual(0, message.RepeatedForeignMessage.Count); - Assert.AreEqual(0, message.RepeatedImportEnum.Count); - Assert.AreEqual(0, message.RepeatedImportMessage.Count); - Assert.AreEqual(0, message.RepeatedNestedEnum.Count); - Assert.AreEqual(0, message.RepeatedNestedMessage.Count); - Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count); - Assert.AreEqual(0, message.RepeatedSfixed32.Count); - Assert.AreEqual(0, message.RepeatedSfixed64.Count); - Assert.AreEqual(0, message.RepeatedSint32.Count); - Assert.AreEqual(0, message.RepeatedSint64.Count); - Assert.AreEqual(0, message.RepeatedString.Count); - Assert.AreEqual(0, message.RepeatedUint32.Count); - Assert.AreEqual(0, message.RepeatedUint64.Count); - - // Oneof fields - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - } - - [Test] - public void NullStringAndBytesRejected() - { - var message = new TestAllTypes(); - Assert.Throws<ArgumentNullException>(() => message.SingleString = null); - Assert.Throws<ArgumentNullException>(() => message.OneofString = null); - Assert.Throws<ArgumentNullException>(() => message.SingleBytes = null); - Assert.Throws<ArgumentNullException>(() => message.OneofBytes = null); - } - - [Test] - public void RoundTrip_Empty() - { - var message = new TestAllTypes(); - // 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); - } - - [Test] - public void RoundTrip_SingleValues() - { - var message = new TestAllTypes - { - SingleBool = true, - SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), - SingleDouble = 23.5, - SingleFixed32 = 23, - SingleFixed64 = 1234567890123, - SingleFloat = 12.25f, - SingleForeignEnum = ForeignEnum.ForeignBar, - SingleForeignMessage = new ForeignMessage { C = 10 }, - SingleImportEnum = ImportEnum.ImportBaz, - SingleImportMessage = new ImportMessage { D = 20 }, - SingleInt32 = 100, - SingleInt64 = 3210987654321, - SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, - SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, - SinglePublicImportMessage = new PublicImportMessage { E = 54 }, - SingleSfixed32 = -123, - SingleSfixed64 = -12345678901234, - SingleSint32 = -456, - SingleSint64 = -12345678901235, - SingleString = "test", - SingleUint32 = uint.MaxValue, - SingleUint64 = ulong.MaxValue - }; - - byte[] bytes = message.ToByteArray(); - TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); - Assert.AreEqual(message, parsed); - } - - [Test] - public void RoundTrip_RepeatedValues() - { - var message = new TestAllTypes - { - RepeatedBool = { true, false }, - RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, - RepeatedDouble = { -12.25, 23.5 }, - RepeatedFixed32 = { uint.MaxValue, 23 }, - RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, - RepeatedFloat = { 100f, 12.25f }, - RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar }, - RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, - RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified }, - RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, - RepeatedInt32 = { 100, 200 }, - RepeatedInt64 = { 3210987654321, long.MaxValue }, - RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, - RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, - RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, - RepeatedSfixed32 = { -123, 123 }, - RepeatedSfixed64 = { -12345678901234, 12345678901234 }, - RepeatedSint32 = { -456, 100 }, - RepeatedSint64 = { -12345678901235, 123 }, - RepeatedString = { "foo", "bar" }, - RepeatedUint32 = { uint.MaxValue, uint.MinValue }, - RepeatedUint64 = { ulong.MaxValue, uint.MinValue } - }; - - byte[] bytes = message.ToByteArray(); - TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); - Assert.AreEqual(message, parsed); - } - - // Note that not every map within map_unittest_proto3 is used. They all go through very - // similar code paths. The fact that all maps are present is validation that we have codecs - // for every type. - [Test] - public void RoundTrip_Maps() - { - var message = new TestMap - { - MapBoolBool = { - { false, true }, - { true, false } - }, - MapInt32Bytes = { - { 5, ByteString.CopyFrom(6, 7, 8) }, - { 25, ByteString.CopyFrom(1, 2, 3, 4, 5) }, - { 10, ByteString.Empty } - }, - MapInt32ForeignMessage = { - { 0, new ForeignMessage { C = 10 } }, - { 5, new ForeignMessage() }, - }, - MapInt32Enum = { - { 1, MapEnum.Bar }, - { 2000, MapEnum.Foo } - } - }; - - byte[] bytes = message.ToByteArray(); - TestMap parsed = TestMap.Parser.ParseFrom(bytes); - Assert.AreEqual(message, parsed); - } - - [Test] - public void MapWithEmptyEntry() - { - var message = new TestMap - { - MapInt32Bytes = { { 0, ByteString.Empty } } - }; - - 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]); - } - - [Test] - public void MapWithOnlyValue() - { - // Hand-craft the stream to contain a single entry with just a value. - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); - var nestedMessage = new ForeignMessage { C = 20 }; - // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage) - output.WriteLength(2 + nestedMessage.CalculateSize()); - output.WriteTag(2, WireFormat.WireType.LengthDelimited); - output.WriteMessage(nestedMessage); - output.Flush(); - - var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); - Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]); - } - - [Test] - public void MapWithOnlyKey_PrimitiveValue() - { - // Hand-craft the stream to contain a single entry with just a key. - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - output.WriteTag(TestMap.MapInt32DoubleFieldNumber, WireFormat.WireType.LengthDelimited); - int key = 10; - output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.Flush(); - - var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); - Assert.AreEqual(0.0, parsed.MapInt32Double[key]); - } - - [Test] - public void MapWithOnlyKey_MessageValue() - { - // Hand-craft the stream to contain a single entry with just a key. - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); - int key = 10; - output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.Flush(); - - var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); - Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]); - } - - [Test] - public void MapIgnoresExtraFieldsWithinEntryMessages() - { - // Hand-craft the stream to contain a single entry with three fields - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - - var key = 10; // Field 1 - var value = 20; // Field 2 - var extra = 30; // Field 3 - - // Each field can be represented in a single byte, with a single byte tag. - // Total message size: 6 bytes. - output.WriteLength(6); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value); - output.WriteTag(3, WireFormat.WireType.Varint); - output.WriteInt32(extra); - output.Flush(); - - var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); - Assert.AreEqual(value, parsed.MapInt32Int32[key]); - } - - [Test] - public void MapFieldOrderIsIrrelevant() - { - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - - var key = 10; - var value = 20; - - // Each field can be represented in a single byte, with a single byte tag. - // Total message size: 4 bytes. - output.WriteLength(4); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.Flush(); - - var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); - Assert.AreEqual(value, parsed.MapInt32Int32[key]); - } - - [Test] - public void MapNonContiguousEntries() - { - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - - // Message structure: - // Entry for MapInt32Int32 - // Entry for MapStringString - // Entry for MapInt32Int32 - - // First entry - var key1 = 10; - var value1 = 20; - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(4); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key1); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value1); - - // Second entry - var key2 = "a"; - var value2 = "b"; - output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(6); // 3 bytes per entry: tag, size, character - output.WriteTag(1, WireFormat.WireType.LengthDelimited); - output.WriteString(key2); - output.WriteTag(2, WireFormat.WireType.LengthDelimited); - output.WriteString(value2); - - // Third entry - var key3 = 15; - var value3 = 25; - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(4); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key3); - output.WriteTag(2, WireFormat.WireType.Varint); - 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); - } - - [Test] - public void DuplicateKeys_LastEntryWins() - { - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - - var key = 10; - var value1 = 20; - var value2 = 30; - - // First entry - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(4); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value1); - - // Second entry - same key, different value - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(4); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value2); - output.Flush(); - - var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); - Assert.AreEqual(value2, parsed.MapInt32Int32[key]); - } - - [Test] - public void CloneSingleNonMessageValues() - { - var original = new TestAllTypes - { - SingleBool = true, - SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), - SingleDouble = 23.5, - SingleFixed32 = 23, - SingleFixed64 = 1234567890123, - SingleFloat = 12.25f, - SingleInt32 = 100, - SingleInt64 = 3210987654321, - SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, - SingleSfixed32 = -123, - SingleSfixed64 = -12345678901234, - SingleSint32 = -456, - SingleSint64 = -12345678901235, - SingleString = "test", - SingleUint32 = uint.MaxValue, - SingleUint64 = ulong.MaxValue - }; - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreEqual(original, clone); - // Just as a single example - clone.SingleInt32 = 150; - Assert.AreNotEqual(original, clone); - } - - [Test] - public void CloneRepeatedNonMessageValues() - { - var original = new TestAllTypes - { - RepeatedBool = { true, false }, - RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, - RepeatedDouble = { -12.25, 23.5 }, - RepeatedFixed32 = { uint.MaxValue, 23 }, - RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, - RepeatedFloat = { 100f, 12.25f }, - RepeatedInt32 = { 100, 200 }, - RepeatedInt64 = { 3210987654321, long.MaxValue }, - RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, - RepeatedSfixed32 = { -123, 123 }, - RepeatedSfixed64 = { -12345678901234, 12345678901234 }, - RepeatedSint32 = { -456, 100 }, - RepeatedSint64 = { -12345678901235, 123 }, - RepeatedString = { "foo", "bar" }, - RepeatedUint32 = { uint.MaxValue, uint.MinValue }, - RepeatedUint64 = { ulong.MaxValue, uint.MinValue } - }; - - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreEqual(original, clone); - // Just as a single example - clone.RepeatedDouble.Add(25.5); - Assert.AreNotEqual(original, clone); - } - - [Test] - public void CloneSingleMessageField() - { - var original = new TestAllTypes - { - SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } - }; - - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreNotSame(original.SingleNestedMessage, clone.SingleNestedMessage); - Assert.AreEqual(original, clone); - - clone.SingleNestedMessage.Bb = 30; - Assert.AreNotEqual(original, clone); - } - - [Test] - public void CloneRepeatedMessageField() - { - var original = new TestAllTypes - { - RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 20 } } - }; - - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreNotSame(original.RepeatedNestedMessage, clone.RepeatedNestedMessage); - Assert.AreNotSame(original.RepeatedNestedMessage[0], clone.RepeatedNestedMessage[0]); - Assert.AreEqual(original, clone); - - clone.RepeatedNestedMessage[0].Bb = 30; - Assert.AreNotEqual(original, clone); - } - - [Test] - public void CloneOneofField() - { - var original = new TestAllTypes - { - OneofNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } - }; - - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreEqual(original, clone); - - // We should have cloned the message - original.OneofNestedMessage.Bb = 30; - Assert.AreNotEqual(original, clone); - } - - [Test] - public void OneofProperties() - { - // Switch the oneof case between each of the different options, and check everything behaves - // as expected in each case. - var message = new TestAllTypes(); - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); - - message.OneofString = "sample"; - Assert.AreEqual("sample", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase); - - var bytes = ByteString.CopyFrom(1, 2, 3); - message.OneofBytes = bytes; - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(bytes, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofBytes, message.OneofFieldCase); - - message.OneofUint32 = 20; - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(20, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase); - - var nestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 25 }; - message.OneofNestedMessage = nestedMessage; - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.AreEqual(nestedMessage, message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofNestedMessage, message.OneofFieldCase); - - message.ClearOneofField(); - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); - } - - [Test] - public void Oneof_DefaultValuesNotEqual() - { - var message1 = new TestAllTypes { OneofString = "" }; - var message2 = new TestAllTypes { OneofUint32 = 0 }; - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message1.OneofFieldCase); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); - Assert.AreNotEqual(message1, message2); - } - - [Test] - public void OneofSerialization_NonDefaultValue() - { - var message = new TestAllTypes(); - message.OneofString = "this would take a bit of space"; - message.OneofUint32 = 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); - } - - [Test] - public void OneofSerialization_DefaultValue() - { - var message = new TestAllTypes(); - message.OneofString = "this would take a bit of space"; - message.OneofUint32 = 0; // This is the default value for UInt32; normally wouldn't be serialized - 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); - } - - [Test] - public void DiscardUnknownFields_RealDataStillRead() - { - var message = SampleMessages.CreateFullTestAllTypes(); - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - var unusedFieldNumber = 23456; - Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber)); - output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteString("ignore me"); - message.WriteTo(output); - output.Flush(); - - stream.Position = 0; - var parsed = TestAllTypes.Parser.ParseFrom(stream); - // TODO(jieluo): Add test back after DiscardUnknownFields is supported - // Assert.AreEqual(message, parsed); - } - - [Test] - public void DiscardUnknownFields_AllTypes() - { - // 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 after DiscardUnknownField is supported. - // Assert.AreEqual(new Empty(), empty); - } - - // This was originally seen as a conformance test failure. - [Test] - public void TruncatedMessageFieldThrows() - { - // 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)); - } - - /// <summary> - /// Demonstrates current behaviour with an extraneous end group tag - see issue 688 - /// for details; we may want to change this. - /// </summary> - [Test] - public void ExtraEndGroupThrows() - { - var message = SampleMessages.CreateFullTestAllTypes(); - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - - output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32); - output.WriteFixed32(123); - output.WriteTag(100, WireFormat.WireType.EndGroup); - - output.Flush(); - - stream.Position = 0; - Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream)); - } - - [Test] - public void CustomDiagnosticMessage_DirectToStringCall() - { - var message = new ForeignMessage { C = 31 }; - Assert.AreEqual("{ \"c\": 31, \"@cInHex\": \"1f\" }", message.ToString()); - Assert.AreEqual("{ \"c\": 31 }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void CustomDiagnosticMessage_Nested() - { - var message = new TestAllTypes { SingleForeignMessage = new ForeignMessage { C = 16 } }; - Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16, \"@cInHex\": \"10\" } }", message.ToString()); - Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16 } }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void CustomDiagnosticMessage_DirectToTextWriterCall() - { - var message = new ForeignMessage { C = 31 }; - var writer = new StringWriter(); - JsonFormatter.Default.Format(message, writer); - Assert.AreEqual("{ \"c\": 31 }", writer.ToString()); - } - } -} +#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 System; +using System.IO; +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Google.Protobuf.WellKnownTypes; + +namespace Google.Protobuf +{ + /// <summary> + /// Tests around the generated TestAllTypes message. + /// </summary> + public class GeneratedMessageTest + { + [Test] + public void EmptyMessageFieldDistinctFromMissingMessageField() + { + // This demonstrates what we're really interested in... + var message1 = new TestAllTypes { SingleForeignMessage = new ForeignMessage() }; + var message2 = new TestAllTypes(); // SingleForeignMessage is null + EqualityTester.AssertInequality(message1, message2); + } + + [Test] + public void DefaultValues() + { + // Single fields + var message = new TestAllTypes(); + Assert.AreEqual(false, message.SingleBool); + Assert.AreEqual(ByteString.Empty, message.SingleBytes); + Assert.AreEqual(0.0, message.SingleDouble); + Assert.AreEqual(0, message.SingleFixed32); + Assert.AreEqual(0L, message.SingleFixed64); + Assert.AreEqual(0.0f, message.SingleFloat); + Assert.AreEqual(ForeignEnum.ForeignUnspecified, message.SingleForeignEnum); + Assert.IsNull(message.SingleForeignMessage); + Assert.AreEqual(ImportEnum.Unspecified, message.SingleImportEnum); + Assert.IsNull(message.SingleImportMessage); + Assert.AreEqual(0, message.SingleInt32); + Assert.AreEqual(0L, message.SingleInt64); + Assert.AreEqual(TestAllTypes.Types.NestedEnum.Unspecified, message.SingleNestedEnum); + Assert.IsNull(message.SingleNestedMessage); + Assert.IsNull(message.SinglePublicImportMessage); + Assert.AreEqual(0, message.SingleSfixed32); + Assert.AreEqual(0L, message.SingleSfixed64); + Assert.AreEqual(0, message.SingleSint32); + Assert.AreEqual(0L, message.SingleSint64); + Assert.AreEqual("", message.SingleString); + Assert.AreEqual(0U, message.SingleUint32); + Assert.AreEqual(0UL, message.SingleUint64); + + // Repeated fields + Assert.AreEqual(0, message.RepeatedBool.Count); + Assert.AreEqual(0, message.RepeatedBytes.Count); + Assert.AreEqual(0, message.RepeatedDouble.Count); + Assert.AreEqual(0, message.RepeatedFixed32.Count); + Assert.AreEqual(0, message.RepeatedFixed64.Count); + Assert.AreEqual(0, message.RepeatedFloat.Count); + Assert.AreEqual(0, message.RepeatedForeignEnum.Count); + Assert.AreEqual(0, message.RepeatedForeignMessage.Count); + Assert.AreEqual(0, message.RepeatedImportEnum.Count); + Assert.AreEqual(0, message.RepeatedImportMessage.Count); + Assert.AreEqual(0, message.RepeatedNestedEnum.Count); + Assert.AreEqual(0, message.RepeatedNestedMessage.Count); + Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count); + Assert.AreEqual(0, message.RepeatedSfixed32.Count); + Assert.AreEqual(0, message.RepeatedSfixed64.Count); + Assert.AreEqual(0, message.RepeatedSint32.Count); + Assert.AreEqual(0, message.RepeatedSint64.Count); + Assert.AreEqual(0, message.RepeatedString.Count); + Assert.AreEqual(0, message.RepeatedUint32.Count); + Assert.AreEqual(0, message.RepeatedUint64.Count); + + // Oneof fields + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + } + + [Test] + public void NullStringAndBytesRejected() + { + var message = new TestAllTypes(); + Assert.Throws<ArgumentNullException>(() => message.SingleString = null); + Assert.Throws<ArgumentNullException>(() => message.OneofString = null); + Assert.Throws<ArgumentNullException>(() => message.SingleBytes = null); + Assert.Throws<ArgumentNullException>(() => message.OneofBytes = null); + } + + [Test] + public void RoundTrip_Empty() + { + var message = new TestAllTypes(); + // 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); + } + + [Test] + public void RoundTrip_SingleValues() + { + var message = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleForeignEnum = ForeignEnum.ForeignBar, + SingleForeignMessage = new ForeignMessage { C = 10 }, + SingleImportEnum = ImportEnum.ImportBaz, + SingleImportMessage = new ImportMessage { D = 20 }, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, + SinglePublicImportMessage = new PublicImportMessage { E = 54 }, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + + byte[] bytes = message.ToByteArray(); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void RoundTrip_RepeatedValues() + { + var message = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar }, + RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, + RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified }, + RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, + RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { uint.MaxValue, uint.MinValue }, + RepeatedUint64 = { ulong.MaxValue, uint.MinValue } + }; + + byte[] bytes = message.ToByteArray(); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + // Note that not every map within map_unittest_proto3 is used. They all go through very + // similar code paths. The fact that all maps are present is validation that we have codecs + // for every type. + [Test] + public void RoundTrip_Maps() + { + var message = new TestMap + { + MapBoolBool = { + { false, true }, + { true, false } + }, + MapInt32Bytes = { + { 5, ByteString.CopyFrom(6, 7, 8) }, + { 25, ByteString.CopyFrom(1, 2, 3, 4, 5) }, + { 10, ByteString.Empty } + }, + MapInt32ForeignMessage = { + { 0, new ForeignMessage { C = 10 } }, + { 5, new ForeignMessage() }, + }, + MapInt32Enum = { + { 1, MapEnum.Bar }, + { 2000, MapEnum.Foo } + } + }; + + byte[] bytes = message.ToByteArray(); + TestMap parsed = TestMap.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void MapWithEmptyEntry() + { + var message = new TestMap + { + MapInt32Bytes = { { 0, ByteString.Empty } } + }; + + 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]); + } + + [Test] + public void MapWithOnlyValue() + { + // Hand-craft the stream to contain a single entry with just a value. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); + var nestedMessage = new ForeignMessage { C = 20 }; + // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage) + output.WriteLength(2 + nestedMessage.CalculateSize()); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteMessage(nestedMessage); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]); + } + + [Test] + public void MapWithOnlyKey_PrimitiveValue() + { + // Hand-craft the stream to contain a single entry with just a key. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32DoubleFieldNumber, WireFormat.WireType.LengthDelimited); + int key = 10; + output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(0.0, parsed.MapInt32Double[key]); + } + + [Test] + public void MapWithOnlyKey_MessageValue() + { + // Hand-craft the stream to contain a single entry with just a key. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); + int key = 10; + output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]); + } + + [Test] + public void MapIgnoresExtraFieldsWithinEntryMessages() + { + // Hand-craft the stream to contain a single entry with three fields + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + + var key = 10; // Field 1 + var value = 20; // Field 2 + var extra = 30; // Field 3 + + // Each field can be represented in a single byte, with a single byte tag. + // Total message size: 6 bytes. + output.WriteLength(6); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value); + output.WriteTag(3, WireFormat.WireType.Varint); + output.WriteInt32(extra); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value, parsed.MapInt32Int32[key]); + } + + [Test] + public void MapFieldOrderIsIrrelevant() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + + var key = 10; + var value = 20; + + // Each field can be represented in a single byte, with a single byte tag. + // Total message size: 4 bytes. + output.WriteLength(4); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value, parsed.MapInt32Int32[key]); + } + + [Test] + public void MapNonContiguousEntries() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + // Message structure: + // Entry for MapInt32Int32 + // Entry for MapStringString + // Entry for MapInt32Int32 + + // First entry + var key1 = 10; + var value1 = 20; + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key1); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value1); + + // Second entry + var key2 = "a"; + var value2 = "b"; + output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(6); // 3 bytes per entry: tag, size, character + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString(key2); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteString(value2); + + // Third entry + var key3 = 15; + var value3 = 25; + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key3); + output.WriteTag(2, WireFormat.WireType.Varint); + 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); + } + + [Test] + public void DuplicateKeys_LastEntryWins() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + var key = 10; + var value1 = 20; + var value2 = 30; + + // First entry + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value1); + + // Second entry - same key, different value + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value2); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value2, parsed.MapInt32Int32[key]); + } + + [Test] + public void CloneSingleNonMessageValues() + { + var original = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + // Just as a single example + clone.SingleInt32 = 150; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneRepeatedNonMessageValues() + { + var original = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { uint.MaxValue, uint.MinValue }, + RepeatedUint64 = { ulong.MaxValue, uint.MinValue } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + // Just as a single example + clone.RepeatedDouble.Add(25.5); + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneSingleMessageField() + { + var original = new TestAllTypes + { + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreNotSame(original.SingleNestedMessage, clone.SingleNestedMessage); + Assert.AreEqual(original, clone); + + clone.SingleNestedMessage.Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneRepeatedMessageField() + { + var original = new TestAllTypes + { + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 20 } } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreNotSame(original.RepeatedNestedMessage, clone.RepeatedNestedMessage); + Assert.AreNotSame(original.RepeatedNestedMessage[0], clone.RepeatedNestedMessage[0]); + Assert.AreEqual(original, clone); + + clone.RepeatedNestedMessage[0].Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneOneofField() + { + var original = new TestAllTypes + { + OneofNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + + // We should have cloned the message + original.OneofNestedMessage.Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void OneofProperties() + { + // Switch the oneof case between each of the different options, and check everything behaves + // as expected in each case. + var message = new TestAllTypes(); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + + message.OneofString = "sample"; + Assert.AreEqual("sample", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase); + + var bytes = ByteString.CopyFrom(1, 2, 3); + message.OneofBytes = bytes; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(bytes, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofBytes, message.OneofFieldCase); + + message.OneofUint32 = 20; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(20, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase); + + var nestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 25 }; + message.OneofNestedMessage = nestedMessage; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.AreEqual(nestedMessage, message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofNestedMessage, message.OneofFieldCase); + + message.ClearOneofField(); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + } + + [Test] + public void Oneof_DefaultValuesNotEqual() + { + var message1 = new TestAllTypes { OneofString = "" }; + var message2 = new TestAllTypes { OneofUint32 = 0 }; + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message1.OneofFieldCase); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); + Assert.AreNotEqual(message1, message2); + } + + [Test] + public void OneofSerialization_NonDefaultValue() + { + var message = new TestAllTypes(); + message.OneofString = "this would take a bit of space"; + message.OneofUint32 = 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); + } + + [Test] + public void OneofSerialization_DefaultValue() + { + var message = new TestAllTypes(); + message.OneofString = "this would take a bit of space"; + message.OneofUint32 = 0; // This is the default value for UInt32; normally wouldn't be serialized + 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); + } + + [Test] + public void DiscardUnknownFields_RealDataStillRead() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var unusedFieldNumber = 23456; + Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber)); + output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteString("ignore me"); + message.WriteTo(output); + output.Flush(); + + stream.Position = 0; + var parsed = TestAllTypes.Parser.ParseFrom(stream); + // TODO(jieluo): Add test back after DiscardUnknownFields is supported + // Assert.AreEqual(message, parsed); + } + + [Test] + public void DiscardUnknownFields_AllTypes() + { + // 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 after DiscardUnknownField is supported. + // Assert.AreEqual(new Empty(), empty); + } + + // This was originally seen as a conformance test failure. + [Test] + public void TruncatedMessageFieldThrows() + { + // 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)); + } + + /// <summary> + /// Demonstrates current behaviour with an extraneous end group tag - see issue 688 + /// for details; we may want to change this. + /// </summary> + [Test] + public void ExtraEndGroupThrows() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + + output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32); + output.WriteFixed32(123); + output.WriteTag(100, WireFormat.WireType.EndGroup); + + output.Flush(); + + stream.Position = 0; + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream)); + } + + [Test] + public void CustomDiagnosticMessage_DirectToStringCall() + { + var message = new ForeignMessage { C = 31 }; + Assert.AreEqual("{ \"c\": 31, \"@cInHex\": \"1f\" }", message.ToString()); + Assert.AreEqual("{ \"c\": 31 }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void CustomDiagnosticMessage_Nested() + { + var message = new TestAllTypes { SingleForeignMessage = new ForeignMessage { C = 16 } }; + Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16, \"@cInHex\": \"10\" } }", message.ToString()); + Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16 } }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void CustomDiagnosticMessage_DirectToTextWriterCall() + { + var message = new ForeignMessage { C = 31 }; + var writer = new StringWriter(); + JsonFormatter.Default.Format(message, writer); + Assert.AreEqual("{ \"c\": 31 }", writer.ToString()); + } + } +}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs index a38d6b0..b4022a2 100644 --- a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs +++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/IssuesTest.cs
@@ -1,82 +1,82 @@ -#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.Reflection; -using UnitTest.Issues.TestProtos; -using NUnit.Framework; - - -namespace Google.Protobuf -{ - /// <summary> - /// Tests for issues which aren't easily compartmentalized into other unit tests. - /// </summary> - public class IssuesTest - { - // Issue 45 - [Test] - public void FieldCalledItem() - { - ItemField message = new ItemField { Item = 3 }; - FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item"); - Assert.NotNull(field); - Assert.AreEqual(3, (int)field.Accessor.GetValue(message)); - } - - [Test] - public void ReservedNames() - { - var message = new ReservedNames { Types_ = 10, Descriptor_ = 20 }; - // Underscores aren't reflected in the JSON. - Assert.AreEqual("{ \"types\": 10, \"descriptor\": 20 }", message.ToString()); - } - - [Test] - public void JsonNameParseTest() - { - var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor)); - var parser = new JsonParser(settings); - - // It is safe to use either original field name or explicitly specified json_name - Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }, - parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }")); - } - - [Test] - public void JsonNameFormatTest() - { - var message = new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }; - Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }", - JsonFormatter.Default.Format(message)); - } - } -} +#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.Reflection; +using UnitTest.Issues.TestProtos; +using NUnit.Framework; + + +namespace Google.Protobuf +{ + /// <summary> + /// Tests for issues which aren't easily compartmentalized into other unit tests. + /// </summary> + public class IssuesTest + { + // Issue 45 + [Test] + public void FieldCalledItem() + { + ItemField message = new ItemField { Item = 3 }; + FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item"); + Assert.NotNull(field); + Assert.AreEqual(3, (int)field.Accessor.GetValue(message)); + } + + [Test] + public void ReservedNames() + { + var message = new ReservedNames { Types_ = 10, Descriptor_ = 20 }; + // Underscores aren't reflected in the JSON. + Assert.AreEqual("{ \"types\": 10, \"descriptor\": 20 }", message.ToString()); + } + + [Test] + public void JsonNameParseTest() + { + var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor)); + var parser = new JsonParser(settings); + + // It is safe to use either original field name or explicitly specified json_name + Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }, + parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }")); + } + + [Test] + public void JsonNameFormatTest() + { + var message = new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }; + Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }", + JsonFormatter.Default.Format(message)); + } + } +}
diff --git a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs index 248f5fa..859b49c 100644 --- a/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs +++ b/csharp/compatibility_tests/v3.0.0/src/Google.Protobuf.Test/TestCornerCases.cs
@@ -1,62 +1,62 @@ -#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 UnitTest.Issues.TestProtos; -using NUnit.Framework; - -namespace Google.Protobuf -{ - public class TestCornerCases - { - [Test] - public void TestRoundTripNegativeEnums() - { - NegativeEnumMessage msg = new NegativeEnumMessage - { - Value = NegativeEnum.MinusOne, - Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }, - PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow } - }; - - Assert.AreEqual(58, msg.CalculateSize()); - - byte[] bytes = new byte[58]; - CodedOutputStream output = new CodedOutputStream(bytes); - - msg.WriteTo(output); - Assert.AreEqual(0, output.SpaceLeft); - - NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes); - Assert.AreEqual(msg, copy); - } - } -} +#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 UnitTest.Issues.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class TestCornerCases + { + [Test] + public void TestRoundTripNegativeEnums() + { + NegativeEnumMessage msg = new NegativeEnumMessage + { + Value = NegativeEnum.MinusOne, + Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }, + PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow } + }; + + Assert.AreEqual(58, msg.CalculateSize()); + + byte[] bytes = new byte[58]; + CodedOutputStream output = new CodedOutputStream(bytes); + + msg.WriteTo(output); + Assert.AreEqual(0, output.SpaceLeft); + + NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes); + Assert.AreEqual(msg, copy); + } + } +}
diff --git a/csharp/generate_protos.sh b/csharp/generate_protos.sh index b663138..b021de2 100755 --- a/csharp/generate_protos.sh +++ b/csharp/generate_protos.sh
@@ -13,7 +13,9 @@ # Windows and Unix. if [ -z "$PROTOC" ]; then # TODO(jonskeet): Use an array and a for loop instead? - if [ -x cmake/build/Debug/protoc.exe ]; then + if [ -x solution/Debug/protoc.exe ]; then + PROTOC=solution/Debug/protoc.exe + elif [ -x cmake/build/Debug/protoc.exe ]; then PROTOC=cmake/build/Debug/protoc.exe elif [ -x cmake/build/Release/protoc.exe ]; then PROTOC=cmake/build/Release/protoc.exe
diff --git a/csharp/protos/unittest_issues.proto b/csharp/protos/unittest_issues.proto index 388998f..f46c20e 100644 --- a/csharp/protos/unittest_issues.proto +++ b/csharp/protos/unittest_issues.proto
@@ -156,3 +156,17 @@ string regular_field = 1; optional string optional_field = 2; } + +message OneofWithNoneField { + oneof test { + string x = 1; + string none = 2; + } +} + +message OneofWithNoneName { + oneof none { + string x = 1; + string y = 2; + } +} \ No newline at end of file
diff --git a/csharp/src/AddressBook/AddPerson.cs b/csharp/src/AddressBook/AddPerson.cs index 62d1788..889d1d0 100644 --- a/csharp/src/AddressBook/AddPerson.cs +++ b/csharp/src/AddressBook/AddPerson.cs
@@ -1,132 +1,132 @@ -#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.IO; - -namespace Google.Protobuf.Examples.AddressBook -{ - internal class AddPerson - { - /// <summary> - /// Builds a person based on user input - /// </summary> - private static Person PromptForAddress(TextReader input, TextWriter output) - { - Person person = new Person(); - - output.Write("Enter person ID: "); - person.Id = int.Parse(input.ReadLine()); - - output.Write("Enter name: "); - person.Name = input.ReadLine(); - - output.Write("Enter email address (blank for none): "); - string email = input.ReadLine(); - if (email.Length > 0) - { - person.Email = email; - } - - while (true) - { - output.Write("Enter a phone number (or leave blank to finish): "); - string number = input.ReadLine(); - if (number.Length == 0) - { - break; - } - - Person.Types.PhoneNumber phoneNumber = new Person.Types.PhoneNumber { Number = number }; - - output.Write("Is this a mobile, home, or work phone? "); - String type = input.ReadLine(); - switch (type) - { - case "mobile": - phoneNumber.Type = Person.Types.PhoneType.Mobile; - break; - case "home": - phoneNumber.Type = Person.Types.PhoneType.Home; - break; - case "work": - phoneNumber.Type = Person.Types.PhoneType.Work; - break; - default: - output.Write("Unknown phone type. Using default."); - break; - } - - person.Phones.Add(phoneNumber); - } - return person; - } - - /// <summary> - /// Entry point - loads an existing addressbook or creates a new one, - /// then writes it back to the file. - /// </summary> - public static int Main(string[] args) - { - if (args.Length != 1) - { - Console.Error.WriteLine("Usage: AddPerson ADDRESS_BOOK_FILE"); - return -1; - } - - AddressBook addressBook; - - if (File.Exists(args[0])) - { - using (Stream file = File.OpenRead(args[0])) - { - addressBook = AddressBook.Parser.ParseFrom(file); - } - } - else - { - Console.WriteLine("{0}: File not found. Creating a new file.", args[0]); - addressBook = new AddressBook(); - } - - // Add an address. - addressBook.People.Add(PromptForAddress(Console.In, Console.Out)); - - // Write the new address book back to disk. - using (Stream output = File.OpenWrite(args[0])) - { - addressBook.WriteTo(output); - } - return 0; - } - } +#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.IO; + +namespace Google.Protobuf.Examples.AddressBook +{ + internal class AddPerson + { + /// <summary> + /// Builds a person based on user input + /// </summary> + private static Person PromptForAddress(TextReader input, TextWriter output) + { + Person person = new Person(); + + output.Write("Enter person ID: "); + person.Id = int.Parse(input.ReadLine()); + + output.Write("Enter name: "); + person.Name = input.ReadLine(); + + output.Write("Enter email address (blank for none): "); + string email = input.ReadLine(); + if (email.Length > 0) + { + person.Email = email; + } + + while (true) + { + output.Write("Enter a phone number (or leave blank to finish): "); + string number = input.ReadLine(); + if (number.Length == 0) + { + break; + } + + Person.Types.PhoneNumber phoneNumber = new Person.Types.PhoneNumber { Number = number }; + + output.Write("Is this a mobile, home, or work phone? "); + String type = input.ReadLine(); + switch (type) + { + case "mobile": + phoneNumber.Type = Person.Types.PhoneType.Mobile; + break; + case "home": + phoneNumber.Type = Person.Types.PhoneType.Home; + break; + case "work": + phoneNumber.Type = Person.Types.PhoneType.Work; + break; + default: + output.Write("Unknown phone type. Using default."); + break; + } + + person.Phones.Add(phoneNumber); + } + return person; + } + + /// <summary> + /// Entry point - loads an existing addressbook or creates a new one, + /// then writes it back to the file. + /// </summary> + public static int Main(string[] args) + { + if (args.Length != 1) + { + Console.Error.WriteLine("Usage: AddPerson ADDRESS_BOOK_FILE"); + return -1; + } + + AddressBook addressBook; + + if (File.Exists(args[0])) + { + using (Stream file = File.OpenRead(args[0])) + { + addressBook = AddressBook.Parser.ParseFrom(file); + } + } + else + { + Console.WriteLine("{0}: File not found. Creating a new file.", args[0]); + addressBook = new AddressBook(); + } + + // Add an address. + addressBook.People.Add(PromptForAddress(Console.In, Console.Out)); + + // Write the new address book back to disk. + using (Stream output = File.OpenWrite(args[0])) + { + addressBook.WriteTo(output); + } + return 0; + } + } } \ No newline at end of file
diff --git a/csharp/src/AddressBook/ListPeople.cs b/csharp/src/AddressBook/ListPeople.cs index 3758c1b..fdcd64d 100644 --- a/csharp/src/AddressBook/ListPeople.cs +++ b/csharp/src/AddressBook/ListPeople.cs
@@ -1,99 +1,99 @@ -#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.IO; - -namespace Google.Protobuf.Examples.AddressBook -{ - internal class ListPeople - { - /// <summary> - /// Iterates though all people in the AddressBook and prints info about them. - /// </summary> - private static void Print(AddressBook addressBook) - { - foreach (Person person in addressBook.People) - { - Console.WriteLine("Person ID: {0}", person.Id); - Console.WriteLine(" Name: {0}", person.Name); - if (person.Email != "") - { - Console.WriteLine(" E-mail address: {0}", person.Email); - } - - foreach (Person.Types.PhoneNumber phoneNumber in person.Phones) - { - switch (phoneNumber.Type) - { - case Person.Types.PhoneType.Mobile: - Console.Write(" Mobile phone #: "); - break; - case Person.Types.PhoneType.Home: - Console.Write(" Home phone #: "); - break; - case Person.Types.PhoneType.Work: - Console.Write(" Work phone #: "); - break; - } - Console.WriteLine(phoneNumber.Number); - } - } - } - - /// <summary> - /// Entry point - loads the addressbook and then displays it. - /// </summary> - public static int Main(string[] args) - { - if (args.Length != 1) - { - Console.Error.WriteLine("Usage: ListPeople ADDRESS_BOOK_FILE"); - return 1; - } - - if (!File.Exists(args[0])) - { - Console.WriteLine("{0} doesn't exist. Add a person to create the file first.", args[0]); - return 0; - } - - // Read the existing address book. - using (Stream stream = File.OpenRead(args[0])) - { - AddressBook addressBook = AddressBook.Parser.ParseFrom(stream); - Print(addressBook); - } - return 0; - } - } +#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.IO; + +namespace Google.Protobuf.Examples.AddressBook +{ + internal class ListPeople + { + /// <summary> + /// Iterates though all people in the AddressBook and prints info about them. + /// </summary> + private static void Print(AddressBook addressBook) + { + foreach (Person person in addressBook.People) + { + Console.WriteLine("Person ID: {0}", person.Id); + Console.WriteLine(" Name: {0}", person.Name); + if (person.Email != "") + { + Console.WriteLine(" E-mail address: {0}", person.Email); + } + + foreach (Person.Types.PhoneNumber phoneNumber in person.Phones) + { + switch (phoneNumber.Type) + { + case Person.Types.PhoneType.Mobile: + Console.Write(" Mobile phone #: "); + break; + case Person.Types.PhoneType.Home: + Console.Write(" Home phone #: "); + break; + case Person.Types.PhoneType.Work: + Console.Write(" Work phone #: "); + break; + } + Console.WriteLine(phoneNumber.Number); + } + } + } + + /// <summary> + /// Entry point - loads the addressbook and then displays it. + /// </summary> + public static int Main(string[] args) + { + if (args.Length != 1) + { + Console.Error.WriteLine("Usage: ListPeople ADDRESS_BOOK_FILE"); + return 1; + } + + if (!File.Exists(args[0])) + { + Console.WriteLine("{0} doesn't exist. Add a person to create the file first.", args[0]); + return 0; + } + + // Read the existing address book. + using (Stream stream = File.OpenRead(args[0])) + { + AddressBook addressBook = AddressBook.Parser.ParseFrom(stream); + Print(addressBook); + } + return 0; + } + } } \ No newline at end of file
diff --git a/csharp/src/AddressBook/Program.cs b/csharp/src/AddressBook/Program.cs index de4867a..5bbe84c 100644 --- a/csharp/src/AddressBook/Program.cs +++ b/csharp/src/AddressBook/Program.cs
@@ -1,95 +1,95 @@ -#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; - -namespace Google.Protobuf.Examples.AddressBook -{ - /// <summary> - /// Entry point. Repeatedly prompts user for an action to take, delegating actual behaviour - /// to individual actions. Each action has its own Main method, so that it can be used as an - /// individual complete program. - /// </summary> - internal class Program - { - private static int Main(string[] args) - { - if (args.Length > 1) - { - Console.Error.WriteLine("Usage: AddressBook [file]"); - Console.Error.WriteLine("If the filename isn't specified, \"addressbook.data\" is used instead."); - return 1; - } - string addressBookFile = args.Length > 0 ? args[0] : "addressbook.data"; - - bool stopping = false; - while (!stopping) - { - Console.WriteLine("Options:"); - Console.WriteLine(" L: List contents"); - Console.WriteLine(" A: Add new person"); - Console.WriteLine(" Q: Quit"); - Console.Write("Action? "); - Console.Out.Flush(); - char choice = Console.ReadKey().KeyChar; - Console.WriteLine(); - try - { - switch (choice) - { - case 'A': - case 'a': - AddPerson.Main(new string[] {addressBookFile}); - break; - case 'L': - case 'l': - ListPeople.Main(new string[] {addressBookFile}); - break; - case 'Q': - case 'q': - stopping = true; - break; - default: - Console.WriteLine("Unknown option: {0}", choice); - break; - } - } - catch (Exception e) - { - Console.WriteLine("Exception executing action: {0}", e); - } - Console.WriteLine(); - } - return 0; - } - } +#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; + +namespace Google.Protobuf.Examples.AddressBook +{ + /// <summary> + /// Entry point. Repeatedly prompts user for an action to take, delegating actual behaviour + /// to individual actions. Each action has its own Main method, so that it can be used as an + /// individual complete program. + /// </summary> + internal class Program + { + private static int Main(string[] args) + { + if (args.Length > 1) + { + Console.Error.WriteLine("Usage: AddressBook [file]"); + Console.Error.WriteLine("If the filename isn't specified, \"addressbook.data\" is used instead."); + return 1; + } + string addressBookFile = args.Length > 0 ? args[0] : "addressbook.data"; + + bool stopping = false; + while (!stopping) + { + Console.WriteLine("Options:"); + Console.WriteLine(" L: List contents"); + Console.WriteLine(" A: Add new person"); + Console.WriteLine(" Q: Quit"); + Console.Write("Action? "); + Console.Out.Flush(); + char choice = Console.ReadKey().KeyChar; + Console.WriteLine(); + try + { + switch (choice) + { + case 'A': + case 'a': + AddPerson.Main(new string[] {addressBookFile}); + break; + case 'L': + case 'l': + ListPeople.Main(new string[] {addressBookFile}); + break; + case 'Q': + case 'q': + stopping = true; + break; + default: + Console.WriteLine("Unknown option: {0}", choice); + break; + } + } + catch (Exception e) + { + Console.WriteLine("Exception executing action: {0}", e); + } + Console.WriteLine(); + } + return 0; + } + } } \ No newline at end of file
diff --git a/csharp/src/AddressBook/SampleUsage.cs b/csharp/src/AddressBook/SampleUsage.cs index 941d865..8f08f0f 100644 --- a/csharp/src/AddressBook/SampleUsage.cs +++ b/csharp/src/AddressBook/SampleUsage.cs
@@ -1,73 +1,73 @@ -#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.IO; - -namespace Google.Protobuf.Examples.AddressBook -{ - internal class SampleUsage - { - private static void Main() - { - byte[] bytes; - // Create a new person - Person person = new Person - { - Id = 1, - Name = "Foo", - Email = "foo@bar", - Phones = { new Person.Types.PhoneNumber { Number = "555-1212" } } - }; - using (MemoryStream stream = new MemoryStream()) - { - // Save the person to a stream - person.WriteTo(stream); - bytes = stream.ToArray(); - } - Person copy = Person.Parser.ParseFrom(bytes); - - AddressBook book = new AddressBook - { - People = { copy } - }; - bytes = book.ToByteArray(); - // And read the address book back again - AddressBook restored = AddressBook.Parser.ParseFrom(bytes); - // The message performs a deep-comparison on equality: - if (restored.People.Count != 1 || !person.Equals(restored.People[0])) - { - throw new Exception("There is a bad person in here!"); - } - } - } +#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.IO; + +namespace Google.Protobuf.Examples.AddressBook +{ + internal class SampleUsage + { + private static void Main() + { + byte[] bytes; + // Create a new person + Person person = new Person + { + Id = 1, + Name = "Foo", + Email = "foo@bar", + Phones = { new Person.Types.PhoneNumber { Number = "555-1212" } } + }; + using (MemoryStream stream = new MemoryStream()) + { + // Save the person to a stream + person.WriteTo(stream); + bytes = stream.ToArray(); + } + Person copy = Person.Parser.ParseFrom(bytes); + + AddressBook book = new AddressBook + { + People = { copy } + }; + bytes = book.ToByteArray(); + // And read the address book back again + AddressBook restored = AddressBook.Parser.ParseFrom(bytes); + // The message performs a deep-comparison on equality: + if (restored.People.Count != 1 || !person.Equals(restored.People[0])) + { + throw new Exception("There is a bad person in here!"); + } + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj b/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj index ac8e009a..fee5f65 100644 --- a/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj +++ b/csharp/src/Google.Protobuf.Benchmarks/Google.Protobuf.Benchmarks.csproj
@@ -2,7 +2,7 @@ <PropertyGroup> <OutputType>Exe</OutputType> - <TargetFramework>net5.0</TargetFramework> + <TargetFramework>net6.0</TargetFramework> <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile> <SignAssembly>true</SignAssembly> <IsPackable>False</IsPackable> @@ -15,7 +15,7 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="BenchmarkDotNet" Version="0.12.1" /> + <PackageReference Include="BenchmarkDotNet" Version="0.13.1" /> <ProjectReference Include="..\Google.Protobuf\Google.Protobuf.csproj" /> </ItemGroup>
diff --git a/csharp/src/Google.Protobuf.Benchmarks/GoogleMessageBenchmark.cs b/csharp/src/Google.Protobuf.Benchmarks/GoogleMessageBenchmark.cs index 132967e..40fb3ba 100644 --- a/csharp/src/Google.Protobuf.Benchmarks/GoogleMessageBenchmark.cs +++ b/csharp/src/Google.Protobuf.Benchmarks/GoogleMessageBenchmark.cs
@@ -41,8 +41,8 @@ /// 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 + /// See https://github.com/protocolbuffers/protobuf/blob/main/benchmarks/README.md + /// See https://github.com/protocolbuffers/protobuf/blob/main/docs/performance.md /// </summary> [MemoryDiagnoser] public class GoogleMessageBenchmark
diff --git a/csharp/src/Google.Protobuf.JsonDump/Program.cs b/csharp/src/Google.Protobuf.JsonDump/Program.cs index 296b2f3..56e32ad 100644 --- a/csharp/src/Google.Protobuf.JsonDump/Program.cs +++ b/csharp/src/Google.Protobuf.JsonDump/Program.cs
@@ -1,73 +1,73 @@ -#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.IO; -using System.Reflection; - -namespace Google.Protobuf.ProtoDump -{ - /// <summary> - /// Small utility to load a binary message and dump it in JSON format. - /// </summary> - internal class Program - { - private static int Main(string[] args) - { - if (args.Length != 2) - { - Console.Error.WriteLine("Usage: Google.Protobuf.JsonDump <descriptor type name> <input data>"); - Console.Error.WriteLine("The descriptor type name is the fully-qualified message name,"); - Console.Error.WriteLine("including assembly e.g. ProjectNamespace.Message,Company.Project"); - return 1; - } - Type type = Type.GetType(args[0]); - if (type == null) - { - Console.Error.WriteLine("Unable to load type {0}.", args[0]); - return 1; - } - if (!typeof(IMessage).GetTypeInfo().IsAssignableFrom(type)) - { - Console.Error.WriteLine("Type {0} doesn't implement IMessage.", args[0]); - return 1; - } - IMessage message = (IMessage) Activator.CreateInstance(type); - using (var input = File.OpenRead(args[1])) - { - message.MergeFrom(input); - } - Console.WriteLine(message); - return 0; - } - } +#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.IO; +using System.Reflection; + +namespace Google.Protobuf.ProtoDump +{ + /// <summary> + /// Small utility to load a binary message and dump it in JSON format. + /// </summary> + internal class Program + { + private static int Main(string[] args) + { + if (args.Length != 2) + { + Console.Error.WriteLine("Usage: Google.Protobuf.JsonDump <descriptor type name> <input data>"); + Console.Error.WriteLine("The descriptor type name is the fully-qualified message name,"); + Console.Error.WriteLine("including assembly e.g. ProjectNamespace.Message,Company.Project"); + return 1; + } + Type type = Type.GetType(args[0]); + if (type == null) + { + Console.Error.WriteLine("Unable to load type {0}.", args[0]); + return 1; + } + if (!typeof(IMessage).GetTypeInfo().IsAssignableFrom(type)) + { + Console.Error.WriteLine("Type {0} doesn't implement IMessage.", args[0]); + return 1; + } + IMessage message = (IMessage) Activator.CreateInstance(type); + using (var input = File.OpenRead(args[1])) + { + message.MergeFrom(input); + } + Console.WriteLine(message); + return 0; + } + } } \ No newline at end of file
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 5030043..8d9d64b 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
@@ -1,25 +1,25 @@ -<Project Sdk="Microsoft.NET.Sdk"> - - <!-- - This TestProtos project is kept separate from the original test project for many reasons. - It allows us to make sure code can compile on a separate compiler version, different frameworks, - and without the internal visibility from the test project (all of which have caused issues in the past). - --> - <PropertyGroup> - <TargetFrameworks>net45;netstandard1.1;netstandard2.0</TargetFrameworks> - <LangVersion>3.0</LangVersion> - <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile> - <SignAssembly>true</SignAssembly> - <IsPackable>False</IsPackable> - </PropertyGroup> - - <!-- Needed for the net45 build to work on Unix. See https://github.com/dotnet/designs/pull/33 --> - <ItemGroup> - <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" /> - </ItemGroup> - - <ItemGroup> - <ProjectReference Include="..\Google.Protobuf\Google.Protobuf.csproj" /> - </ItemGroup> - -</Project> +<Project Sdk="Microsoft.NET.Sdk"> + + <!-- + This TestProtos project is kept separate from the original test project for many reasons. + It allows us to make sure code can compile on a separate compiler version, different frameworks, + and without the internal visibility from the test project (all of which have caused issues in the past). + --> + <PropertyGroup> + <TargetFrameworks>net462;netstandard1.1;netstandard2.0</TargetFrameworks> + <LangVersion>3.0</LangVersion> + <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile> + <SignAssembly>true</SignAssembly> + <IsPackable>False</IsPackable> + </PropertyGroup> + + <!-- Needed for the net45 build to work on Unix. See https://github.com/dotnet/designs/pull/33 --> + <ItemGroup> + <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="All" /> + </ItemGroup> + + <ItemGroup> + <ProjectReference Include="..\Google.Protobuf\Google.Protobuf.csproj" /> + </ItemGroup> + +</Project>
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto3.cs b/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto3.cs index 71e803c..5a2aa3b 100644 --- a/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto3.cs +++ b/csharp/src/Google.Protobuf.Test.TestProtos/TestMessagesProto3.cs
@@ -226,7 +226,7 @@ "dG8zLkZvcmVpZ25FbnVtOgI4ASI5CgpOZXN0ZWRFbnVtEgcKA0ZPTxAAEgcK", "A0JBUhABEgcKA0JBWhACEhAKA05FRxD///////////8BIlkKC0FsaWFzZWRF", "bnVtEg0KCUFMSUFTX0ZPTxAAEg0KCUFMSUFTX0JBUhABEg0KCUFMSUFTX0JB", - "WhACEgcKA1FVWBACEgcKA3F1eBACEgcKA2JBehACGgIQAUINCgtvbmVvZl9m", + "WhACEgcKA01PTxACEgcKA21vbxACEgcKA2JBehACGgIQAUINCgtvbmVvZl9m", "aWVsZEoGCPUDEP8DIhsKDkZvcmVpZ25NZXNzYWdlEgkKAWMYASABKAUiFgoU", "TnVsbEh5cG90aGVzaXNQcm90bzMiLwoORW51bU9ubHlQcm90bzMiHQoEQm9v", "bBIKCgZrRmFsc2UQABIJCgVrVHJ1ZRABKkAKC0ZvcmVpZ25FbnVtEg8KC0ZP", @@ -5432,8 +5432,8 @@ [pbr::OriginalName("ALIAS_FOO")] AliasFoo = 0, [pbr::OriginalName("ALIAS_BAR")] AliasBar = 1, [pbr::OriginalName("ALIAS_BAZ")] AliasBaz = 2, - [pbr::OriginalName("QUX", PreferredAlias = false)] Qux = 2, - [pbr::OriginalName("qux", PreferredAlias = false)] Qux_ = 2, + [pbr::OriginalName("MOO", PreferredAlias = false)] Moo = 2, + [pbr::OriginalName("moo", PreferredAlias = false)] Moo_ = 2, [pbr::OriginalName("bAz", PreferredAlias = false)] BAz = 2, }
diff --git a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs index ec4c07b..3440105 100644 --- a/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs +++ b/csharp/src/Google.Protobuf.Test.TestProtos/UnittestIssues.cs
@@ -54,11 +54,13 @@ "dEluT25lb2YSLgoKbnVsbF92YWx1ZRgCIAEoDjIaLmdvb2dsZS5wcm90b2J1", "Zi5OdWxsVmFsdWUiYAoXTWl4ZWRSZWd1bGFyQW5kT3B0aW9uYWwSFQoNcmVn", "dWxhcl9maWVsZBgBIAEoCRIbCg5vcHRpb25hbF9maWVsZBgCIAEoCUgAiAEB", - "QhEKD19vcHRpb25hbF9maWVsZCpVCgxOZWdhdGl2ZUVudW0SFgoSTkVHQVRJ", - "VkVfRU5VTV9aRVJPEAASFgoJRml2ZUJlbG93EPv//////////wESFQoITWlu", - "dXNPbmUQ////////////ASouCg5EZXByZWNhdGVkRW51bRITCg9ERVBSRUNB", - "VEVEX1pFUk8QABIHCgNvbmUQAUIdqgIaVW5pdFRlc3QuSXNzdWVzLlRlc3RQ", - "cm90b3NiBnByb3RvMw==")); + "QhEKD19vcHRpb25hbF9maWVsZCI5ChJPbmVvZldpdGhOb25lRmllbGQSCwoB", + "eBgBIAEoCUgAEg4KBG5vbmUYAiABKAlIAEIGCgR0ZXN0IjUKEU9uZW9mV2l0", + "aE5vbmVOYW1lEgsKAXgYASABKAlIABILCgF5GAIgASgJSABCBgoEbm9uZSpV", + "CgxOZWdhdGl2ZUVudW0SFgoSTkVHQVRJVkVfRU5VTV9aRVJPEAASFgoJRml2", + "ZUJlbG93EPv//////////wESFQoITWludXNPbmUQ////////////ASouCg5E", + "ZXByZWNhdGVkRW51bRITCg9ERVBSRUNBVEVEX1pFUk8QABIHCgNvbmUQAUId", + "qgIaVW5pdFRlc3QuSXNzdWVzLlRlc3RQcm90b3NiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::UnitTest.Issues.TestProtos.NegativeEnum), typeof(global::UnitTest.Issues.TestProtos.DeprecatedEnum), }, null, new pbr::GeneratedClrTypeInfo[] { @@ -73,7 +75,9 @@ new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.OneofMerging), global::UnitTest.Issues.TestProtos.OneofMerging.Parser, new[]{ "Text", "Nested" }, new[]{ "Value" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested), global::UnitTest.Issues.TestProtos.OneofMerging.Types.Nested.Parser, new[]{ "X", "Y" }, null, null, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NullValueOutsideStruct), global::UnitTest.Issues.TestProtos.NullValueOutsideStruct.Parser, new[]{ "StringValue", "NullValue" }, new[]{ "Value" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.NullValueNotInOneof), global::UnitTest.Issues.TestProtos.NullValueNotInOneof.Parser, new[]{ "NullValue" }, null, null, null, null), - new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.MixedRegularAndOptional), global::UnitTest.Issues.TestProtos.MixedRegularAndOptional.Parser, new[]{ "RegularField", "OptionalField" }, new[]{ "OptionalField" }, null, null, null) + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.MixedRegularAndOptional), global::UnitTest.Issues.TestProtos.MixedRegularAndOptional.Parser, new[]{ "RegularField", "OptionalField" }, new[]{ "OptionalField" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.OneofWithNoneField), global::UnitTest.Issues.TestProtos.OneofWithNoneField.Parser, new[]{ "X", "None" }, new[]{ "Test" }, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::UnitTest.Issues.TestProtos.OneofWithNoneName), global::UnitTest.Issues.TestProtos.OneofWithNoneName.Parser, new[]{ "X", "Y" }, new[]{ "None" }, null, null, null) })); } #endregion @@ -3825,6 +3829,524 @@ } + public sealed partial class OneofWithNoneField : pb::IMessage<OneofWithNoneField> + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser<OneofWithNoneField> _parser = new pb::MessageParser<OneofWithNoneField>(() => new OneofWithNoneField()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser<OneofWithNoneField> Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[12]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofWithNoneField() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofWithNoneField(OneofWithNoneField other) : this() { + switch (other.TestCase) { + case TestOneofCase.X: + X = other.X; + break; + case TestOneofCase.None_: + None = other.None; + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofWithNoneField Clone() { + return new OneofWithNoneField(this); + } + + /// <summary>Field number for the "x" field.</summary> + public const int XFieldNumber = 1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string X { + get { return testCase_ == TestOneofCase.X ? (string) test_ : ""; } + set { + test_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + testCase_ = TestOneofCase.X; + } + } + + /// <summary>Field number for the "none" field.</summary> + public const int NoneFieldNumber = 2; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string None { + get { return testCase_ == TestOneofCase.None_ ? (string) test_ : ""; } + set { + test_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + testCase_ = TestOneofCase.None_; + } + } + + private object test_; + /// <summary>Enum of possible cases for the "test" oneof.</summary> + public enum TestOneofCase { + None = 0, + X = 1, + None_ = 2, + } + private TestOneofCase testCase_ = TestOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public TestOneofCase TestCase { + get { return testCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearTest() { + testCase_ = TestOneofCase.None; + test_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OneofWithNoneField); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OneofWithNoneField other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (X != other.X) return false; + if (None != other.None) return false; + if (TestCase != other.TestCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (testCase_ == TestOneofCase.X) hash ^= X.GetHashCode(); + if (testCase_ == TestOneofCase.None_) hash ^= None.GetHashCode(); + hash ^= (int) testCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (testCase_ == TestOneofCase.X) { + output.WriteRawTag(10); + output.WriteString(X); + } + if (testCase_ == TestOneofCase.None_) { + output.WriteRawTag(18); + output.WriteString(None); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (testCase_ == TestOneofCase.X) { + output.WriteRawTag(10); + output.WriteString(X); + } + if (testCase_ == TestOneofCase.None_) { + output.WriteRawTag(18); + output.WriteString(None); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (testCase_ == TestOneofCase.X) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(X); + } + if (testCase_ == TestOneofCase.None_) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(None); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OneofWithNoneField other) { + if (other == null) { + return; + } + switch (other.TestCase) { + case TestOneofCase.X: + X = other.X; + break; + case TestOneofCase.None_: + None = other.None; + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + X = input.ReadString(); + break; + } + case 18: { + None = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + 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: { + X = input.ReadString(); + break; + } + case 18: { + None = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class OneofWithNoneName : pb::IMessage<OneofWithNoneName> + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser<OneofWithNoneName> _parser = new pb::MessageParser<OneofWithNoneName>(() => new OneofWithNoneName()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pb::MessageParser<OneofWithNoneName> Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public static pbr::MessageDescriptor Descriptor { + get { return global::UnitTest.Issues.TestProtos.UnittestIssuesReflection.Descriptor.MessageTypes[13]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofWithNoneName() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofWithNoneName(OneofWithNoneName other) : this() { + switch (other.NoneCase) { + case NoneOneofCase.X: + X = other.X; + break; + case NoneOneofCase.Y: + Y = other.Y; + break; + } + + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public OneofWithNoneName Clone() { + return new OneofWithNoneName(this); + } + + /// <summary>Field number for the "x" field.</summary> + public const int XFieldNumber = 1; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string X { + get { return noneCase_ == NoneOneofCase.X ? (string) none_ : ""; } + set { + none_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + noneCase_ = NoneOneofCase.X; + } + } + + /// <summary>Field number for the "y" field.</summary> + public const int YFieldNumber = 2; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public string Y { + get { return noneCase_ == NoneOneofCase.Y ? (string) none_ : ""; } + set { + none_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + noneCase_ = NoneOneofCase.Y; + } + } + + private object none_; + /// <summary>Enum of possible cases for the "none" oneof.</summary> + public enum NoneOneofCase { + None = 0, + X = 1, + Y = 2, + } + private NoneOneofCase noneCase_ = NoneOneofCase.None; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public NoneOneofCase NoneCase { + get { return noneCase_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void ClearNone() { + noneCase_ = NoneOneofCase.None; + none_ = null; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override bool Equals(object other) { + return Equals(other as OneofWithNoneName); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public bool Equals(OneofWithNoneName other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (X != other.X) return false; + if (Y != other.Y) return false; + if (NoneCase != other.NoneCase) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override int GetHashCode() { + int hash = 1; + if (noneCase_ == NoneOneofCase.X) hash ^= X.GetHashCode(); + if (noneCase_ == NoneOneofCase.Y) hash ^= Y.GetHashCode(); + hash ^= (int) noneCase_; + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (noneCase_ == NoneOneofCase.X) { + output.WriteRawTag(10); + output.WriteString(X); + } + if (noneCase_ == NoneOneofCase.Y) { + output.WriteRawTag(18); + output.WriteString(Y); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (noneCase_ == NoneOneofCase.X) { + output.WriteRawTag(10); + output.WriteString(X); + } + if (noneCase_ == NoneOneofCase.Y) { + output.WriteRawTag(18); + output.WriteString(Y); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public int CalculateSize() { + int size = 0; + if (noneCase_ == NoneOneofCase.X) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(X); + } + if (noneCase_ == NoneOneofCase.Y) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Y); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(OneofWithNoneName other) { + if (other == null) { + return; + } + switch (other.NoneCase) { + case NoneOneofCase.X: + X = other.X; + break; + case NoneOneofCase.Y: + Y = other.Y; + break; + } + + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + X = input.ReadString(); + break; + } + case 18: { + Y = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] + 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: { + X = input.ReadString(); + break; + } + case 18: { + Y = input.ReadString(); + break; + } + } + } + } + #endif + + } + #endregion }
diff --git a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs index 04d68b5..4876e09 100644 --- a/csharp/src/Google.Protobuf.Test/ByteStringTest.cs +++ b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs
@@ -1,439 +1,439 @@ -#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.Text; -using NUnit.Framework; -using System.IO; -using System.Collections.Generic; -using System.Collections; -using System.Linq; -using System.Buffers; -using System.Runtime.InteropServices; -using System.Threading; -using System.Runtime.CompilerServices; -#if !NET35 -using System.Threading.Tasks; -#endif - -namespace Google.Protobuf -{ - public class ByteStringTest - { - [Test] - public void Equality() - { - ByteString b1 = ByteString.CopyFrom(1, 2, 3); - ByteString b2 = ByteString.CopyFrom(1, 2, 3); - ByteString b3 = ByteString.CopyFrom(1, 2, 4); - ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); - EqualityTester.AssertEquality(b1, b1); - EqualityTester.AssertEquality(b1, b2); - EqualityTester.AssertInequality(b1, b3); - EqualityTester.AssertInequality(b1, b4); - EqualityTester.AssertInequality(b1, null); - EqualityTester.AssertEquality(ByteString.Empty, ByteString.Empty); -#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) - Assert.IsTrue(b1 == b1); - Assert.IsTrue(b1 == b2); - Assert.IsFalse(b1 == b3); - Assert.IsFalse(b1 == b4); - Assert.IsFalse(b1 == null); - Assert.IsTrue((ByteString) null == null); - Assert.IsFalse(b1 != b1); - Assert.IsFalse(b1 != b2); - Assert.IsTrue(ByteString.Empty == ByteString.Empty); -#pragma warning disable 1718 - Assert.IsTrue(b1 != b3); - Assert.IsTrue(b1 != b4); - Assert.IsTrue(b1 != null); - Assert.IsFalse((ByteString) null != null); - } - - [Test] - public void EmptyByteStringHasZeroSize() - { - Assert.AreEqual(0, ByteString.Empty.Length); - } - - [Test] - public void CopyFromStringWithExplicitEncoding() - { - ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); - Assert.AreEqual(4, bs.Length); - Assert.AreEqual(65, bs[0]); - Assert.AreEqual(0, bs[1]); - Assert.AreEqual(66, bs[2]); - Assert.AreEqual(0, bs[3]); - } - - [Test] - public void IsEmptyWhenEmpty() - { - Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); - } - - [Test] - public void IsEmptyWhenNotEmpty() - { - Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); - } - - [Test] - public void CopyFromByteArrayCopiesContents() - { - byte[] data = new byte[1]; - data[0] = 10; - ByteString bs = ByteString.CopyFrom(data); - Assert.AreEqual(10, bs[0]); - data[0] = 5; - Assert.AreEqual(10, bs[0]); - } - - [Test] - public void CopyFromReadOnlySpanCopiesContents() - { - byte[] data = new byte[1]; - data[0] = 10; - ReadOnlySpan<byte> byteSpan = data; - var bs = ByteString.CopyFrom(byteSpan); - Assert.AreEqual(10, bs[0]); - data[0] = 5; - Assert.AreEqual(10, bs[0]); - } - - [Test] - public void ToByteArrayCopiesContents() - { - ByteString bs = ByteString.CopyFromUtf8("Hello"); - byte[] data = bs.ToByteArray(); - Assert.AreEqual((byte)'H', data[0]); - Assert.AreEqual((byte)'H', bs[0]); - data[0] = 0; - Assert.AreEqual(0, data[0]); - Assert.AreEqual((byte)'H', bs[0]); - } - - [Test] - public void CopyFromUtf8UsesUtf8() - { - ByteString bs = ByteString.CopyFromUtf8("\u20ac"); - Assert.AreEqual(3, bs.Length); - Assert.AreEqual(0xe2, bs[0]); - Assert.AreEqual(0x82, bs[1]); - Assert.AreEqual(0xac, bs[2]); - } - - [Test] - public void CopyFromPortion() - { - byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; - ByteString bs = ByteString.CopyFrom(data, 2, 3); - Assert.AreEqual(3, bs.Length); - Assert.AreEqual(2, bs[0]); - Assert.AreEqual(3, bs[1]); - } - - [Test] - public void CopyTo() - { - byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - ByteString bs = ByteString.CopyFrom(data); - - byte[] dest = new byte[data.Length]; - bs.CopyTo(dest, 0); - - CollectionAssert.AreEqual(data, dest); - } - - [Test] - public void GetEnumerator() - { - byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - ByteString bs = ByteString.CopyFrom(data); - - IEnumerator<byte> genericEnumerator = bs.GetEnumerator(); - Assert.IsTrue(genericEnumerator.MoveNext()); - Assert.AreEqual(0, genericEnumerator.Current); - - IEnumerator enumerator = ((IEnumerable)bs).GetEnumerator(); - Assert.IsTrue(enumerator.MoveNext()); - Assert.AreEqual(0, enumerator.Current); - - // Call via LINQ - CollectionAssert.AreEqual(bs.Span.ToArray(), bs.ToArray()); - } - - [Test] - public void UnsafeWrap() - { - byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - ByteString bs = UnsafeByteOperations.UnsafeWrap(data.AsMemory(2, 3)); - ReadOnlySpan<byte> s = bs.Span; - - Assert.AreEqual(3, s.Length); - Assert.AreEqual(2, s[0]); - Assert.AreEqual(3, s[1]); - Assert.AreEqual(4, s[2]); - - // Check that the value is not a copy - data[2] = byte.MaxValue; - Assert.AreEqual(byte.MaxValue, s[0]); - } - - [Test] - public void CreateCodedInput_FromArraySegment() - { - byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - ByteString bs = UnsafeByteOperations.UnsafeWrap(data.AsMemory(2, 3)); - CodedInputStream codedInputStream = bs.CreateCodedInput(); - - byte[] bytes = codedInputStream.ReadRawBytes(3); - - Assert.AreEqual(3, bytes.Length); - Assert.AreEqual(2, bytes[0]); - Assert.AreEqual(3, bytes[1]); - Assert.AreEqual(4, bytes[2]); - Assert.IsTrue(codedInputStream.IsAtEnd); - } - - [Test] - public void WriteToStream() - { - byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; - ByteString bs = ByteString.CopyFrom(data); - - MemoryStream ms = new MemoryStream(); - bs.WriteTo(ms); - - CollectionAssert.AreEqual(data, ms.ToArray()); - } - - [Test] - public void WriteToStream_Stackalloc() - { - byte[] data = Encoding.UTF8.GetBytes("Hello world"); - Span<byte> s = stackalloc byte[data.Length]; - data.CopyTo(s); - - MemoryStream ms = new MemoryStream(); - - using (UnmanagedMemoryManager<byte> manager = new UnmanagedMemoryManager<byte>(s)) - { - ByteString bs = ByteString.AttachBytes(manager.Memory); - - bs.WriteTo(ms); - } - - CollectionAssert.AreEqual(data, ms.ToArray()); - } - - [Test] - public void ToStringUtf8() - { - ByteString bs = ByteString.CopyFromUtf8("\u20ac"); - Assert.AreEqual("\u20ac", bs.ToStringUtf8()); - } - - [Test] - public void ToStringWithExplicitEncoding() - { - ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); - Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); - } - - [Test] - public void ToString_Stackalloc() - { - byte[] data = Encoding.UTF8.GetBytes("Hello world"); - Span<byte> s = stackalloc byte[data.Length]; - data.CopyTo(s); - - using (UnmanagedMemoryManager<byte> manager = new UnmanagedMemoryManager<byte>(s)) - { - ByteString bs = ByteString.AttachBytes(manager.Memory); - - Assert.AreEqual("Hello world", bs.ToString(Encoding.UTF8)); - } - } - - [Test] - public void FromBase64_WithText() - { - byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; - string base64 = Convert.ToBase64String(data); - ByteString bs = ByteString.FromBase64(base64); - Assert.AreEqual(data, bs.ToByteArray()); - } - - [Test] - public void FromBase64_Empty() - { - // Optimization which also fixes issue 61. - Assert.AreSame(ByteString.Empty, ByteString.FromBase64("")); - } - - [Test] - public void ToBase64_Array() - { - ByteString bs = ByteString.CopyFrom(Encoding.UTF8.GetBytes("Hello world")); - - Assert.AreEqual("SGVsbG8gd29ybGQ=", bs.ToBase64()); - } - - [Test] - public void ToBase64_Stackalloc() - { - byte[] data = Encoding.UTF8.GetBytes("Hello world"); - Span<byte> s = stackalloc byte[data.Length]; - data.CopyTo(s); - - using (UnmanagedMemoryManager<byte> manager = new UnmanagedMemoryManager<byte>(s)) - { - ByteString bs = ByteString.AttachBytes(manager.Memory); - - Assert.AreEqual("SGVsbG8gd29ybGQ=", bs.ToBase64()); - } - } - - [Test] - public void FromStream_Seekable() - { - var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); - // Consume the first byte, just to test that it's "from current position" - stream.ReadByte(); - var actual = ByteString.FromStream(stream); - ByteString expected = ByteString.CopyFrom(2, 3, 4, 5); - Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); - } - - [Test] - public void FromStream_NotSeekable() - { - var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); - // Consume the first byte, just to test that it's "from current position" - stream.ReadByte(); - // Wrap the original stream in LimitedInputStream, which has CanSeek=false - var limitedStream = new LimitedInputStream(stream, 3); - var actual = ByteString.FromStream(limitedStream); - ByteString expected = ByteString.CopyFrom(2, 3, 4); - Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); - } - -#if !NET35 - [Test] - public async Task FromStreamAsync_Seekable() - { - var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); - // Consume the first byte, just to test that it's "from current position" - stream.ReadByte(); - var actual = await ByteString.FromStreamAsync(stream); - ByteString expected = ByteString.CopyFrom(2, 3, 4, 5); - Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); - } - - [Test] - public async Task FromStreamAsync_NotSeekable() - { - var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); - // Consume the first byte, just to test that it's "from current position" - stream.ReadByte(); - // Wrap the original stream in LimitedInputStream, which has CanSeek=false - var limitedStream = new LimitedInputStream(stream, 3); - var actual = await ByteString.FromStreamAsync(limitedStream); - ByteString expected = ByteString.CopyFrom(2, 3, 4); - Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); - } -#endif - - [Test] - public void GetHashCode_Regression() - { - // We used to have an awful hash algorithm where only the last four - // bytes were relevant. This is a regression test for - // https://github.com/protocolbuffers/protobuf/issues/2511 - - ByteString b1 = ByteString.CopyFrom(100, 1, 2, 3, 4); - ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4); - Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode()); - } - - [Test] - public void GetContentsAsReadOnlySpan() - { - var byteString = ByteString.CopyFrom(1, 2, 3, 4, 5); - var copied = byteString.Span.ToArray(); - CollectionAssert.AreEqual(byteString, copied); - } - - [Test] - public void GetContentsAsReadOnlyMemory() - { - var byteString = ByteString.CopyFrom(1, 2, 3, 4, 5); - var copied = byteString.Memory.ToArray(); - CollectionAssert.AreEqual(byteString, copied); - } - - // Create Memory<byte> from non-array source. - // Use by ByteString tests that have optimized path for array backed Memory<byte>. - private sealed unsafe class UnmanagedMemoryManager<T> : MemoryManager<T> where T : unmanaged - { - private readonly T* _pointer; - private readonly int _length; - - public UnmanagedMemoryManager(Span<T> span) - { - fixed (T* ptr = &MemoryMarshal.GetReference(span)) - { - _pointer = ptr; - _length = span.Length; - } - } - - public override Span<T> GetSpan() => new Span<T>(_pointer, _length); - - public override MemoryHandle Pin(int elementIndex = 0) - { - if (elementIndex < 0 || elementIndex >= _length) - { - throw new ArgumentOutOfRangeException(nameof(elementIndex)); - } - - return new MemoryHandle(_pointer + elementIndex); - } - - public override void Unpin() { } - - protected override void Dispose(bool disposing) { } - } - } +#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.Text; +using NUnit.Framework; +using System.IO; +using System.Collections.Generic; +using System.Collections; +using System.Linq; +using System.Buffers; +using System.Runtime.InteropServices; +using System.Threading; +using System.Runtime.CompilerServices; +#if !NET35 +using System.Threading.Tasks; +#endif + +namespace Google.Protobuf +{ + public class ByteStringTest + { + [Test] + public void Equality() + { + ByteString b1 = ByteString.CopyFrom(1, 2, 3); + ByteString b2 = ByteString.CopyFrom(1, 2, 3); + ByteString b3 = ByteString.CopyFrom(1, 2, 4); + ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); + EqualityTester.AssertEquality(b1, b1); + EqualityTester.AssertEquality(b1, b2); + EqualityTester.AssertInequality(b1, b3); + EqualityTester.AssertInequality(b1, b4); + EqualityTester.AssertInequality(b1, null); + EqualityTester.AssertEquality(ByteString.Empty, ByteString.Empty); +#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) + Assert.IsTrue(b1 == b1); + Assert.IsTrue(b1 == b2); + Assert.IsFalse(b1 == b3); + Assert.IsFalse(b1 == b4); + Assert.IsFalse(b1 == null); + Assert.IsTrue((ByteString) null == null); + Assert.IsFalse(b1 != b1); + Assert.IsFalse(b1 != b2); + Assert.IsTrue(ByteString.Empty == ByteString.Empty); +#pragma warning disable 1718 + Assert.IsTrue(b1 != b3); + Assert.IsTrue(b1 != b4); + Assert.IsTrue(b1 != null); + Assert.IsFalse((ByteString) null != null); + } + + [Test] + public void EmptyByteStringHasZeroSize() + { + Assert.AreEqual(0, ByteString.Empty.Length); + } + + [Test] + public void CopyFromStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("AB", Encoding.Unicode); + Assert.AreEqual(4, bs.Length); + Assert.AreEqual(65, bs[0]); + Assert.AreEqual(0, bs[1]); + Assert.AreEqual(66, bs[2]); + Assert.AreEqual(0, bs[3]); + } + + [Test] + public void IsEmptyWhenEmpty() + { + Assert.IsTrue(ByteString.CopyFromUtf8("").IsEmpty); + } + + [Test] + public void IsEmptyWhenNotEmpty() + { + Assert.IsFalse(ByteString.CopyFromUtf8("X").IsEmpty); + } + + [Test] + public void CopyFromByteArrayCopiesContents() + { + byte[] data = new byte[1]; + data[0] = 10; + ByteString bs = ByteString.CopyFrom(data); + Assert.AreEqual(10, bs[0]); + data[0] = 5; + Assert.AreEqual(10, bs[0]); + } + + [Test] + public void CopyFromReadOnlySpanCopiesContents() + { + byte[] data = new byte[1]; + data[0] = 10; + ReadOnlySpan<byte> byteSpan = data; + var bs = ByteString.CopyFrom(byteSpan); + Assert.AreEqual(10, bs[0]); + data[0] = 5; + Assert.AreEqual(10, bs[0]); + } + + [Test] + public void ToByteArrayCopiesContents() + { + ByteString bs = ByteString.CopyFromUtf8("Hello"); + byte[] data = bs.ToByteArray(); + Assert.AreEqual((byte)'H', data[0]); + Assert.AreEqual((byte)'H', bs[0]); + data[0] = 0; + Assert.AreEqual(0, data[0]); + Assert.AreEqual((byte)'H', bs[0]); + } + + [Test] + public void CopyFromUtf8UsesUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(0xe2, bs[0]); + Assert.AreEqual(0x82, bs[1]); + Assert.AreEqual(0xac, bs[2]); + } + + [Test] + public void CopyFromPortion() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + ByteString bs = ByteString.CopyFrom(data, 2, 3); + Assert.AreEqual(3, bs.Length); + Assert.AreEqual(2, bs[0]); + Assert.AreEqual(3, bs[1]); + } + + [Test] + public void CopyTo() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = ByteString.CopyFrom(data); + + byte[] dest = new byte[data.Length]; + bs.CopyTo(dest, 0); + + CollectionAssert.AreEqual(data, dest); + } + + [Test] + public void GetEnumerator() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = ByteString.CopyFrom(data); + + IEnumerator<byte> genericEnumerator = bs.GetEnumerator(); + Assert.IsTrue(genericEnumerator.MoveNext()); + Assert.AreEqual(0, genericEnumerator.Current); + + IEnumerator enumerator = ((IEnumerable)bs).GetEnumerator(); + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual(0, enumerator.Current); + + // Call via LINQ + CollectionAssert.AreEqual(bs.Span.ToArray(), bs.ToArray()); + } + + [Test] + public void UnsafeWrap() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = UnsafeByteOperations.UnsafeWrap(data.AsMemory(2, 3)); + ReadOnlySpan<byte> s = bs.Span; + + Assert.AreEqual(3, s.Length); + Assert.AreEqual(2, s[0]); + Assert.AreEqual(3, s[1]); + Assert.AreEqual(4, s[2]); + + // Check that the value is not a copy + data[2] = byte.MaxValue; + Assert.AreEqual(byte.MaxValue, s[0]); + } + + [Test] + public void CreateCodedInput_FromArraySegment() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = UnsafeByteOperations.UnsafeWrap(data.AsMemory(2, 3)); + CodedInputStream codedInputStream = bs.CreateCodedInput(); + + byte[] bytes = codedInputStream.ReadRawBytes(3); + + Assert.AreEqual(3, bytes.Length); + Assert.AreEqual(2, bytes[0]); + Assert.AreEqual(3, bytes[1]); + Assert.AreEqual(4, bytes[2]); + Assert.IsTrue(codedInputStream.IsAtEnd); + } + + [Test] + public void WriteToStream() + { + byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6 }; + ByteString bs = ByteString.CopyFrom(data); + + MemoryStream ms = new MemoryStream(); + bs.WriteTo(ms); + + CollectionAssert.AreEqual(data, ms.ToArray()); + } + + [Test] + public void WriteToStream_Stackalloc() + { + byte[] data = Encoding.UTF8.GetBytes("Hello world"); + Span<byte> s = stackalloc byte[data.Length]; + data.CopyTo(s); + + MemoryStream ms = new MemoryStream(); + + using (UnmanagedMemoryManager<byte> manager = new UnmanagedMemoryManager<byte>(s)) + { + ByteString bs = ByteString.AttachBytes(manager.Memory); + + bs.WriteTo(ms); + } + + CollectionAssert.AreEqual(data, ms.ToArray()); + } + + [Test] + public void ToStringUtf8() + { + ByteString bs = ByteString.CopyFromUtf8("\u20ac"); + Assert.AreEqual("\u20ac", bs.ToStringUtf8()); + } + + [Test] + public void ToStringWithExplicitEncoding() + { + ByteString bs = ByteString.CopyFrom("\u20ac", Encoding.Unicode); + Assert.AreEqual("\u20ac", bs.ToString(Encoding.Unicode)); + } + + [Test] + public void ToString_Stackalloc() + { + byte[] data = Encoding.UTF8.GetBytes("Hello world"); + Span<byte> s = stackalloc byte[data.Length]; + data.CopyTo(s); + + using (UnmanagedMemoryManager<byte> manager = new UnmanagedMemoryManager<byte>(s)) + { + ByteString bs = ByteString.AttachBytes(manager.Memory); + + Assert.AreEqual("Hello world", bs.ToString(Encoding.UTF8)); + } + } + + [Test] + public void FromBase64_WithText() + { + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6}; + string base64 = Convert.ToBase64String(data); + ByteString bs = ByteString.FromBase64(base64); + Assert.AreEqual(data, bs.ToByteArray()); + } + + [Test] + public void FromBase64_Empty() + { + // Optimization which also fixes issue 61. + Assert.AreSame(ByteString.Empty, ByteString.FromBase64("")); + } + + [Test] + public void ToBase64_Array() + { + ByteString bs = ByteString.CopyFrom(Encoding.UTF8.GetBytes("Hello world")); + + Assert.AreEqual("SGVsbG8gd29ybGQ=", bs.ToBase64()); + } + + [Test] + public void ToBase64_Stackalloc() + { + byte[] data = Encoding.UTF8.GetBytes("Hello world"); + Span<byte> s = stackalloc byte[data.Length]; + data.CopyTo(s); + + using (UnmanagedMemoryManager<byte> manager = new UnmanagedMemoryManager<byte>(s)) + { + ByteString bs = ByteString.AttachBytes(manager.Memory); + + Assert.AreEqual("SGVsbG8gd29ybGQ=", bs.ToBase64()); + } + } + + [Test] + public void FromStream_Seekable() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); + // Consume the first byte, just to test that it's "from current position" + stream.ReadByte(); + var actual = ByteString.FromStream(stream); + ByteString expected = ByteString.CopyFrom(2, 3, 4, 5); + Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); + } + + [Test] + public void FromStream_NotSeekable() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); + // Consume the first byte, just to test that it's "from current position" + stream.ReadByte(); + // Wrap the original stream in LimitedInputStream, which has CanSeek=false + var limitedStream = new LimitedInputStream(stream, 3); + var actual = ByteString.FromStream(limitedStream); + ByteString expected = ByteString.CopyFrom(2, 3, 4); + Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); + } + +#if !NET35 + [Test] + public async Task FromStreamAsync_Seekable() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); + // Consume the first byte, just to test that it's "from current position" + stream.ReadByte(); + var actual = await ByteString.FromStreamAsync(stream); + ByteString expected = ByteString.CopyFrom(2, 3, 4, 5); + Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); + } + + [Test] + public async Task FromStreamAsync_NotSeekable() + { + var stream = new MemoryStream(new byte[] { 1, 2, 3, 4, 5 }); + // Consume the first byte, just to test that it's "from current position" + stream.ReadByte(); + // Wrap the original stream in LimitedInputStream, which has CanSeek=false + var limitedStream = new LimitedInputStream(stream, 3); + var actual = await ByteString.FromStreamAsync(limitedStream); + ByteString expected = ByteString.CopyFrom(2, 3, 4); + Assert.AreEqual(expected, actual, $"{expected.ToBase64()} != {actual.ToBase64()}"); + } +#endif + + [Test] + public void GetHashCode_Regression() + { + // We used to have an awful hash algorithm where only the last four + // bytes were relevant. This is a regression test for + // https://github.com/protocolbuffers/protobuf/issues/2511 + + ByteString b1 = ByteString.CopyFrom(100, 1, 2, 3, 4); + ByteString b2 = ByteString.CopyFrom(200, 1, 2, 3, 4); + Assert.AreNotEqual(b1.GetHashCode(), b2.GetHashCode()); + } + + [Test] + public void GetContentsAsReadOnlySpan() + { + var byteString = ByteString.CopyFrom(1, 2, 3, 4, 5); + var copied = byteString.Span.ToArray(); + CollectionAssert.AreEqual(byteString, copied); + } + + [Test] + public void GetContentsAsReadOnlyMemory() + { + var byteString = ByteString.CopyFrom(1, 2, 3, 4, 5); + var copied = byteString.Memory.ToArray(); + CollectionAssert.AreEqual(byteString, copied); + } + + // Create Memory<byte> from non-array source. + // Use by ByteString tests that have optimized path for array backed Memory<byte>. + private sealed unsafe class UnmanagedMemoryManager<T> : MemoryManager<T> where T : unmanaged + { + private readonly T* _pointer; + private readonly int _length; + + public UnmanagedMemoryManager(Span<T> span) + { + fixed (T* ptr = &MemoryMarshal.GetReference(span)) + { + _pointer = ptr; + _length = span.Length; + } + } + + public override Span<T> GetSpan() => new Span<T>(_pointer, _length); + + public override MemoryHandle Pin(int elementIndex = 0) + { + if (elementIndex < 0 || elementIndex >= _length) + { + throw new ArgumentOutOfRangeException(nameof(elementIndex)); + } + + return new MemoryHandle(_pointer + elementIndex); + } + + public override void Unpin() { } + + protected override void Dispose(bool disposing) { } + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs index 2341559..b84a1b7 100644 --- a/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs +++ b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs
@@ -1,1008 +1,1008 @@ -#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 Google.Protobuf.TestProtos; -using Proto2 = Google.Protobuf.TestProtos.Proto2; -using NUnit.Framework; - -namespace Google.Protobuf -{ - public class CodedInputStreamTest - { - /// <summary> - /// Helper to construct a byte array from a bunch of bytes. The inputs are - /// actually ints so that I can use hex notation and not get stupid errors - /// about precision. - /// </summary> - private static byte[] Bytes(params int[] bytesAsInts) - { - byte[] bytes = new byte[bytesAsInts.Length]; - for (int i = 0; i < bytesAsInts.Length; i++) - { - bytes[i] = (byte) bytesAsInts[i]; - } - return bytes; - } - - /// <summary> - /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() - /// </summary> - private static void AssertReadVarint(byte[] data, ulong value) - { - 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) - { - input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); - Assert.AreEqual((uint) value, input.ReadRawVarint32()); - - 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 - // doesn't read past the end of the input, so write an extra byte - this - // lets us test the position at the end. - MemoryStream memoryStream = new MemoryStream(); - memoryStream.Write(data, 0, data.Length); - memoryStream.WriteByte(0); - memoryStream.Position = 0; - Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream)); - Assert.AreEqual(data.Length, memoryStream.Position); - } - - /// <summary> - /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and - /// expects them to fail with an InvalidProtocolBufferException whose - /// description matches the given one. - /// </summary> - private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) - { - CodedInputStream input = new CodedInputStream(data); - var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32()); - Assert.AreEqual(expected.Message, exception.Message); - - input = new CodedInputStream(data); - 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) - { - // Check as ReadOnlySequence<byte> - ParseContext.Initialize(input, out ParseContext parseCtx); - assertAction(ref parseCtx); - if (assertIsAtEnd) - { - Assert.IsTrue(SegmentedBufferHelper.IsAtEnd(ref parseCtx.buffer, ref parseCtx.state)); - } - - // Check as ReadOnlySpan<byte> - ParseContext.Initialize(input.ToArray().AsSpan(), out ParseContext spanParseContext); - assertAction(ref spanParseContext); - if (assertIsAtEnd) - { - Assert.IsTrue(SegmentedBufferHelper.IsAtEnd(ref spanParseContext.buffer, ref spanParseContext.state)); - } - } - - [Test] - public void ReadVarint() - { - AssertReadVarint(Bytes(0x00), 0); - AssertReadVarint(Bytes(0x01), 1); - AssertReadVarint(Bytes(0x7f), 127); - // 14882 - AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7)); - // 2961488830 - AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x0bL << 28)); - - // 64-bit - // 7256456126 - AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x1bL << 28)); - // 41256202580718336 - AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | - (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49)); - // 11964378330978735131 - AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), - (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) | - (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63)); - - // Failures - AssertReadVarintFailure( - InvalidProtocolBufferException.MalformedVarint(), - Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, - 0x00)); - AssertReadVarintFailure( - InvalidProtocolBufferException.TruncatedMessage(), - Bytes(0x80)); - } - - /// <summary> - /// Parses the given bytes using ReadRawLittleEndian32() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertReadLittleEndian32(byte[] data, uint value) - { - CodedInputStream input = new CodedInputStream(data); - 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) - { - input = new CodedInputStream( - 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); - } - } - - /// <summary> - /// Parses the given bytes using ReadRawLittleEndian64() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertReadLittleEndian64(byte[] data, ulong value) - { - CodedInputStream input = new CodedInputStream(data); - 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) - { - input = new CodedInputStream( - 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); - } - } - - [Test] - public void ReadLittleEndian() - { - AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678); - AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0); - - AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), - 0x123456789abcdef0L); - AssertReadLittleEndian64( - Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL); - } - - [Test] - public void DecodeZigZag32() - { - 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, 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] - public void ReadWholeMessage_VaryingBlockSizes() - { - TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); - - byte[] rawBytes = message.ToByteArray(); - Assert.AreEqual(rawBytes.Length, message.CalculateSize()); - TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); - Assert.AreEqual(message, message2); - - // Try different block sizes. - for (int blockSize = 1; blockSize < 256; blockSize *= 2) - { - message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); - Assert.AreEqual(message, message2); - } - } - - [Test] - public void ReadWholeMessage_VaryingBlockSizes_FromSequence() - { - TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); - - byte[] rawBytes = message.ToByteArray(); - Assert.AreEqual(rawBytes.Length, message.CalculateSize()); - TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); - Assert.AreEqual(message, message2); - - // Try different block sizes. - for (int blockSize = 1; blockSize < 256; blockSize *= 2) - { - message2 = TestAllTypes.Parser.ParseFrom(ReadOnlySequenceFactory.CreateWithContent(rawBytes, blockSize)); - Assert.AreEqual(message, message2); - } - } - - [Test] - public void ReadInt32Wrapper_VariableBlockSizes() - { - byte[] rawBytes = new byte[] { 202, 1, 11, 8, 254, 255, 255, 255, 255, 255, 255, 255, 255, 1 }; - - for (int blockSize = 1; blockSize <= rawBytes.Length; blockSize++) - { - ReadOnlySequence<byte> data = ReadOnlySequenceFactory.CreateWithContent(rawBytes, blockSize); - AssertReadFromParseContext(data, (ref ParseContext ctx) => - { - ctx.ReadTag(); - - var value = ParsingPrimitivesWrappers.ReadInt32Wrapper(ref ctx); - - Assert.AreEqual(-2, value); - }, true); - } - } - - [Test] - public void ReadHugeBlob() - { - // Allocate and initialize a 1MB blob. - byte[] blob = new byte[1 << 20]; - for (int i = 0; i < blob.Length; i++) - { - blob[i] = (byte) i; - } - - // Make a message containing it. - var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) }; - - // Serialize and parse it. Make sure to parse from an InputStream, not - // directly from a ByteString, so that CodedInputStream uses buffered - // reading. - TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString()); - - Assert.AreEqual(message, message2); - } - - [Test] - public void ReadMaliciouslyLargeBlob() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteRawVarint32(0x7FFFFFFF); - output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms); - Assert.AreEqual(tag, input.ReadTag()); - - Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); - } - - [Test] - public void ReadBlobGreaterThanCurrentLimit() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteRawVarint32(4); - output.WriteRawBytes(new byte[4]); // Pad with a few random bytes. - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms); - Assert.AreEqual(tag, input.ReadTag()); - - // Specify limit smaller than data length - input.PushLimit(3); - Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); - - AssertReadFromParseContext(new ReadOnlySequence<byte>(ms.ToArray()), (ref ParseContext ctx) => - { - Assert.AreEqual(tag, ctx.ReadTag()); - SegmentedBufferHelper.PushLimit(ref ctx.state, 3); - try - { - ctx.ReadBytes(); - Assert.Fail(); - } - catch (InvalidProtocolBufferException) {} - }, true); - } - - [Test] - public void ReadStringGreaterThanCurrentLimit() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteRawVarint32(4); - output.WriteRawBytes(new byte[4]); // Pad with a few random bytes. - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms.ToArray()); - Assert.AreEqual(tag, input.ReadTag()); - - // Specify limit smaller than data length - input.PushLimit(3); - Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString()); - - AssertReadFromParseContext(new ReadOnlySequence<byte>(ms.ToArray()), (ref ParseContext ctx) => - { - Assert.AreEqual(tag, ctx.ReadTag()); - SegmentedBufferHelper.PushLimit(ref ctx.state, 3); - try - { - ctx.ReadString(); - Assert.Fail(); - } - catch (InvalidProtocolBufferException) { } - }, true); - } - - // Representations of a tag for field 0 with various wire types - [Test] - [TestCase(0)] - [TestCase(1)] - [TestCase(2)] - [TestCase(3)] - [TestCase(4)] - [TestCase(5)] - public void ReadTag_ZeroFieldRejected(byte tag) - { - CodedInputStream cis = new CodedInputStream(new byte[] { tag }); - Assert.Throws<InvalidProtocolBufferException>(() => cis.ReadTag()); - } - - internal static TestRecursiveMessage MakeRecursiveMessage(int depth) - { - if (depth == 0) - { - return new TestRecursiveMessage { I = 5 }; - } - else - { - return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) }; - } - } - - internal static void AssertMessageDepth(TestRecursiveMessage message, int depth) - { - if (depth == 0) - { - Assert.IsNull(message.A); - Assert.AreEqual(5, message.I); - } - else - { - Assert.IsNotNull(message.A); - AssertMessageDepth(message.A, depth - 1); - } - } - - [Test] - public void MaliciousRecursion() - { - ByteString atRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit).ToByteString(); - ByteString beyondRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit + 1).ToByteString(); - - AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(atRecursiveLimit), CodedInputStream.DefaultRecursionLimit); - - Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(beyondRecursiveLimit)); - - 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() - { - // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't - // apply to the latter case. - MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray()); - CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100); - Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input)); - } - - /// <summary> - /// Tests that if we read an string that contains invalid UTF-8, no exception - /// is thrown. Instead, the invalid bytes are replaced with the Unicode - /// "replacement character" U+FFFD. - /// </summary> - [Test] - public void ReadInvalidUtf8() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteRawVarint32(1); - output.WriteRawBytes(new byte[] {0x80}); - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms); - - Assert.AreEqual(tag, input.ReadTag()); - string text = input.ReadString(); - Assert.AreEqual('\ufffd', text[0]); - } - - [Test] - public void ReadNegativeSizedStringThrowsInvalidProtocolBufferException() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteLength(-1); - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms); - - Assert.AreEqual(tag, input.ReadTag()); - Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString()); - } - - [Test] - public void ReadNegativeSizedBytesThrowsInvalidProtocolBufferException() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - - uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteLength(-1); - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms); - - Assert.AreEqual(tag, input.ReadTag()); - Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); - } - - /// <summary> - /// A stream which limits the number of bytes it reads at a time. - /// We use this to make sure that CodedInputStream doesn't screw up when - /// reading in small blocks. - /// </summary> - private sealed class SmallBlockInputStream : MemoryStream - { - private readonly int blockSize; - - public SmallBlockInputStream(byte[] data, int blockSize) - : base(data) - { - this.blockSize = blockSize; - } - - public override int Read(byte[] buffer, int offset, int count) - { - return base.Read(buffer, offset, Math.Min(count, blockSize)); - } - } - - [Test] - public void TestNegativeEnum() - { - byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; - CodedInputStream input = new CodedInputStream(bytes); - Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum()); - Assert.IsTrue(input.IsAtEnd); - } - - //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily - [Test] - public void TestSlowPathAvoidance() - { - using (var ms = new MemoryStream()) - { - CodedOutputStream output = new CodedOutputStream(ms); - output.WriteTag(1, WireFormat.WireType.LengthDelimited); - output.WriteBytes(ByteString.CopyFrom(new byte[100])); - output.WriteTag(2, WireFormat.WireType.LengthDelimited); - output.WriteBytes(ByteString.CopyFrom(new byte[100])); - output.Flush(); - - ms.Position = 0; - CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false); - - uint tag = input.ReadTag(); - Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); - Assert.AreEqual(100, input.ReadBytes().Length); - - tag = input.ReadTag(); - Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); - Assert.AreEqual(100, input.ReadBytes().Length); - } - } - - [Test] - public void MaximumFieldNumber() - { - MemoryStream ms = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(ms); - - int fieldNumber = 0x1FFFFFFF; - uint tag = WireFormat.MakeTag(fieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteRawVarint32(tag); - output.WriteString("field 1"); - output.Flush(); - ms.Position = 0; - - CodedInputStream input = new CodedInputStream(ms); - - Assert.AreEqual(tag, input.ReadTag()); - Assert.AreEqual(fieldNumber, WireFormat.GetTagFieldNumber(tag)); - } - - [Test] - public void Tag0Throws() - { - var input = new CodedInputStream(new byte[] { 0 }); - Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag()); - } - - [Test] - public void SkipGroup() - { - // Create an output stream with a group in: - // Field 1: string "field 1" - // Field 2: group containing: - // Field 1: fixed int32 value 100 - // Field 2: string "ignore me" - // Field 3: nested group containing - // Field 1: fixed int64 value 1000 - // Field 3: string "field 3" - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - output.WriteTag(1, WireFormat.WireType.LengthDelimited); - output.WriteString("field 1"); - - // The outer group... - output.WriteTag(2, WireFormat.WireType.StartGroup); - output.WriteTag(1, WireFormat.WireType.Fixed32); - output.WriteFixed32(100); - output.WriteTag(2, WireFormat.WireType.LengthDelimited); - output.WriteString("ignore me"); - // The nested group... - output.WriteTag(3, WireFormat.WireType.StartGroup); - output.WriteTag(1, WireFormat.WireType.Fixed64); - output.WriteFixed64(1000); - // Note: Not sure the field number is relevant for end group... - output.WriteTag(3, WireFormat.WireType.EndGroup); - - // End the outer group - output.WriteTag(2, WireFormat.WireType.EndGroup); - - output.WriteTag(3, WireFormat.WireType.LengthDelimited); - output.WriteString("field 3"); - output.Flush(); - stream.Position = 0; - - // Now act like a generated client - var input = new CodedInputStream(stream); - Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); - Assert.AreEqual("field 1", input.ReadString()); - Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); - input.SkipLastField(); // Should consume the whole group, including the nested one. - Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag()); - Assert.AreEqual("field 3", input.ReadString()); - } - - [Test] - public void SkipGroup_WrongEndGroupTag() - { - // Create an output stream with: - // Field 1: string "field 1" - // Start group 2 - // Field 3: fixed int32 - // End group 4 (should give an error) - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - output.WriteTag(1, WireFormat.WireType.LengthDelimited); - output.WriteString("field 1"); - - // The outer group... - output.WriteTag(2, WireFormat.WireType.StartGroup); - output.WriteTag(3, WireFormat.WireType.Fixed32); - output.WriteFixed32(100); - output.WriteTag(4, WireFormat.WireType.EndGroup); - output.Flush(); - stream.Position = 0; - - // Now act like a generated client - var input = new CodedInputStream(stream); - Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); - Assert.AreEqual("field 1", input.ReadString()); - Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); - Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); - } - - [Test] - public void RogueEndGroupTag() - { - // If we have an end-group tag without a leading start-group tag, generated - // code will just call SkipLastField... so that should fail. - - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - output.WriteTag(1, WireFormat.WireType.EndGroup); - output.Flush(); - stream.Position = 0; - - var input = new CodedInputStream(stream); - Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag()); - Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); - } - - [Test] - public void EndOfStreamReachedWhileSkippingGroup() - { - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - output.WriteTag(1, WireFormat.WireType.StartGroup); - output.WriteTag(2, WireFormat.WireType.StartGroup); - output.WriteTag(2, WireFormat.WireType.EndGroup); - - output.Flush(); - stream.Position = 0; - - // Now act like a generated client - var input = new CodedInputStream(stream); - input.ReadTag(); - Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); - } - - [Test] - public void RecursionLimitAppliedWhileSkippingGroup() - { - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) - { - output.WriteTag(1, WireFormat.WireType.StartGroup); - } - for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) - { - output.WriteTag(1, WireFormat.WireType.EndGroup); - } - output.Flush(); - stream.Position = 0; - - // Now act like a generated client - var input = new CodedInputStream(stream); - Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag()); - Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); - } - - [Test] - public void Construction_Invalid() - { - Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null)); - Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0)); - Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null)); - Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0)); - Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10)); - } - - [Test] - public void CreateWithLimits_InvalidLimits() - { - var stream = new MemoryStream(); - Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1)); - Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0)); - } - - [Test] - public void Dispose_DisposesUnderlyingStream() - { - var memoryStream = new MemoryStream(); - Assert.IsTrue(memoryStream.CanRead); - using (var cis = new CodedInputStream(memoryStream)) - { - } - Assert.IsFalse(memoryStream.CanRead); // Disposed - } - - [Test] - public void Dispose_WithLeaveOpen() - { - var memoryStream = new MemoryStream(); - Assert.IsTrue(memoryStream.CanRead); - using (var cis = new CodedInputStream(memoryStream, true)) - { - } - Assert.IsTrue(memoryStream.CanRead); // We left the stream open - } - - [Test] - public void Dispose_FromByteArray() - { - var stream = new CodedInputStream(new byte[10]); - stream.Dispose(); - } - - [Test] - public void TestParseMessagesCloseTo2G() - { - byte[] serializedMessage = GenerateBigSerializedMessage(); - // How many of these big messages do we need to take us near our 2GB limit? - int count = Int32.MaxValue / serializedMessage.Length; - // Now make a MemoryStream that will fake a near-2GB stream of messages by returning - // our big serialized message 'count' times. - using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count)) - { - Assert.DoesNotThrow(()=>TestAllTypes.Parser.ParseFrom(stream)); - } - } - - [Test] - public void TestParseMessagesOver2G() - { - byte[] serializedMessage = GenerateBigSerializedMessage(); - // How many of these big messages do we need to take us near our 2GB limit? - int count = Int32.MaxValue / serializedMessage.Length; - // Now add one to take us over the 2GB limit - count++; - // Now make a MemoryStream that will fake a near-2GB stream of messages by returning - // our big serialized message 'count' times. - using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count)) - { - Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream), - "Protocol message was too large. May be malicious. " + - "Use CodedInputStream.SetSizeLimit() to increase the size limit."); - } - } - - /// <returns>A serialized big message</returns> - private static byte[] GenerateBigSerializedMessage() - { - byte[] value = new byte[16 * 1024 * 1024]; - TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); - message.SingleBytes = ByteString.CopyFrom(value); - return message.ToByteArray(); - } - - /// <summary> - /// A MemoryStream that repeats a byte arrays' content a number of times. - /// Simulates really large input without consuming loads of memory. Used above - /// to test the parsing behavior when the input size exceeds 2GB or close to it. - /// </summary> - private class RepeatingMemoryStream: MemoryStream - { - private readonly byte[] bytes; - private readonly int maxIterations; - private int index = 0; - - public RepeatingMemoryStream(byte[] bytes, int maxIterations) - { - this.bytes = bytes; - this.maxIterations = maxIterations; - } - - public override int Read(byte[] buffer, int offset, int count) - { - if (bytes.Length == 0) - { - return 0; - } - int numBytesCopiedTotal = 0; - while (numBytesCopiedTotal < count && index < maxIterations) - { - int numBytesToCopy = Math.Min(bytes.Length - (int)Position, count); - Array.Copy(bytes, (int)Position, buffer, offset, numBytesToCopy); - numBytesCopiedTotal += numBytesToCopy; - offset += numBytesToCopy; - count -= numBytesCopiedTotal; - Position += numBytesToCopy; - if (Position >= bytes.Length) - { - Position = 0; - index++; - } - } - return numBytesCopiedTotal; - } - } - } -} +#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 Google.Protobuf.TestProtos; +using Proto2 = Google.Protobuf.TestProtos.Proto2; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class CodedInputStreamTest + { + /// <summary> + /// Helper to construct a byte array from a bunch of bytes. The inputs are + /// actually ints so that I can use hex notation and not get stupid errors + /// about precision. + /// </summary> + private static byte[] Bytes(params int[] bytesAsInts) + { + byte[] bytes = new byte[bytesAsInts.Length]; + for (int i = 0; i < bytesAsInts.Length; i++) + { + bytes[i] = (byte) bytesAsInts[i]; + } + return bytes; + } + + /// <summary> + /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() + /// </summary> + private static void AssertReadVarint(byte[] data, ulong value) + { + 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) + { + input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); + Assert.AreEqual((uint) value, input.ReadRawVarint32()); + + 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 + // doesn't read past the end of the input, so write an extra byte - this + // lets us test the position at the end. + MemoryStream memoryStream = new MemoryStream(); + memoryStream.Write(data, 0, data.Length); + memoryStream.WriteByte(0); + memoryStream.Position = 0; + Assert.AreEqual((uint) value, CodedInputStream.ReadRawVarint32(memoryStream)); + Assert.AreEqual(data.Length, memoryStream.Position); + } + + /// <summary> + /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and + /// expects them to fail with an InvalidProtocolBufferException whose + /// description matches the given one. + /// </summary> + private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) + { + CodedInputStream input = new CodedInputStream(data); + var exception = Assert.Throws<InvalidProtocolBufferException>(() => input.ReadRawVarint32()); + Assert.AreEqual(expected.Message, exception.Message); + + input = new CodedInputStream(data); + 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) + { + // Check as ReadOnlySequence<byte> + ParseContext.Initialize(input, out ParseContext parseCtx); + assertAction(ref parseCtx); + if (assertIsAtEnd) + { + Assert.IsTrue(SegmentedBufferHelper.IsAtEnd(ref parseCtx.buffer, ref parseCtx.state)); + } + + // Check as ReadOnlySpan<byte> + ParseContext.Initialize(input.ToArray().AsSpan(), out ParseContext spanParseContext); + assertAction(ref spanParseContext); + if (assertIsAtEnd) + { + Assert.IsTrue(SegmentedBufferHelper.IsAtEnd(ref spanParseContext.buffer, ref spanParseContext.state)); + } + } + + [Test] + public void ReadVarint() + { + AssertReadVarint(Bytes(0x00), 0); + AssertReadVarint(Bytes(0x01), 1); + AssertReadVarint(Bytes(0x7f), 127); + // 14882 + AssertReadVarint(Bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7)); + // 2961488830 + AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b), + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x0bL << 28)); + + // 64-bit + // 7256456126 + AssertReadVarint(Bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b), + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x1bL << 28)); + // 41256202580718336 + AssertReadVarint(Bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49), + (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | + (0x43L << 28) | (0x49L << 35) | (0x24L << 42) | (0x49L << 49)); + // 11964378330978735131 + AssertReadVarint(Bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01), + (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | + (0x3bUL << 28) | (0x56UL << 35) | (0x00UL << 42) | + (0x05UL << 49) | (0x26UL << 56) | (0x01UL << 63)); + + // Failures + AssertReadVarintFailure( + InvalidProtocolBufferException.MalformedVarint(), + Bytes(0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x00)); + AssertReadVarintFailure( + InvalidProtocolBufferException.TruncatedMessage(), + Bytes(0x80)); + } + + /// <summary> + /// Parses the given bytes using ReadRawLittleEndian32() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertReadLittleEndian32(byte[] data, uint value) + { + CodedInputStream input = new CodedInputStream(data); + 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) + { + input = new CodedInputStream( + 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); + } + } + + /// <summary> + /// Parses the given bytes using ReadRawLittleEndian64() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertReadLittleEndian64(byte[] data, ulong value) + { + CodedInputStream input = new CodedInputStream(data); + 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) + { + input = new CodedInputStream( + 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); + } + } + + [Test] + public void ReadLittleEndian() + { + AssertReadLittleEndian32(Bytes(0x78, 0x56, 0x34, 0x12), 0x12345678); + AssertReadLittleEndian32(Bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0); + + AssertReadLittleEndian64(Bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), + 0x123456789abcdef0L); + AssertReadLittleEndian64( + Bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678UL); + } + + [Test] + public void DecodeZigZag32() + { + 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, 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] + public void ReadWholeMessage_VaryingBlockSizes() + { + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + + byte[] rawBytes = message.ToByteArray(); + Assert.AreEqual(rawBytes.Length, message.CalculateSize()); + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); + Assert.AreEqual(message, message2); + + // Try different block sizes. + for (int blockSize = 1; blockSize < 256; blockSize *= 2) + { + message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); + Assert.AreEqual(message, message2); + } + } + + [Test] + public void ReadWholeMessage_VaryingBlockSizes_FromSequence() + { + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + + byte[] rawBytes = message.ToByteArray(); + Assert.AreEqual(rawBytes.Length, message.CalculateSize()); + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); + Assert.AreEqual(message, message2); + + // Try different block sizes. + for (int blockSize = 1; blockSize < 256; blockSize *= 2) + { + message2 = TestAllTypes.Parser.ParseFrom(ReadOnlySequenceFactory.CreateWithContent(rawBytes, blockSize)); + Assert.AreEqual(message, message2); + } + } + + [Test] + public void ReadInt32Wrapper_VariableBlockSizes() + { + byte[] rawBytes = new byte[] { 202, 1, 11, 8, 254, 255, 255, 255, 255, 255, 255, 255, 255, 1 }; + + for (int blockSize = 1; blockSize <= rawBytes.Length; blockSize++) + { + ReadOnlySequence<byte> data = ReadOnlySequenceFactory.CreateWithContent(rawBytes, blockSize); + AssertReadFromParseContext(data, (ref ParseContext ctx) => + { + ctx.ReadTag(); + + var value = ParsingPrimitivesWrappers.ReadInt32Wrapper(ref ctx); + + Assert.AreEqual(-2, value); + }, true); + } + } + + [Test] + public void ReadHugeBlob() + { + // Allocate and initialize a 1MB blob. + byte[] blob = new byte[1 << 20]; + for (int i = 0; i < blob.Length; i++) + { + blob[i] = (byte) i; + } + + // Make a message containing it. + var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) }; + + // Serialize and parse it. Make sure to parse from an InputStream, not + // directly from a ByteString, so that CodedInputStream uses buffered + // reading. + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString()); + + Assert.AreEqual(message, message2); + } + + [Test] + public void ReadMaliciouslyLargeBlob() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteRawVarint32(0x7FFFFFFF); + output.WriteRawBytes(new byte[32]); // Pad with a few random bytes. + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + Assert.AreEqual(tag, input.ReadTag()); + + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); + } + + [Test] + public void ReadBlobGreaterThanCurrentLimit() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteRawVarint32(4); + output.WriteRawBytes(new byte[4]); // Pad with a few random bytes. + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + Assert.AreEqual(tag, input.ReadTag()); + + // Specify limit smaller than data length + input.PushLimit(3); + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); + + AssertReadFromParseContext(new ReadOnlySequence<byte>(ms.ToArray()), (ref ParseContext ctx) => + { + Assert.AreEqual(tag, ctx.ReadTag()); + SegmentedBufferHelper.PushLimit(ref ctx.state, 3); + try + { + ctx.ReadBytes(); + Assert.Fail(); + } + catch (InvalidProtocolBufferException) {} + }, true); + } + + [Test] + public void ReadStringGreaterThanCurrentLimit() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteRawVarint32(4); + output.WriteRawBytes(new byte[4]); // Pad with a few random bytes. + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms.ToArray()); + Assert.AreEqual(tag, input.ReadTag()); + + // Specify limit smaller than data length + input.PushLimit(3); + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString()); + + AssertReadFromParseContext(new ReadOnlySequence<byte>(ms.ToArray()), (ref ParseContext ctx) => + { + Assert.AreEqual(tag, ctx.ReadTag()); + SegmentedBufferHelper.PushLimit(ref ctx.state, 3); + try + { + ctx.ReadString(); + Assert.Fail(); + } + catch (InvalidProtocolBufferException) { } + }, true); + } + + // Representations of a tag for field 0 with various wire types + [Test] + [TestCase(0)] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + public void ReadTag_ZeroFieldRejected(byte tag) + { + CodedInputStream cis = new CodedInputStream(new byte[] { tag }); + Assert.Throws<InvalidProtocolBufferException>(() => cis.ReadTag()); + } + + internal static TestRecursiveMessage MakeRecursiveMessage(int depth) + { + if (depth == 0) + { + return new TestRecursiveMessage { I = 5 }; + } + else + { + return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) }; + } + } + + internal static void AssertMessageDepth(TestRecursiveMessage message, int depth) + { + if (depth == 0) + { + Assert.IsNull(message.A); + Assert.AreEqual(5, message.I); + } + else + { + Assert.IsNotNull(message.A); + AssertMessageDepth(message.A, depth - 1); + } + } + + [Test] + public void MaliciousRecursion() + { + ByteString atRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit).ToByteString(); + ByteString beyondRecursiveLimit = MakeRecursiveMessage(CodedInputStream.DefaultRecursionLimit + 1).ToByteString(); + + AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(atRecursiveLimit), CodedInputStream.DefaultRecursionLimit); + + Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(beyondRecursiveLimit)); + + 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() + { + // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't + // apply to the latter case. + MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray()); + CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100); + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(input)); + } + + /// <summary> + /// Tests that if we read an string that contains invalid UTF-8, no exception + /// is thrown. Instead, the invalid bytes are replaced with the Unicode + /// "replacement character" U+FFFD. + /// </summary> + [Test] + public void ReadInvalidUtf8() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteRawVarint32(1); + output.WriteRawBytes(new byte[] {0x80}); + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + + Assert.AreEqual(tag, input.ReadTag()); + string text = input.ReadString(); + Assert.AreEqual('\ufffd', text[0]); + } + + [Test] + public void ReadNegativeSizedStringThrowsInvalidProtocolBufferException() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteLength(-1); + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + + Assert.AreEqual(tag, input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadString()); + } + + [Test] + public void ReadNegativeSizedBytesThrowsInvalidProtocolBufferException() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteLength(-1); + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + + Assert.AreEqual(tag, input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadBytes()); + } + + /// <summary> + /// A stream which limits the number of bytes it reads at a time. + /// We use this to make sure that CodedInputStream doesn't screw up when + /// reading in small blocks. + /// </summary> + private sealed class SmallBlockInputStream : MemoryStream + { + private readonly int blockSize; + + public SmallBlockInputStream(byte[] data, int blockSize) + : base(data) + { + this.blockSize = blockSize; + } + + public override int Read(byte[] buffer, int offset, int count) + { + return base.Read(buffer, offset, Math.Min(count, blockSize)); + } + } + + [Test] + public void TestNegativeEnum() + { + byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; + CodedInputStream input = new CodedInputStream(bytes); + Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum()); + Assert.IsTrue(input.IsAtEnd); + } + + //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily + [Test] + public void TestSlowPathAvoidance() + { + using (var ms = new MemoryStream()) + { + CodedOutputStream output = new CodedOutputStream(ms); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteBytes(ByteString.CopyFrom(new byte[100])); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteBytes(ByteString.CopyFrom(new byte[100])); + output.Flush(); + + ms.Position = 0; + CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0, false); + + uint tag = input.ReadTag(); + Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); + Assert.AreEqual(100, input.ReadBytes().Length); + + tag = input.ReadTag(); + Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); + Assert.AreEqual(100, input.ReadBytes().Length); + } + } + + [Test] + public void MaximumFieldNumber() + { + MemoryStream ms = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(ms); + + int fieldNumber = 0x1FFFFFFF; + uint tag = WireFormat.MakeTag(fieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteRawVarint32(tag); + output.WriteString("field 1"); + output.Flush(); + ms.Position = 0; + + CodedInputStream input = new CodedInputStream(ms); + + Assert.AreEqual(tag, input.ReadTag()); + Assert.AreEqual(fieldNumber, WireFormat.GetTagFieldNumber(tag)); + } + + [Test] + public void Tag0Throws() + { + var input = new CodedInputStream(new byte[] { 0 }); + Assert.Throws<InvalidProtocolBufferException>(() => input.ReadTag()); + } + + [Test] + public void SkipGroup() + { + // Create an output stream with a group in: + // Field 1: string "field 1" + // Field 2: group containing: + // Field 1: fixed int32 value 100 + // Field 2: string "ignore me" + // Field 3: nested group containing + // Field 1: fixed int64 value 1000 + // Field 3: string "field 3" + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString("field 1"); + + // The outer group... + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(1, WireFormat.WireType.Fixed32); + output.WriteFixed32(100); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteString("ignore me"); + // The nested group... + output.WriteTag(3, WireFormat.WireType.StartGroup); + output.WriteTag(1, WireFormat.WireType.Fixed64); + output.WriteFixed64(1000); + // Note: Not sure the field number is relevant for end group... + output.WriteTag(3, WireFormat.WireType.EndGroup); + + // End the outer group + output.WriteTag(2, WireFormat.WireType.EndGroup); + + output.WriteTag(3, WireFormat.WireType.LengthDelimited); + output.WriteString("field 3"); + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 1", input.ReadString()); + Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); + input.SkipLastField(); // Should consume the whole group, including the nested one. + Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 3", input.ReadString()); + } + + [Test] + public void SkipGroup_WrongEndGroupTag() + { + // Create an output stream with: + // Field 1: string "field 1" + // Start group 2 + // Field 3: fixed int32 + // End group 4 (should give an error) + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString("field 1"); + + // The outer group... + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(3, WireFormat.WireType.Fixed32); + output.WriteFixed32(100); + output.WriteTag(4, WireFormat.WireType.EndGroup); + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 1", input.ReadString()); + Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void RogueEndGroupTag() + { + // If we have an end-group tag without a leading start-group tag, generated + // code will just call SkipLastField... so that should fail. + + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.EndGroup); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.EndGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void EndOfStreamReachedWhileSkippingGroup() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.StartGroup); + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(2, WireFormat.WireType.EndGroup); + + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + input.ReadTag(); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void RecursionLimitAppliedWhileSkippingGroup() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) + { + output.WriteTag(1, WireFormat.WireType.StartGroup); + } + for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) + { + output.WriteTag(1, WireFormat.WireType.EndGroup); + } + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag()); + Assert.Throws<InvalidProtocolBufferException>(input.SkipLastField); + } + + [Test] + public void Construction_Invalid() + { + Assert.Throws<ArgumentNullException>(() => new CodedInputStream((byte[]) null)); + Assert.Throws<ArgumentNullException>(() => new CodedInputStream(null, 0, 0)); + Assert.Throws<ArgumentNullException>(() => new CodedInputStream((Stream) null)); + Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 100, 0)); + Assert.Throws<ArgumentOutOfRangeException>(() => new CodedInputStream(new byte[10], 5, 10)); + } + + [Test] + public void CreateWithLimits_InvalidLimits() + { + var stream = new MemoryStream(); + Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 0, 1)); + Assert.Throws<ArgumentOutOfRangeException>(() => CodedInputStream.CreateWithLimits(stream, 1, 0)); + } + + [Test] + public void Dispose_DisposesUnderlyingStream() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanRead); + using (var cis = new CodedInputStream(memoryStream)) + { + } + Assert.IsFalse(memoryStream.CanRead); // Disposed + } + + [Test] + public void Dispose_WithLeaveOpen() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanRead); + using (var cis = new CodedInputStream(memoryStream, true)) + { + } + Assert.IsTrue(memoryStream.CanRead); // We left the stream open + } + + [Test] + public void Dispose_FromByteArray() + { + var stream = new CodedInputStream(new byte[10]); + stream.Dispose(); + } + + [Test] + public void TestParseMessagesCloseTo2G() + { + byte[] serializedMessage = GenerateBigSerializedMessage(); + // How many of these big messages do we need to take us near our 2GB limit? + int count = Int32.MaxValue / serializedMessage.Length; + // Now make a MemoryStream that will fake a near-2GB stream of messages by returning + // our big serialized message 'count' times. + using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count)) + { + Assert.DoesNotThrow(()=>TestAllTypes.Parser.ParseFrom(stream)); + } + } + + [Test] + public void TestParseMessagesOver2G() + { + byte[] serializedMessage = GenerateBigSerializedMessage(); + // How many of these big messages do we need to take us near our 2GB limit? + int count = Int32.MaxValue / serializedMessage.Length; + // Now add one to take us over the 2GB limit + count++; + // Now make a MemoryStream that will fake a near-2GB stream of messages by returning + // our big serialized message 'count' times. + using (RepeatingMemoryStream stream = new RepeatingMemoryStream(serializedMessage, count)) + { + Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseFrom(stream), + "Protocol message was too large. May be malicious. " + + "Use CodedInputStream.SetSizeLimit() to increase the size limit."); + } + } + + /// <returns>A serialized big message</returns> + private static byte[] GenerateBigSerializedMessage() + { + byte[] value = new byte[16 * 1024 * 1024]; + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + message.SingleBytes = ByteString.CopyFrom(value); + return message.ToByteArray(); + } + + /// <summary> + /// A MemoryStream that repeats a byte arrays' content a number of times. + /// Simulates really large input without consuming loads of memory. Used above + /// to test the parsing behavior when the input size exceeds 2GB or close to it. + /// </summary> + private class RepeatingMemoryStream: MemoryStream + { + private readonly byte[] bytes; + private readonly int maxIterations; + private int index = 0; + + public RepeatingMemoryStream(byte[] bytes, int maxIterations) + { + this.bytes = bytes; + this.maxIterations = maxIterations; + } + + public override int Read(byte[] buffer, int offset, int count) + { + if (bytes.Length == 0) + { + return 0; + } + int numBytesCopiedTotal = 0; + while (numBytesCopiedTotal < count && index < maxIterations) + { + int numBytesToCopy = Math.Min(bytes.Length - (int)Position, count); + Array.Copy(bytes, (int)Position, buffer, offset, numBytesToCopy); + numBytesCopiedTotal += numBytesToCopy; + offset += numBytesToCopy; + count -= numBytesCopiedTotal; + Position += numBytesToCopy; + if (Position >= bytes.Length) + { + Position = 0; + index++; + } + } + return numBytesCopiedTotal; + } + } + } +}
diff --git a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs index 1444009..13f83a2 100644 --- a/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs +++ b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs
@@ -1,583 +1,583 @@ -#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.IO; -using Google.Protobuf.TestProtos; -using Google.Protobuf.Buffers; -using NUnit.Framework; -using System.Text; - -namespace Google.Protobuf -{ - public class CodedOutputStreamTest - { - /// <summary> - /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and - /// checks that the result matches the given bytes - /// </summary> - private static void AssertWriteVarint(byte[] data, ulong value) - { - // Only do 32-bit write if the value fits in 32 bits. - if ((value >> 32) == 0) - { - // CodedOutputStream - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput); - output.WriteRawVarint32((uint) value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - // IBufferWriter - var bufferWriter = new TestArrayBufferWriter<byte>(); - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteUInt32((uint) value); - ctx.Flush(); - Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); - - // Also try computing size. - Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value)); - } - - { - // CodedOutputStream - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput); - output.WriteRawVarint64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - // IBufferWriter - var bufferWriter = new TestArrayBufferWriter<byte>(); - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteUInt64(value); - ctx.Flush(); - Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); - - // Also try computing size. - Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value)); - } - - // Try different buffer sizes. - for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) - { - // Only do 32-bit write if the value fits in 32 bits. - if ((value >> 32) == 0) - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = - new CodedOutputStream(rawOutput, bufferSize); - output.WriteRawVarint32((uint) value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - var bufferWriter = new TestArrayBufferWriter<byte>(); - bufferWriter.MaxGrowBy = bufferSize; - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteUInt32((uint) value); - ctx.Flush(); - Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); - } - - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize); - output.WriteRawVarint64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - var bufferWriter = new TestArrayBufferWriter<byte>(); - bufferWriter.MaxGrowBy = bufferSize; - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteUInt64(value); - ctx.Flush(); - Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); - } - - } - } - - /// <summary> - /// Tests WriteRawVarint32() and WriteRawVarint64() - /// </summary> - [Test] - public void WriteVarint() - { - AssertWriteVarint(new byte[] {0x00}, 0); - AssertWriteVarint(new byte[] {0x01}, 1); - AssertWriteVarint(new byte[] {0x7f}, 127); - // 14882 - AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7)); - // 2961488830 - AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b}, - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x0bL << 28)); - - // 64-bit - // 7256456126 - AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b}, - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (0x1bL << 28)); - // 41256202580718336 - AssertWriteVarint( - new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | - (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49)); - // 11964378330978735131 - AssertWriteVarint( - new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, - unchecked((ulong) - ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) | - (0x05L << 49) | (0x26L << 56) | (0x01L << 63)))); - } - - /// <summary> - /// Parses the given bytes using WriteRawLittleEndian32() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertWriteLittleEndian32(byte[] data, uint value) - { - { - var rawOutput = new MemoryStream(); - var output = new CodedOutputStream(rawOutput); - output.WriteRawLittleEndian32(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - var bufferWriter = new TestArrayBufferWriter<byte>(); - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteFixed32(value); - ctx.Flush(); - Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); - } - - // Try different buffer sizes. - for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) - { - var rawOutput = new MemoryStream(); - var output = new CodedOutputStream(rawOutput, bufferSize); - output.WriteRawLittleEndian32(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - var bufferWriter = new TestArrayBufferWriter<byte>(); - bufferWriter.MaxGrowBy = bufferSize; - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteFixed32(value); - ctx.Flush(); - Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); - } - } - - /// <summary> - /// Parses the given bytes using WriteRawLittleEndian64() and checks - /// that the result matches the given value. - /// </summary> - private static void AssertWriteLittleEndian64(byte[] data, ulong value) - { - { - var rawOutput = new MemoryStream(); - var output = new CodedOutputStream(rawOutput); - output.WriteRawLittleEndian64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - var bufferWriter = new TestArrayBufferWriter<byte>(); - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteFixed64(value); - ctx.Flush(); - Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); - } - - // Try different block sizes. - for (int blockSize = 1; blockSize <= 16; blockSize *= 2) - { - var rawOutput = new MemoryStream(); - var output = new CodedOutputStream(rawOutput, blockSize); - output.WriteRawLittleEndian64(value); - output.Flush(); - Assert.AreEqual(data, rawOutput.ToArray()); - - var bufferWriter = new TestArrayBufferWriter<byte>(); - bufferWriter.MaxGrowBy = blockSize; - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteFixed64(value); - ctx.Flush(); - Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); - } - } - - /// <summary> - /// Tests writeRawLittleEndian32() and writeRawLittleEndian64(). - /// </summary> - [Test] - public void WriteLittleEndian() - { - AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678); - AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0); - - AssertWriteLittleEndian64( - new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}, - 0x123456789abcdef0L); - AssertWriteLittleEndian64( - new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a}, - 0x9abcdef012345678UL); - } - - [Test] - public void WriteWholeMessage_VaryingBlockSizes() - { - TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); - - byte[] rawBytes = message.ToByteArray(); - - // Try different block sizes. - for (int blockSize = 1; blockSize < 256; blockSize *= 2) - { - MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize); - message.WriteTo(output); - output.Flush(); - Assert.AreEqual(rawBytes, rawOutput.ToArray()); - - var bufferWriter = new TestArrayBufferWriter<byte>(); - bufferWriter.MaxGrowBy = blockSize; - message.WriteTo(bufferWriter); - Assert.AreEqual(rawBytes, bufferWriter.WrittenSpan.ToArray()); - } - } - - [Test] - public void WriteContext_WritesWithFlushes() - { - TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); - - MemoryStream expectedOutput = new MemoryStream(); - CodedOutputStream output = new CodedOutputStream(expectedOutput); - output.WriteMessage(message); - output.Flush(); - byte[] expectedBytes1 = expectedOutput.ToArray(); - - output.WriteMessage(message); - output.Flush(); - byte[] expectedBytes2 = expectedOutput.ToArray(); - - var bufferWriter = new TestArrayBufferWriter<byte>(); - WriteContext.Initialize(bufferWriter, out WriteContext ctx); - ctx.WriteMessage(message); - ctx.Flush(); - Assert.AreEqual(expectedBytes1, bufferWriter.WrittenSpan.ToArray()); - - ctx.WriteMessage(message); - ctx.Flush(); - Assert.AreEqual(expectedBytes2, bufferWriter.WrittenSpan.ToArray()); - } - - [Test] - public void EncodeZigZag32() - { - Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag32(0)); - Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag32(-1)); - Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag32(1)); - Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag32(-2)); - Assert.AreEqual(0x7FFFFFFEu, WritingPrimitives.EncodeZigZag32(0x3FFFFFFF)); - Assert.AreEqual(0x7FFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0xC0000000))); - Assert.AreEqual(0xFFFFFFFEu, WritingPrimitives.EncodeZigZag32(0x7FFFFFFF)); - Assert.AreEqual(0xFFFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0x80000000))); - } - - [Test] - public void EncodeZigZag64() - { - Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag64(0)); - Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag64(-1)); - Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag64(1)); - Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag64(-2)); - Assert.AreEqual(0x000000007FFFFFFEuL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL))); - Assert.AreEqual(0x000000007FFFFFFFuL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL))); - Assert.AreEqual(0x00000000FFFFFFFEuL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL))); - Assert.AreEqual(0x00000000FFFFFFFFuL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL))); - Assert.AreEqual(0xFFFFFFFFFFFFFFFEL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL))); - Assert.AreEqual(0xFFFFFFFFFFFFFFFFL, - WritingPrimitives.EncodeZigZag64(unchecked((long) 0x8000000000000000UL))); - } - - [Test] - public void RoundTripZigZag32() - { - // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) - // were chosen semi-randomly via keyboard bashing. - Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(0))); - Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(1))); - Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-1))); - Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(14927))); - Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-3612))); - } - - [Test] - public void RoundTripZigZag64() - { - Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(0))); - Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(1))); - Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-1))); - Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(14927))); - Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-3612))); - - Assert.AreEqual(856912304801416L, - ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(856912304801416L))); - Assert.AreEqual(-75123905439571256L, - ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-75123905439571256L))); - } - - [Test] - public void TestNegativeEnumNoTag() - { - Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2)); - Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue)); - - byte[] bytes = new byte[10]; - CodedOutputStream output = new CodedOutputStream(bytes); - output.WriteEnum((int) SampleEnum.NegativeValue); - - Assert.AreEqual(0, output.SpaceLeft); - Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); - } - - [Test] - public void TestCodedInputOutputPosition() - { - byte[] content = new byte[110]; - for (int i = 0; i < content.Length; i++) - content[i] = (byte)i; - - byte[] child = new byte[120]; - { - MemoryStream ms = new MemoryStream(child); - CodedOutputStream cout = new CodedOutputStream(ms, 20); - // Field 11: numeric value: 500 - cout.WriteTag(11, WireFormat.WireType.Varint); - Assert.AreEqual(1, cout.Position); - cout.WriteInt32(500); - Assert.AreEqual(3, cout.Position); - //Field 12: length delimited 120 bytes - cout.WriteTag(12, WireFormat.WireType.LengthDelimited); - Assert.AreEqual(4, cout.Position); - cout.WriteBytes(ByteString.CopyFrom(content)); - Assert.AreEqual(115, cout.Position); - // Field 13: fixed numeric value: 501 - cout.WriteTag(13, WireFormat.WireType.Fixed32); - Assert.AreEqual(116, cout.Position); - cout.WriteSFixed32(501); - Assert.AreEqual(120, cout.Position); - cout.Flush(); - } - - byte[] bytes = new byte[130]; - { - CodedOutputStream cout = new CodedOutputStream(bytes); - // Field 1: numeric value: 500 - cout.WriteTag(1, WireFormat.WireType.Varint); - Assert.AreEqual(1, cout.Position); - cout.WriteInt32(500); - Assert.AreEqual(3, cout.Position); - //Field 2: length delimited 120 bytes - cout.WriteTag(2, WireFormat.WireType.LengthDelimited); - Assert.AreEqual(4, cout.Position); - cout.WriteBytes(ByteString.CopyFrom(child)); - Assert.AreEqual(125, cout.Position); - // Field 3: fixed numeric value: 500 - cout.WriteTag(3, WireFormat.WireType.Fixed32); - Assert.AreEqual(126, cout.Position); - cout.WriteSFixed32(501); - Assert.AreEqual(130, cout.Position); - cout.Flush(); - } - // Now test Input stream: - { - CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false); - Assert.AreEqual(0, cin.Position); - // Field 1: - uint tag = cin.ReadTag(); - Assert.AreEqual(1, tag >> 3); - Assert.AreEqual(1, cin.Position); - Assert.AreEqual(500, cin.ReadInt32()); - Assert.AreEqual(3, cin.Position); - //Field 2: - tag = cin.ReadTag(); - Assert.AreEqual(2, tag >> 3); - Assert.AreEqual(4, cin.Position); - int childlen = cin.ReadLength(); - Assert.AreEqual(120, childlen); - Assert.AreEqual(5, cin.Position); - int oldlimit = cin.PushLimit((int)childlen); - Assert.AreEqual(5, cin.Position); - // Now we are reading child message - { - // Field 11: numeric value: 500 - tag = cin.ReadTag(); - Assert.AreEqual(11, tag >> 3); - Assert.AreEqual(6, cin.Position); - Assert.AreEqual(500, cin.ReadInt32()); - Assert.AreEqual(8, cin.Position); - //Field 12: length delimited 120 bytes - tag = cin.ReadTag(); - Assert.AreEqual(12, tag >> 3); - Assert.AreEqual(9, cin.Position); - ByteString bstr = cin.ReadBytes(); - Assert.AreEqual(110, bstr.Length); - Assert.AreEqual((byte) 109, bstr[109]); - Assert.AreEqual(120, cin.Position); - // Field 13: fixed numeric value: 501 - tag = cin.ReadTag(); - Assert.AreEqual(13, tag >> 3); - // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit - Assert.AreEqual(121, cin.Position); - Assert.AreEqual(501, cin.ReadSFixed32()); - Assert.AreEqual(125, cin.Position); - Assert.IsTrue(cin.IsAtEnd); - } - cin.PopLimit(oldlimit); - Assert.AreEqual(125, cin.Position); - // Field 3: fixed numeric value: 501 - tag = cin.ReadTag(); - Assert.AreEqual(3, tag >> 3); - Assert.AreEqual(126, cin.Position); - Assert.AreEqual(501, cin.ReadSFixed32()); - Assert.AreEqual(130, cin.Position); - Assert.IsTrue(cin.IsAtEnd); - } - } - - [Test] - public void Dispose_DisposesUnderlyingStream() - { - var memoryStream = new MemoryStream(); - Assert.IsTrue(memoryStream.CanWrite); - using (var cos = new CodedOutputStream(memoryStream)) - { - cos.WriteRawBytes(new byte[] {0}); - Assert.AreEqual(0, memoryStream.Position); // Not flushed yet - } - Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream - Assert.IsFalse(memoryStream.CanWrite); // Disposed - } - - [Test] - public void Dispose_WithLeaveOpen() - { - var memoryStream = new MemoryStream(); - Assert.IsTrue(memoryStream.CanWrite); - using (var cos = new CodedOutputStream(memoryStream, true)) - { - cos.WriteRawBytes(new byte[] {0}); - Assert.AreEqual(0, memoryStream.Position); // Not flushed yet - } - Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream - Assert.IsTrue(memoryStream.CanWrite); // We left the stream open - } - - [Test] - public void Dispose_FromByteArray() - { - var stream = new CodedOutputStream(new byte[10]); - stream.Dispose(); - } - - [Test] - public void WriteString_AsciiSmall_MaxUtf8SizeExceedsBuffer() - { - var buffer = new byte[5]; - var output = new CodedOutputStream(buffer); - output.WriteString("ABC"); - - output.Flush(); - - // Verify written content - var input = new CodedInputStream(buffer); - Assert.AreEqual("ABC", input.ReadString()); - } - - [Test] - public void WriteStringsOfDifferentSizes_Ascii() - { - for (int i = 1; i <= 1024; i++) - { - var buffer = new byte[4096]; - var output = new CodedOutputStream(buffer); - var sb = new StringBuilder(); - for (int j = 0; j < i; j++) - { - sb.Append((j % 10).ToString()); // incrementing numbers, repeating - } - var s = sb.ToString(); - output.WriteString(s); - - output.Flush(); - - // Verify written content - var input = new CodedInputStream(buffer); - Assert.AreEqual(s, input.ReadString()); - } - } - - [Test] - public void WriteStringsOfDifferentSizes_Unicode() - { - for (int i = 1; i <= 1024; i++) - { - var buffer = new byte[4096]; - var output = new CodedOutputStream(buffer); - var sb = new StringBuilder(); - for (int j = 0; j < i; j++) - { - char c = (char)((j % 10) + 10112); - sb.Append(c.ToString()); // incrementing unicode numbers, repeating - } - var s = sb.ToString(); - output.WriteString(s); - - output.Flush(); - - // Verify written content - var input = new CodedInputStream(buffer); - - Assert.AreEqual(s, input.ReadString()); - } - } - } +#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.IO; +using Google.Protobuf.TestProtos; +using Google.Protobuf.Buffers; +using NUnit.Framework; +using System.Text; + +namespace Google.Protobuf +{ + public class CodedOutputStreamTest + { + /// <summary> + /// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and + /// checks that the result matches the given bytes + /// </summary> + private static void AssertWriteVarint(byte[] data, ulong value) + { + // Only do 32-bit write if the value fits in 32 bits. + if ((value >> 32) == 0) + { + // CodedOutputStream + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawVarint32((uint) value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + // IBufferWriter + var bufferWriter = new TestArrayBufferWriter<byte>(); + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteUInt32((uint) value); + ctx.Flush(); + Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); + + // Also try computing size. + Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value)); + } + + { + // CodedOutputStream + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput); + output.WriteRawVarint64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + // IBufferWriter + var bufferWriter = new TestArrayBufferWriter<byte>(); + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteUInt64(value); + ctx.Flush(); + Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); + + // Also try computing size. + Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value)); + } + + // Try different buffer sizes. + for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) + { + // Only do 32-bit write if the value fits in 32 bits. + if ((value >> 32) == 0) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = + new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawVarint32((uint) value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + var bufferWriter = new TestArrayBufferWriter<byte>(); + bufferWriter.MaxGrowBy = bufferSize; + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteUInt32((uint) value); + ctx.Flush(); + Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); + } + + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawVarint64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + var bufferWriter = new TestArrayBufferWriter<byte>(); + bufferWriter.MaxGrowBy = bufferSize; + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteUInt64(value); + ctx.Flush(); + Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); + } + + } + } + + /// <summary> + /// Tests WriteRawVarint32() and WriteRawVarint64() + /// </summary> + [Test] + public void WriteVarint() + { + AssertWriteVarint(new byte[] {0x00}, 0); + AssertWriteVarint(new byte[] {0x01}, 1); + AssertWriteVarint(new byte[] {0x7f}, 127); + // 14882 + AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7)); + // 2961488830 + AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b}, + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x0bL << 28)); + + // 64-bit + // 7256456126 + AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b}, + (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | + (0x1bL << 28)); + // 41256202580718336 + AssertWriteVarint( + new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, + (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | + (0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49)); + // 11964378330978735131 + AssertWriteVarint( + new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, + unchecked((ulong) + ((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | + (0x3bL << 28) | (0x56L << 35) | (0x00L << 42) | + (0x05L << 49) | (0x26L << 56) | (0x01L << 63)))); + } + + /// <summary> + /// Parses the given bytes using WriteRawLittleEndian32() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertWriteLittleEndian32(byte[] data, uint value) + { + { + var rawOutput = new MemoryStream(); + var output = new CodedOutputStream(rawOutput); + output.WriteRawLittleEndian32(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + var bufferWriter = new TestArrayBufferWriter<byte>(); + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteFixed32(value); + ctx.Flush(); + Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); + } + + // Try different buffer sizes. + for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) + { + var rawOutput = new MemoryStream(); + var output = new CodedOutputStream(rawOutput, bufferSize); + output.WriteRawLittleEndian32(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + var bufferWriter = new TestArrayBufferWriter<byte>(); + bufferWriter.MaxGrowBy = bufferSize; + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteFixed32(value); + ctx.Flush(); + Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); + } + } + + /// <summary> + /// Parses the given bytes using WriteRawLittleEndian64() and checks + /// that the result matches the given value. + /// </summary> + private static void AssertWriteLittleEndian64(byte[] data, ulong value) + { + { + var rawOutput = new MemoryStream(); + var output = new CodedOutputStream(rawOutput); + output.WriteRawLittleEndian64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + var bufferWriter = new TestArrayBufferWriter<byte>(); + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteFixed64(value); + ctx.Flush(); + Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); + } + + // Try different block sizes. + for (int blockSize = 1; blockSize <= 16; blockSize *= 2) + { + var rawOutput = new MemoryStream(); + var output = new CodedOutputStream(rawOutput, blockSize); + output.WriteRawLittleEndian64(value); + output.Flush(); + Assert.AreEqual(data, rawOutput.ToArray()); + + var bufferWriter = new TestArrayBufferWriter<byte>(); + bufferWriter.MaxGrowBy = blockSize; + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteFixed64(value); + ctx.Flush(); + Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray()); + } + } + + /// <summary> + /// Tests writeRawLittleEndian32() and writeRawLittleEndian64(). + /// </summary> + [Test] + public void WriteLittleEndian() + { + AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678); + AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0); + + AssertWriteLittleEndian64( + new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12}, + 0x123456789abcdef0L); + AssertWriteLittleEndian64( + new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a}, + 0x9abcdef012345678UL); + } + + [Test] + public void WriteWholeMessage_VaryingBlockSizes() + { + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + + byte[] rawBytes = message.ToByteArray(); + + // Try different block sizes. + for (int blockSize = 1; blockSize < 256; blockSize *= 2) + { + MemoryStream rawOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize); + message.WriteTo(output); + output.Flush(); + Assert.AreEqual(rawBytes, rawOutput.ToArray()); + + var bufferWriter = new TestArrayBufferWriter<byte>(); + bufferWriter.MaxGrowBy = blockSize; + message.WriteTo(bufferWriter); + Assert.AreEqual(rawBytes, bufferWriter.WrittenSpan.ToArray()); + } + } + + [Test] + public void WriteContext_WritesWithFlushes() + { + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); + + MemoryStream expectedOutput = new MemoryStream(); + CodedOutputStream output = new CodedOutputStream(expectedOutput); + output.WriteMessage(message); + output.Flush(); + byte[] expectedBytes1 = expectedOutput.ToArray(); + + output.WriteMessage(message); + output.Flush(); + byte[] expectedBytes2 = expectedOutput.ToArray(); + + var bufferWriter = new TestArrayBufferWriter<byte>(); + WriteContext.Initialize(bufferWriter, out WriteContext ctx); + ctx.WriteMessage(message); + ctx.Flush(); + Assert.AreEqual(expectedBytes1, bufferWriter.WrittenSpan.ToArray()); + + ctx.WriteMessage(message); + ctx.Flush(); + Assert.AreEqual(expectedBytes2, bufferWriter.WrittenSpan.ToArray()); + } + + [Test] + public void EncodeZigZag32() + { + Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag32(0)); + Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag32(-1)); + Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag32(1)); + Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag32(-2)); + Assert.AreEqual(0x7FFFFFFEu, WritingPrimitives.EncodeZigZag32(0x3FFFFFFF)); + Assert.AreEqual(0x7FFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0xC0000000))); + Assert.AreEqual(0xFFFFFFFEu, WritingPrimitives.EncodeZigZag32(0x7FFFFFFF)); + Assert.AreEqual(0xFFFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0x80000000))); + } + + [Test] + public void EncodeZigZag64() + { + Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag64(0)); + Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag64(-1)); + Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag64(1)); + Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag64(-2)); + Assert.AreEqual(0x000000007FFFFFFEuL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL))); + Assert.AreEqual(0x000000007FFFFFFFuL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL))); + Assert.AreEqual(0x00000000FFFFFFFEuL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL))); + Assert.AreEqual(0x00000000FFFFFFFFuL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL))); + Assert.AreEqual(0xFFFFFFFFFFFFFFFEL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL))); + Assert.AreEqual(0xFFFFFFFFFFFFFFFFL, + WritingPrimitives.EncodeZigZag64(unchecked((long) 0x8000000000000000UL))); + } + + [Test] + public void RoundTripZigZag32() + { + // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) + // were chosen semi-randomly via keyboard bashing. + Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(0))); + Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(1))); + Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-1))); + Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(14927))); + Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-3612))); + } + + [Test] + public void RoundTripZigZag64() + { + Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(0))); + Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(1))); + Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-1))); + Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(14927))); + Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-3612))); + + Assert.AreEqual(856912304801416L, + ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(856912304801416L))); + Assert.AreEqual(-75123905439571256L, + ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-75123905439571256L))); + } + + [Test] + public void TestNegativeEnumNoTag() + { + Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2)); + Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue)); + + byte[] bytes = new byte[10]; + CodedOutputStream output = new CodedOutputStream(bytes); + output.WriteEnum((int) SampleEnum.NegativeValue); + + Assert.AreEqual(0, output.SpaceLeft); + Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); + } + + [Test] + public void TestCodedInputOutputPosition() + { + byte[] content = new byte[110]; + for (int i = 0; i < content.Length; i++) + content[i] = (byte)i; + + byte[] child = new byte[120]; + { + MemoryStream ms = new MemoryStream(child); + CodedOutputStream cout = new CodedOutputStream(ms, 20); + // Field 11: numeric value: 500 + cout.WriteTag(11, WireFormat.WireType.Varint); + Assert.AreEqual(1, cout.Position); + cout.WriteInt32(500); + Assert.AreEqual(3, cout.Position); + //Field 12: length delimited 120 bytes + cout.WriteTag(12, WireFormat.WireType.LengthDelimited); + Assert.AreEqual(4, cout.Position); + cout.WriteBytes(ByteString.CopyFrom(content)); + Assert.AreEqual(115, cout.Position); + // Field 13: fixed numeric value: 501 + cout.WriteTag(13, WireFormat.WireType.Fixed32); + Assert.AreEqual(116, cout.Position); + cout.WriteSFixed32(501); + Assert.AreEqual(120, cout.Position); + cout.Flush(); + } + + byte[] bytes = new byte[130]; + { + CodedOutputStream cout = new CodedOutputStream(bytes); + // Field 1: numeric value: 500 + cout.WriteTag(1, WireFormat.WireType.Varint); + Assert.AreEqual(1, cout.Position); + cout.WriteInt32(500); + Assert.AreEqual(3, cout.Position); + //Field 2: length delimited 120 bytes + cout.WriteTag(2, WireFormat.WireType.LengthDelimited); + Assert.AreEqual(4, cout.Position); + cout.WriteBytes(ByteString.CopyFrom(child)); + Assert.AreEqual(125, cout.Position); + // Field 3: fixed numeric value: 500 + cout.WriteTag(3, WireFormat.WireType.Fixed32); + Assert.AreEqual(126, cout.Position); + cout.WriteSFixed32(501); + Assert.AreEqual(130, cout.Position); + cout.Flush(); + } + // Now test Input stream: + { + CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false); + Assert.AreEqual(0, cin.Position); + // Field 1: + uint tag = cin.ReadTag(); + Assert.AreEqual(1, tag >> 3); + Assert.AreEqual(1, cin.Position); + Assert.AreEqual(500, cin.ReadInt32()); + Assert.AreEqual(3, cin.Position); + //Field 2: + tag = cin.ReadTag(); + Assert.AreEqual(2, tag >> 3); + Assert.AreEqual(4, cin.Position); + int childlen = cin.ReadLength(); + Assert.AreEqual(120, childlen); + Assert.AreEqual(5, cin.Position); + int oldlimit = cin.PushLimit((int)childlen); + Assert.AreEqual(5, cin.Position); + // Now we are reading child message + { + // Field 11: numeric value: 500 + tag = cin.ReadTag(); + Assert.AreEqual(11, tag >> 3); + Assert.AreEqual(6, cin.Position); + Assert.AreEqual(500, cin.ReadInt32()); + Assert.AreEqual(8, cin.Position); + //Field 12: length delimited 120 bytes + tag = cin.ReadTag(); + Assert.AreEqual(12, tag >> 3); + Assert.AreEqual(9, cin.Position); + ByteString bstr = cin.ReadBytes(); + Assert.AreEqual(110, bstr.Length); + Assert.AreEqual((byte) 109, bstr[109]); + Assert.AreEqual(120, cin.Position); + // Field 13: fixed numeric value: 501 + tag = cin.ReadTag(); + Assert.AreEqual(13, tag >> 3); + // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit + Assert.AreEqual(121, cin.Position); + Assert.AreEqual(501, cin.ReadSFixed32()); + Assert.AreEqual(125, cin.Position); + Assert.IsTrue(cin.IsAtEnd); + } + cin.PopLimit(oldlimit); + Assert.AreEqual(125, cin.Position); + // Field 3: fixed numeric value: 501 + tag = cin.ReadTag(); + Assert.AreEqual(3, tag >> 3); + Assert.AreEqual(126, cin.Position); + Assert.AreEqual(501, cin.ReadSFixed32()); + Assert.AreEqual(130, cin.Position); + Assert.IsTrue(cin.IsAtEnd); + } + } + + [Test] + public void Dispose_DisposesUnderlyingStream() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanWrite); + using (var cos = new CodedOutputStream(memoryStream)) + { + cos.WriteRawBytes(new byte[] {0}); + Assert.AreEqual(0, memoryStream.Position); // Not flushed yet + } + Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream + Assert.IsFalse(memoryStream.CanWrite); // Disposed + } + + [Test] + public void Dispose_WithLeaveOpen() + { + var memoryStream = new MemoryStream(); + Assert.IsTrue(memoryStream.CanWrite); + using (var cos = new CodedOutputStream(memoryStream, true)) + { + cos.WriteRawBytes(new byte[] {0}); + Assert.AreEqual(0, memoryStream.Position); // Not flushed yet + } + Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream + Assert.IsTrue(memoryStream.CanWrite); // We left the stream open + } + + [Test] + public void Dispose_FromByteArray() + { + var stream = new CodedOutputStream(new byte[10]); + stream.Dispose(); + } + + [Test] + public void WriteString_AsciiSmall_MaxUtf8SizeExceedsBuffer() + { + var buffer = new byte[5]; + var output = new CodedOutputStream(buffer); + output.WriteString("ABC"); + + output.Flush(); + + // Verify written content + var input = new CodedInputStream(buffer); + Assert.AreEqual("ABC", input.ReadString()); + } + + [Test] + public void WriteStringsOfDifferentSizes_Ascii() + { + for (int i = 1; i <= 1024; i++) + { + var buffer = new byte[4096]; + var output = new CodedOutputStream(buffer); + var sb = new StringBuilder(); + for (int j = 0; j < i; j++) + { + sb.Append((j % 10).ToString()); // incrementing numbers, repeating + } + var s = sb.ToString(); + output.WriteString(s); + + output.Flush(); + + // Verify written content + var input = new CodedInputStream(buffer); + Assert.AreEqual(s, input.ReadString()); + } + } + + [Test] + public void WriteStringsOfDifferentSizes_Unicode() + { + for (int i = 1; i <= 1024; i++) + { + var buffer = new byte[4096]; + var output = new CodedOutputStream(buffer); + var sb = new StringBuilder(); + for (int j = 0; j < i; j++) + { + char c = (char)((j % 10) + 10112); + sb.Append(c.ToString()); // incrementing unicode numbers, repeating + } + var s = sb.ToString(); + output.WriteString(s); + + output.Flush(); + + // Verify written content + var input = new CodedInputStream(buffer); + + Assert.AreEqual(s, input.ReadString()); + } + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs index d4c63dc..1f7b8a3 100644 --- a/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs +++ b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs
@@ -625,8 +625,6 @@ output.WriteString("the_value"); output.Flush(); - Console.WriteLine(BitConverter.ToString(memoryStream.ToArray())); - 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());
diff --git a/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs b/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs index 34d5b9f..fd041e0 100644 --- a/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs +++ b/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs
@@ -1,55 +1,55 @@ -#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 System; -using System.Reflection; -using Google.Protobuf.TestProtos; -using NUnit.Framework; - -namespace Google.Protobuf -{ - public class DeprecatedMemberTest - { - private static void AssertIsDeprecated(MemberInfo member) - { - Assert.NotNull(member); - Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member); - } - - [Test] - public void TestDepreatedPrimitiveValue() - { - AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); - } - - } -} +#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 System; +using System.Reflection; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class DeprecatedMemberTest + { + private static void AssertIsDeprecated(MemberInfo member) + { + Assert.NotNull(member); + Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member); + } + + [Test] + public void TestDepreatedPrimitiveValue() + { + AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); + } + + } +}
diff --git a/csharp/src/Google.Protobuf.Test/ExtensionSetTest.cs b/csharp/src/Google.Protobuf.Test/ExtensionSetTest.cs index 951e856..b2c24dd 100644 --- a/csharp/src/Google.Protobuf.Test/ExtensionSetTest.cs +++ b/csharp/src/Google.Protobuf.Test/ExtensionSetTest.cs
@@ -1,137 +1,196 @@ -using Google.Protobuf.TestProtos.Proto2; -using NUnit.Framework; - -using static Google.Protobuf.TestProtos.Proto2.UnittestExtensions; - -namespace Google.Protobuf -{ - public class ExtensionSetTest - { - [Test] - public void EmptyExtensionSet() - { - ExtensionSet<TestAllExtensions> extensions = new ExtensionSet<TestAllExtensions>(); - Assert.AreEqual(0, extensions.CalculateSize()); - } - - [Test] - public void MergeExtensionSet() - { - ExtensionSet<TestAllExtensions> extensions = null; - ExtensionSet.Set(ref extensions, OptionalBoolExtension, true); - - ExtensionSet<TestAllExtensions> other = null; - - Assert.IsFalse(ExtensionSet.Has(ref other, OptionalBoolExtension)); - ExtensionSet.MergeFrom(ref other, extensions); - Assert.IsTrue(ExtensionSet.Has(ref other, OptionalBoolExtension)); - } - - [Test] - public void TestMergeCodedInput() - { - var message = new TestAllExtensions(); - message.SetExtension(OptionalBoolExtension, true); - var serialized = message.ToByteArray(); - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertReadingMessage( - TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { OptionalBoolExtension }), - serialized, - other => - { - Assert.AreEqual(message, other); - Assert.AreEqual(message.CalculateSize(), other.CalculateSize()); - }); - } - - [Test] - public void TestMergeMessage() - { - var message = new TestAllExtensions(); - message.SetExtension(OptionalBoolExtension, true); - - var other = new TestAllExtensions(); - - Assert.AreNotEqual(message, other); - Assert.AreNotEqual(message.CalculateSize(), other.CalculateSize()); - - other.MergeFrom(message); - - Assert.AreEqual(message, other); - Assert.AreEqual(message.CalculateSize(), other.CalculateSize()); - } - - [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(); - message.SetExtension(OptionalBoolExtension, true); - - var other = new TestAllExtensions(); - - Assert.AreNotEqual(message, other); - Assert.AreNotEqual(message.CalculateSize(), other.CalculateSize()); - - other.SetExtension(OptionalBoolExtension, true); - - Assert.AreEqual(message, other); - Assert.AreEqual(message.CalculateSize(), other.CalculateSize()); - } - - [Test] - public void TestHashCode() - { - var message = new TestAllExtensions(); - var hashCode = message.GetHashCode(); - - message.SetExtension(OptionalBoolExtension, true); - - Assert.AreNotEqual(hashCode, message.GetHashCode()); - } - - [Test] - public void TestClone() - { - var message = new TestAllExtensions(); - message.SetExtension(OptionalBoolExtension, true); - - var other = message.Clone(); - - Assert.AreEqual(message, other); - Assert.AreEqual(message.CalculateSize(), other.CalculateSize()); - } - - [Test] - public void TestDefaultValueRoundTrip() - { - var message = new TestAllExtensions(); - message.SetExtension(OptionalBoolExtension, false); - Assert.IsFalse(message.GetExtension(OptionalBoolExtension)); - Assert.IsTrue(message.HasExtension(OptionalBoolExtension)); - - var bytes = message.ToByteArray(); - var registry = new ExtensionRegistry { OptionalBoolExtension }; - var parsed = TestAllExtensions.Parser.WithExtensionRegistry(registry).ParseFrom(bytes); - Assert.IsFalse(parsed.GetExtension(OptionalBoolExtension)); - Assert.IsTrue(parsed.HasExtension(OptionalBoolExtension)); - } - } -} +using System; +using System.Collections; +using Google.Protobuf.TestProtos.Proto2; +using NUnit.Framework; + +using static Google.Protobuf.TestProtos.Proto2.UnittestExtensions; + +namespace Google.Protobuf +{ + public class ExtensionSetTest + { + [Test] + public void EmptyExtensionSet() + { + ExtensionSet<TestAllExtensions> extensions = new ExtensionSet<TestAllExtensions>(); + Assert.AreEqual(0, extensions.CalculateSize()); + } + + [Test] + public void MergeExtensionSet() + { + ExtensionSet<TestAllExtensions> extensions = null; + ExtensionSet.Set(ref extensions, OptionalBoolExtension, true); + + ExtensionSet<TestAllExtensions> other = null; + + Assert.IsFalse(ExtensionSet.Has(ref other, OptionalBoolExtension)); + ExtensionSet.MergeFrom(ref other, extensions); + Assert.IsTrue(ExtensionSet.Has(ref other, OptionalBoolExtension)); + } + + [Test] + public void TestMergeCodedInput() + { + var message = new TestAllExtensions(); + message.SetExtension(OptionalBoolExtension, true); + var serialized = message.ToByteArray(); + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertReadingMessage( + TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { OptionalBoolExtension }), + serialized, + other => + { + Assert.AreEqual(message, other); + Assert.AreEqual(message.CalculateSize(), other.CalculateSize()); + }); + } + + [Test] + public void TestMergeMessage() + { + var message = new TestAllExtensions(); + message.SetExtension(OptionalBoolExtension, true); + + var other = new TestAllExtensions(); + + Assert.AreNotEqual(message, other); + Assert.AreNotEqual(message.CalculateSize(), other.CalculateSize()); + + other.MergeFrom(message); + + Assert.AreEqual(message, other); + Assert.AreEqual(message.CalculateSize(), other.CalculateSize()); + } + + [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 GetSingle() + { + var extensionValue = new TestAllTypes.Types.NestedMessage() { Bb = 42 }; + var untypedExtension = new Extension<TestAllExtensions, object>(OptionalNestedMessageExtension.FieldNumber, codec: null); + var wrongTypedExtension = new Extension<TestAllExtensions, TestAllTypes>(OptionalNestedMessageExtension.FieldNumber, codec: null); + + var message = new TestAllExtensions(); + + var value1 = message.GetExtension(untypedExtension); + Assert.IsNull(value1); + + message.SetExtension(OptionalNestedMessageExtension, extensionValue); + var value2 = message.GetExtension(untypedExtension); + Assert.IsNotNull(value2); + + var valueBytes = ((IMessage)value2).ToByteArray(); + var parsedValue = TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser.ParseFrom(valueBytes); + Assert.AreEqual(extensionValue, parsedValue); + + var ex = Assert.Throws<InvalidOperationException>(() => message.GetExtension(wrongTypedExtension)); + + var expectedMessage = "The stored extension value has a type of 'Google.Protobuf.TestProtos.Proto2.TestAllTypes+Types+NestedMessage, Google.Protobuf.Test.TestProtos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604'. " + + "This a different from the requested type of 'Google.Protobuf.TestProtos.Proto2.TestAllTypes, Google.Protobuf.Test.TestProtos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604'."; + Assert.AreEqual(expectedMessage, ex.Message); + } + + [Test] + public void GetRepeated() + { + var extensionValue = new TestAllTypes.Types.NestedMessage() { Bb = 42 }; + var untypedExtension = new Extension<TestAllExtensions, IList>(RepeatedNestedMessageExtension.FieldNumber, codec: null); + var wrongTypedExtension = new RepeatedExtension<TestAllExtensions, TestAllTypes>(RepeatedNestedMessageExtension.FieldNumber, codec: null); + + var message = new TestAllExtensions(); + + var value1 = message.GetExtension(untypedExtension); + Assert.IsNull(value1); + + var repeatedField = message.GetOrInitializeExtension<TestAllTypes.Types.NestedMessage>(RepeatedNestedMessageExtension); + repeatedField.Add(extensionValue); + + var value2 = message.GetExtension(untypedExtension); + Assert.IsNotNull(value2); + Assert.AreEqual(1, value2.Count); + + var valueBytes = ((IMessage)value2[0]).ToByteArray(); + var parsedValue = TestProtos.Proto2.TestAllTypes.Types.NestedMessage.Parser.ParseFrom(valueBytes); + Assert.AreEqual(extensionValue, parsedValue); + + var ex = Assert.Throws<InvalidOperationException>(() => message.GetExtension(wrongTypedExtension)); + + var expectedMessage = "The stored extension value has a type of 'Google.Protobuf.TestProtos.Proto2.TestAllTypes+Types+NestedMessage, Google.Protobuf.Test.TestProtos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604'. " + + "This a different from the requested type of 'Google.Protobuf.TestProtos.Proto2.TestAllTypes, Google.Protobuf.Test.TestProtos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604'."; + Assert.AreEqual(expectedMessage, ex.Message); + } + + [Test] + public void TestEquals() + { + var message = new TestAllExtensions(); + message.SetExtension(OptionalBoolExtension, true); + + var other = new TestAllExtensions(); + + Assert.AreNotEqual(message, other); + Assert.AreNotEqual(message.CalculateSize(), other.CalculateSize()); + + other.SetExtension(OptionalBoolExtension, true); + + Assert.AreEqual(message, other); + Assert.AreEqual(message.CalculateSize(), other.CalculateSize()); + } + + [Test] + public void TestHashCode() + { + var message = new TestAllExtensions(); + var hashCode = message.GetHashCode(); + + message.SetExtension(OptionalBoolExtension, true); + + Assert.AreNotEqual(hashCode, message.GetHashCode()); + } + + [Test] + public void TestClone() + { + var message = new TestAllExtensions(); + message.SetExtension(OptionalBoolExtension, true); + + var other = message.Clone(); + + Assert.AreEqual(message, other); + Assert.AreEqual(message.CalculateSize(), other.CalculateSize()); + } + + [Test] + public void TestDefaultValueRoundTrip() + { + var message = new TestAllExtensions(); + message.SetExtension(OptionalBoolExtension, false); + Assert.IsFalse(message.GetExtension(OptionalBoolExtension)); + Assert.IsTrue(message.HasExtension(OptionalBoolExtension)); + + var bytes = message.ToByteArray(); + var registry = new ExtensionRegistry { OptionalBoolExtension }; + var parsed = TestAllExtensions.Parser.WithExtensionRegistry(registry).ParseFrom(bytes); + Assert.IsFalse(parsed.GetExtension(OptionalBoolExtension)); + Assert.IsTrue(parsed.HasExtension(OptionalBoolExtension)); + } + } +}
diff --git a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs index 894d914..fa5f927 100644 --- a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs +++ b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.Proto2.cs
@@ -1,397 +1,397 @@ -using Google.Protobuf.TestProtos.Proto2; -using Proto2 = Google.Protobuf.TestProtos.Proto2; -using NUnit.Framework; - -using static Google.Protobuf.TestProtos.Proto2.UnittestExtensions; - -namespace Google.Protobuf -{ - /// <summary> - /// Tests around the generated TestAllTypes message in unittest.proto - /// </summary> - public partial class GeneratedMessageTest - { - [Test] - public void DefaultProto2Values() - { - var message = new TestAllTypes(); - Assert.AreEqual(false, message.OptionalBool); - Assert.AreEqual(ByteString.Empty, message.OptionalBytes); - Assert.AreEqual(0.0, message.OptionalDouble); - Assert.AreEqual(0, message.OptionalFixed32); - Assert.AreEqual(0L, message.OptionalFixed64); - Assert.AreEqual(0.0f, message.OptionalFloat); - Assert.AreEqual(ForeignEnum.ForeignFoo, message.OptionalForeignEnum); - Assert.IsNull(message.OptionalForeignMessage); - Assert.AreEqual(ImportEnum.ImportFoo, message.OptionalImportEnum); - Assert.IsNull(message.OptionalImportMessage); - Assert.AreEqual(0, message.OptionalInt32); - Assert.AreEqual(0L, message.OptionalInt64); - Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Foo, message.OptionalNestedEnum); - Assert.IsNull(message.OptionalNestedMessage); - Assert.IsNull(message.OptionalPublicImportMessage); - Assert.AreEqual(0, message.OptionalSfixed32); - Assert.AreEqual(0L, message.OptionalSfixed64); - Assert.AreEqual(0, message.OptionalSint32); - Assert.AreEqual(0L, message.OptionalSint64); - Assert.AreEqual("", message.OptionalString); - Assert.AreEqual(0U, message.OptionalUint32); - Assert.AreEqual(0UL, message.OptionalUint64); - - // Repeated fields - Assert.AreEqual(0, message.RepeatedBool.Count); - Assert.AreEqual(0, message.RepeatedBytes.Count); - Assert.AreEqual(0, message.RepeatedDouble.Count); - Assert.AreEqual(0, message.RepeatedFixed32.Count); - Assert.AreEqual(0, message.RepeatedFixed64.Count); - Assert.AreEqual(0, message.RepeatedFloat.Count); - Assert.AreEqual(0, message.RepeatedForeignEnum.Count); - Assert.AreEqual(0, message.RepeatedForeignMessage.Count); - Assert.AreEqual(0, message.RepeatedImportEnum.Count); - Assert.AreEqual(0, message.RepeatedImportMessage.Count); - Assert.AreEqual(0, message.RepeatedNestedEnum.Count); - Assert.AreEqual(0, message.RepeatedNestedMessage.Count); - Assert.AreEqual(0, message.RepeatedSfixed32.Count); - Assert.AreEqual(0, message.RepeatedSfixed64.Count); - Assert.AreEqual(0, message.RepeatedSint32.Count); - Assert.AreEqual(0, message.RepeatedSint64.Count); - Assert.AreEqual(0, message.RepeatedString.Count); - Assert.AreEqual(0, message.RepeatedUint32.Count); - Assert.AreEqual(0, message.RepeatedUint64.Count); - - // Oneof fields - Assert.AreEqual(Proto2.TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - - Assert.AreEqual(true, message.DefaultBool); - Assert.AreEqual(ByteString.CopyFromUtf8("world"), message.DefaultBytes); - Assert.AreEqual("123", message.DefaultCord); - Assert.AreEqual(52e3, message.DefaultDouble); - Assert.AreEqual(47, message.DefaultFixed32); - Assert.AreEqual(48, message.DefaultFixed64); - Assert.AreEqual(51.5, message.DefaultFloat); - Assert.AreEqual(ForeignEnum.ForeignBar, message.DefaultForeignEnum); - Assert.AreEqual(ImportEnum.ImportBar, message.DefaultImportEnum); - Assert.AreEqual(41, message.DefaultInt32); - Assert.AreEqual(42, message.DefaultInt64); - Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Bar, message.DefaultNestedEnum); - Assert.AreEqual(49, message.DefaultSfixed32); - Assert.AreEqual(-50, message.DefaultSfixed64); - Assert.AreEqual(-45, message.DefaultSint32); - Assert.AreEqual(46, message.DefaultSint64); - Assert.AreEqual("hello", message.DefaultString); - Assert.AreEqual("abc", message.DefaultStringPiece); - Assert.AreEqual(43, message.DefaultUint32); - Assert.AreEqual(44, message.DefaultUint64); - - Assert.False(message.HasDefaultBool); - Assert.False(message.HasDefaultBytes); - Assert.False(message.HasDefaultCord); - Assert.False(message.HasDefaultDouble); - Assert.False(message.HasDefaultFixed32); - Assert.False(message.HasDefaultFixed64); - Assert.False(message.HasDefaultFloat); - Assert.False(message.HasDefaultForeignEnum); - Assert.False(message.HasDefaultImportEnum); - Assert.False(message.HasDefaultInt32); - Assert.False(message.HasDefaultInt64); - Assert.False(message.HasDefaultNestedEnum); - Assert.False(message.HasDefaultSfixed32); - Assert.False(message.HasDefaultSfixed64); - Assert.False(message.HasDefaultSint32); - Assert.False(message.HasDefaultSint64); - Assert.False(message.HasDefaultString); - Assert.False(message.HasDefaultStringPiece); - Assert.False(message.HasDefaultUint32); - Assert.False(message.HasDefaultUint64); - } - - [Test] - public void DefaultExtensionValues() - { - var message = new TestAllExtensions(); - Assert.AreEqual(false, message.GetExtension(OptionalBoolExtension)); - Assert.AreEqual(ByteString.Empty, message.GetExtension(OptionalBytesExtension)); - Assert.AreEqual(0.0, message.GetExtension(OptionalDoubleExtension)); - Assert.AreEqual(0, message.GetExtension(OptionalFixed32Extension)); - Assert.AreEqual(0L, message.GetExtension(OptionalFixed64Extension)); - Assert.AreEqual(0.0f, message.GetExtension(OptionalFloatExtension)); - Assert.AreEqual(ForeignEnum.ForeignFoo, message.GetExtension(OptionalForeignEnumExtension)); - Assert.IsNull(message.GetExtension(OptionalForeignMessageExtension)); - Assert.AreEqual(ImportEnum.ImportFoo, message.GetExtension(OptionalImportEnumExtension)); - Assert.IsNull(message.GetExtension(OptionalImportMessageExtension)); - Assert.AreEqual(0, message.GetExtension(OptionalInt32Extension)); - Assert.AreEqual(0L, message.GetExtension(OptionalInt64Extension)); - Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Foo, message.GetExtension(OptionalNestedEnumExtension)); - Assert.IsNull(message.GetExtension(OptionalNestedMessageExtension)); - Assert.IsNull(message.GetExtension(OptionalPublicImportMessageExtension)); - Assert.AreEqual(0, message.GetExtension(OptionalSfixed32Extension)); - Assert.AreEqual(0L, message.GetExtension(OptionalSfixed64Extension)); - Assert.AreEqual(0, message.GetExtension(OptionalSint32Extension)); - Assert.AreEqual(0L, message.GetExtension(OptionalSint64Extension)); - Assert.AreEqual("", message.GetExtension(OptionalStringExtension)); - Assert.AreEqual(0U, message.GetExtension(OptionalUint32Extension)); - Assert.AreEqual(0UL, message.GetExtension(OptionalUint64Extension)); - - // Repeated fields - Assert.IsNull(message.GetExtension(RepeatedBoolExtension)); - Assert.IsNull(message.GetExtension(RepeatedBytesExtension)); - Assert.IsNull(message.GetExtension(RepeatedDoubleExtension)); - Assert.IsNull(message.GetExtension(RepeatedFixed32Extension)); - Assert.IsNull(message.GetExtension(RepeatedFixed64Extension)); - Assert.IsNull(message.GetExtension(RepeatedFloatExtension)); - Assert.IsNull(message.GetExtension(RepeatedForeignEnumExtension)); - Assert.IsNull(message.GetExtension(RepeatedForeignMessageExtension)); - Assert.IsNull(message.GetExtension(RepeatedImportEnumExtension)); - Assert.IsNull(message.GetExtension(RepeatedImportMessageExtension)); - Assert.IsNull(message.GetExtension(RepeatedNestedEnumExtension)); - Assert.IsNull(message.GetExtension(RepeatedNestedMessageExtension)); - Assert.IsNull(message.GetExtension(RepeatedSfixed32Extension)); - Assert.IsNull(message.GetExtension(RepeatedSfixed64Extension)); - Assert.IsNull(message.GetExtension(RepeatedSint32Extension)); - Assert.IsNull(message.GetExtension(RepeatedSint64Extension)); - Assert.IsNull(message.GetExtension(RepeatedStringExtension)); - Assert.IsNull(message.GetExtension(RepeatedUint32Extension)); - Assert.IsNull(message.GetExtension(RepeatedUint64Extension)); - - // Oneof fields - Assert.AreEqual(0, message.GetExtension(OneofUint32Extension)); - Assert.AreEqual("", message.GetExtension(OneofStringExtension)); - Assert.AreEqual(ByteString.Empty, message.GetExtension(OneofBytesExtension)); - Assert.IsNull(message.GetExtension(OneofNestedMessageExtension)); - - Assert.AreEqual(true, message.GetExtension(DefaultBoolExtension)); - Assert.AreEqual(ByteString.CopyFromUtf8("world"), message.GetExtension(DefaultBytesExtension)); - Assert.AreEqual("123", message.GetExtension(DefaultCordExtension)); - Assert.AreEqual(52e3, message.GetExtension(DefaultDoubleExtension)); - Assert.AreEqual(47, message.GetExtension(DefaultFixed32Extension)); - Assert.AreEqual(48, message.GetExtension(DefaultFixed64Extension)); - Assert.AreEqual(51.5, message.GetExtension(DefaultFloatExtension)); - Assert.AreEqual(ForeignEnum.ForeignBar, message.GetExtension(DefaultForeignEnumExtension)); - Assert.AreEqual(ImportEnum.ImportBar, message.GetExtension(DefaultImportEnumExtension)); - Assert.AreEqual(41, message.GetExtension(DefaultInt32Extension)); - Assert.AreEqual(42, message.GetExtension(DefaultInt64Extension)); - Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Bar, message.GetExtension(DefaultNestedEnumExtension)); - Assert.AreEqual(49, message.GetExtension(DefaultSfixed32Extension)); - Assert.AreEqual(-50, message.GetExtension(DefaultSfixed64Extension)); - Assert.AreEqual(-45, message.GetExtension(DefaultSint32Extension)); - Assert.AreEqual(46, message.GetExtension(DefaultSint64Extension)); - Assert.AreEqual("hello", message.GetExtension(DefaultStringExtension)); - Assert.AreEqual("abc", message.GetExtension(DefaultStringPieceExtension)); - Assert.AreEqual(43, message.GetExtension(DefaultUint32Extension)); - Assert.AreEqual(44, message.GetExtension(DefaultUint64Extension)); - - Assert.False(message.HasExtension(DefaultBoolExtension)); - Assert.False(message.HasExtension(DefaultBytesExtension)); - Assert.False(message.HasExtension(DefaultCordExtension)); - Assert.False(message.HasExtension(DefaultDoubleExtension)); - Assert.False(message.HasExtension(DefaultFixed32Extension)); - Assert.False(message.HasExtension(DefaultFixed64Extension)); - Assert.False(message.HasExtension(DefaultFloatExtension)); - Assert.False(message.HasExtension(DefaultForeignEnumExtension)); - Assert.False(message.HasExtension(DefaultImportEnumExtension)); - Assert.False(message.HasExtension(DefaultInt32Extension)); - Assert.False(message.HasExtension(DefaultInt64Extension)); - Assert.False(message.HasExtension(DefaultNestedEnumExtension)); - Assert.False(message.HasExtension(DefaultSfixed32Extension)); - Assert.False(message.HasExtension(DefaultSfixed64Extension)); - Assert.False(message.HasExtension(DefaultSint32Extension)); - Assert.False(message.HasExtension(DefaultSint64Extension)); - Assert.False(message.HasExtension(DefaultStringExtension)); - Assert.False(message.HasExtension(DefaultStringPieceExtension)); - Assert.False(message.HasExtension(DefaultUint32Extension)); - Assert.False(message.HasExtension(DefaultUint64Extension)); - } - - [Test] - public void FieldPresence() - { - var message = new TestAllTypes(); - - Assert.False(message.HasOptionalBool); - Assert.False(message.OptionalBool); - - message.OptionalBool = true; - - Assert.True(message.HasOptionalBool); - Assert.True(message.OptionalBool); - - message.OptionalBool = false; - - Assert.True(message.HasOptionalBool); - Assert.False(message.OptionalBool); - - message.ClearOptionalBool(); - - Assert.False(message.HasOptionalBool); - Assert.False(message.OptionalBool); - - Assert.False(message.HasDefaultBool); - Assert.True(message.DefaultBool); - - message.DefaultBool = false; - - Assert.True(message.HasDefaultBool); - Assert.False(message.DefaultBool); - - message.DefaultBool = true; - - Assert.True(message.HasDefaultBool); - Assert.True(message.DefaultBool); - - message.ClearDefaultBool(); - - Assert.False(message.HasDefaultBool); - Assert.True(message.DefaultBool); - } - - [Test] - public void RequiredFields() - { - var message = new TestRequired(); - Assert.False(message.IsInitialized()); - - message.A = 1; - message.B = 2; - message.C = 3; - - 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() - { - var message = new TestAllExtensions(); - Assert.True(message.IsInitialized()); - - message.SetExtension(TestRequired.Extensions.Single, new TestRequired()); - - Assert.False(message.IsInitialized()); - - var extensionMessage = message.GetExtension(TestRequired.Extensions.Single); - extensionMessage.A = 1; - extensionMessage.B = 2; - extensionMessage.C = 3; - - Assert.True(message.IsInitialized()); - - message.GetOrInitializeExtension(TestRequired.Extensions.Multi); - - Assert.True(message.IsInitialized()); - - message.GetExtension(TestRequired.Extensions.Multi).Add(new TestRequired()); - - Assert.False(message.IsInitialized()); - - extensionMessage = message.GetExtension(TestRequired.Extensions.Multi)[0]; - extensionMessage.A = 1; - extensionMessage.B = 2; - extensionMessage.C = 3; - - Assert.True(message.IsInitialized()); - - message.SetExtension(UnittestExtensions.OptionalBoolExtension, true); - - Assert.True(message.IsInitialized()); - - message.GetOrInitializeExtension(UnittestExtensions.RepeatedBoolExtension).Add(true); - - Assert.True(message.IsInitialized()); - } - - [Test] - public void RequiredFieldInNestedMessageMapValue() - { - var message = new TestRequiredMap(); - message.Foo.Add(0, new TestRequiredMap.Types.NestedMessage()); - - Assert.False(message.IsInitialized()); - - message.Foo[0].RequiredInt32 = 12; - - Assert.True(message.IsInitialized()); - } - - [Test] - public void RoundTrip_Groups() - { - var message = new TestAllTypes - { - OptionalGroup = new TestAllTypes.Types.OptionalGroup - { - A = 10 - }, - RepeatedGroup = - { - new TestAllTypes.Types.RepeatedGroup { A = 10 }, - new TestAllTypes.Types.RepeatedGroup { A = 20 }, - new TestAllTypes.Types.RepeatedGroup { A = 30 } - } - }; - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip(Proto2.TestAllTypes.Parser, message); - } - - [Test] - public void RoundTrip_ExtensionGroups() - { - var message = new TestAllExtensions(); - message.SetExtension(UnittestExtensions.OptionalGroupExtension, new OptionalGroup_extension { A = 10 }); - message.GetOrInitializeExtension(UnittestExtensions.RepeatedGroupExtension).AddRange(new[] - { - new RepeatedGroup_extension { A = 10 }, - new RepeatedGroup_extension { A = 20 }, - new RepeatedGroup_extension { A = 30 } - }); - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip( - TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { UnittestExtensions.OptionalGroupExtension, UnittestExtensions.RepeatedGroupExtension }), - message); - } - - [Test] - public void RoundTrip_NestedExtensionGroup() - { - var message = new TestGroupExtension(); - message.SetExtension(TestNestedExtension.Extensions.OptionalGroupExtension, new TestNestedExtension.Types.OptionalGroup_extension { A = 10 }); - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip( - TestGroupExtension.Parser.WithExtensionRegistry(new ExtensionRegistry() { TestNestedExtension.Extensions.OptionalGroupExtension }), - message); - } - - [Test] - public void RoundTrip_ParseUsingCodedInput() - { - var message = new TestAllExtensions(); - message.SetExtension(UnittestExtensions.OptionalBoolExtension, true); - byte[] bytes = message.ToByteArray(); - using (CodedInputStream input = new CodedInputStream(bytes)) - { - var parsed = TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { UnittestExtensions.OptionalBoolExtension }).ParseFrom(input); - Assert.AreEqual(message, parsed); - } - } - } -} +using Google.Protobuf.TestProtos.Proto2; +using Proto2 = Google.Protobuf.TestProtos.Proto2; +using NUnit.Framework; + +using static Google.Protobuf.TestProtos.Proto2.UnittestExtensions; + +namespace Google.Protobuf +{ + /// <summary> + /// Tests around the generated TestAllTypes message in unittest.proto + /// </summary> + public partial class GeneratedMessageTest + { + [Test] + public void DefaultProto2Values() + { + var message = new TestAllTypes(); + Assert.AreEqual(false, message.OptionalBool); + Assert.AreEqual(ByteString.Empty, message.OptionalBytes); + Assert.AreEqual(0.0, message.OptionalDouble); + Assert.AreEqual(0, message.OptionalFixed32); + Assert.AreEqual(0L, message.OptionalFixed64); + Assert.AreEqual(0.0f, message.OptionalFloat); + Assert.AreEqual(ForeignEnum.ForeignFoo, message.OptionalForeignEnum); + Assert.IsNull(message.OptionalForeignMessage); + Assert.AreEqual(ImportEnum.ImportFoo, message.OptionalImportEnum); + Assert.IsNull(message.OptionalImportMessage); + Assert.AreEqual(0, message.OptionalInt32); + Assert.AreEqual(0L, message.OptionalInt64); + Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Foo, message.OptionalNestedEnum); + Assert.IsNull(message.OptionalNestedMessage); + Assert.IsNull(message.OptionalPublicImportMessage); + Assert.AreEqual(0, message.OptionalSfixed32); + Assert.AreEqual(0L, message.OptionalSfixed64); + Assert.AreEqual(0, message.OptionalSint32); + Assert.AreEqual(0L, message.OptionalSint64); + Assert.AreEqual("", message.OptionalString); + Assert.AreEqual(0U, message.OptionalUint32); + Assert.AreEqual(0UL, message.OptionalUint64); + + // Repeated fields + Assert.AreEqual(0, message.RepeatedBool.Count); + Assert.AreEqual(0, message.RepeatedBytes.Count); + Assert.AreEqual(0, message.RepeatedDouble.Count); + Assert.AreEqual(0, message.RepeatedFixed32.Count); + Assert.AreEqual(0, message.RepeatedFixed64.Count); + Assert.AreEqual(0, message.RepeatedFloat.Count); + Assert.AreEqual(0, message.RepeatedForeignEnum.Count); + Assert.AreEqual(0, message.RepeatedForeignMessage.Count); + Assert.AreEqual(0, message.RepeatedImportEnum.Count); + Assert.AreEqual(0, message.RepeatedImportMessage.Count); + Assert.AreEqual(0, message.RepeatedNestedEnum.Count); + Assert.AreEqual(0, message.RepeatedNestedMessage.Count); + Assert.AreEqual(0, message.RepeatedSfixed32.Count); + Assert.AreEqual(0, message.RepeatedSfixed64.Count); + Assert.AreEqual(0, message.RepeatedSint32.Count); + Assert.AreEqual(0, message.RepeatedSint64.Count); + Assert.AreEqual(0, message.RepeatedString.Count); + Assert.AreEqual(0, message.RepeatedUint32.Count); + Assert.AreEqual(0, message.RepeatedUint64.Count); + + // Oneof fields + Assert.AreEqual(Proto2.TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + + Assert.AreEqual(true, message.DefaultBool); + Assert.AreEqual(ByteString.CopyFromUtf8("world"), message.DefaultBytes); + Assert.AreEqual("123", message.DefaultCord); + Assert.AreEqual(52e3, message.DefaultDouble); + Assert.AreEqual(47, message.DefaultFixed32); + Assert.AreEqual(48, message.DefaultFixed64); + Assert.AreEqual(51.5, message.DefaultFloat); + Assert.AreEqual(ForeignEnum.ForeignBar, message.DefaultForeignEnum); + Assert.AreEqual(ImportEnum.ImportBar, message.DefaultImportEnum); + Assert.AreEqual(41, message.DefaultInt32); + Assert.AreEqual(42, message.DefaultInt64); + Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Bar, message.DefaultNestedEnum); + Assert.AreEqual(49, message.DefaultSfixed32); + Assert.AreEqual(-50, message.DefaultSfixed64); + Assert.AreEqual(-45, message.DefaultSint32); + Assert.AreEqual(46, message.DefaultSint64); + Assert.AreEqual("hello", message.DefaultString); + Assert.AreEqual("abc", message.DefaultStringPiece); + Assert.AreEqual(43, message.DefaultUint32); + Assert.AreEqual(44, message.DefaultUint64); + + Assert.False(message.HasDefaultBool); + Assert.False(message.HasDefaultBytes); + Assert.False(message.HasDefaultCord); + Assert.False(message.HasDefaultDouble); + Assert.False(message.HasDefaultFixed32); + Assert.False(message.HasDefaultFixed64); + Assert.False(message.HasDefaultFloat); + Assert.False(message.HasDefaultForeignEnum); + Assert.False(message.HasDefaultImportEnum); + Assert.False(message.HasDefaultInt32); + Assert.False(message.HasDefaultInt64); + Assert.False(message.HasDefaultNestedEnum); + Assert.False(message.HasDefaultSfixed32); + Assert.False(message.HasDefaultSfixed64); + Assert.False(message.HasDefaultSint32); + Assert.False(message.HasDefaultSint64); + Assert.False(message.HasDefaultString); + Assert.False(message.HasDefaultStringPiece); + Assert.False(message.HasDefaultUint32); + Assert.False(message.HasDefaultUint64); + } + + [Test] + public void DefaultExtensionValues() + { + var message = new TestAllExtensions(); + Assert.AreEqual(false, message.GetExtension(OptionalBoolExtension)); + Assert.AreEqual(ByteString.Empty, message.GetExtension(OptionalBytesExtension)); + Assert.AreEqual(0.0, message.GetExtension(OptionalDoubleExtension)); + Assert.AreEqual(0, message.GetExtension(OptionalFixed32Extension)); + Assert.AreEqual(0L, message.GetExtension(OptionalFixed64Extension)); + Assert.AreEqual(0.0f, message.GetExtension(OptionalFloatExtension)); + Assert.AreEqual(ForeignEnum.ForeignFoo, message.GetExtension(OptionalForeignEnumExtension)); + Assert.IsNull(message.GetExtension(OptionalForeignMessageExtension)); + Assert.AreEqual(ImportEnum.ImportFoo, message.GetExtension(OptionalImportEnumExtension)); + Assert.IsNull(message.GetExtension(OptionalImportMessageExtension)); + Assert.AreEqual(0, message.GetExtension(OptionalInt32Extension)); + Assert.AreEqual(0L, message.GetExtension(OptionalInt64Extension)); + Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Foo, message.GetExtension(OptionalNestedEnumExtension)); + Assert.IsNull(message.GetExtension(OptionalNestedMessageExtension)); + Assert.IsNull(message.GetExtension(OptionalPublicImportMessageExtension)); + Assert.AreEqual(0, message.GetExtension(OptionalSfixed32Extension)); + Assert.AreEqual(0L, message.GetExtension(OptionalSfixed64Extension)); + Assert.AreEqual(0, message.GetExtension(OptionalSint32Extension)); + Assert.AreEqual(0L, message.GetExtension(OptionalSint64Extension)); + Assert.AreEqual("", message.GetExtension(OptionalStringExtension)); + Assert.AreEqual(0U, message.GetExtension(OptionalUint32Extension)); + Assert.AreEqual(0UL, message.GetExtension(OptionalUint64Extension)); + + // Repeated fields + Assert.IsNull(message.GetExtension(RepeatedBoolExtension)); + Assert.IsNull(message.GetExtension(RepeatedBytesExtension)); + Assert.IsNull(message.GetExtension(RepeatedDoubleExtension)); + Assert.IsNull(message.GetExtension(RepeatedFixed32Extension)); + Assert.IsNull(message.GetExtension(RepeatedFixed64Extension)); + Assert.IsNull(message.GetExtension(RepeatedFloatExtension)); + Assert.IsNull(message.GetExtension(RepeatedForeignEnumExtension)); + Assert.IsNull(message.GetExtension(RepeatedForeignMessageExtension)); + Assert.IsNull(message.GetExtension(RepeatedImportEnumExtension)); + Assert.IsNull(message.GetExtension(RepeatedImportMessageExtension)); + Assert.IsNull(message.GetExtension(RepeatedNestedEnumExtension)); + Assert.IsNull(message.GetExtension(RepeatedNestedMessageExtension)); + Assert.IsNull(message.GetExtension(RepeatedSfixed32Extension)); + Assert.IsNull(message.GetExtension(RepeatedSfixed64Extension)); + Assert.IsNull(message.GetExtension(RepeatedSint32Extension)); + Assert.IsNull(message.GetExtension(RepeatedSint64Extension)); + Assert.IsNull(message.GetExtension(RepeatedStringExtension)); + Assert.IsNull(message.GetExtension(RepeatedUint32Extension)); + Assert.IsNull(message.GetExtension(RepeatedUint64Extension)); + + // Oneof fields + Assert.AreEqual(0, message.GetExtension(OneofUint32Extension)); + Assert.AreEqual("", message.GetExtension(OneofStringExtension)); + Assert.AreEqual(ByteString.Empty, message.GetExtension(OneofBytesExtension)); + Assert.IsNull(message.GetExtension(OneofNestedMessageExtension)); + + Assert.AreEqual(true, message.GetExtension(DefaultBoolExtension)); + Assert.AreEqual(ByteString.CopyFromUtf8("world"), message.GetExtension(DefaultBytesExtension)); + Assert.AreEqual("123", message.GetExtension(DefaultCordExtension)); + Assert.AreEqual(52e3, message.GetExtension(DefaultDoubleExtension)); + Assert.AreEqual(47, message.GetExtension(DefaultFixed32Extension)); + Assert.AreEqual(48, message.GetExtension(DefaultFixed64Extension)); + Assert.AreEqual(51.5, message.GetExtension(DefaultFloatExtension)); + Assert.AreEqual(ForeignEnum.ForeignBar, message.GetExtension(DefaultForeignEnumExtension)); + Assert.AreEqual(ImportEnum.ImportBar, message.GetExtension(DefaultImportEnumExtension)); + Assert.AreEqual(41, message.GetExtension(DefaultInt32Extension)); + Assert.AreEqual(42, message.GetExtension(DefaultInt64Extension)); + Assert.AreEqual(Proto2.TestAllTypes.Types.NestedEnum.Bar, message.GetExtension(DefaultNestedEnumExtension)); + Assert.AreEqual(49, message.GetExtension(DefaultSfixed32Extension)); + Assert.AreEqual(-50, message.GetExtension(DefaultSfixed64Extension)); + Assert.AreEqual(-45, message.GetExtension(DefaultSint32Extension)); + Assert.AreEqual(46, message.GetExtension(DefaultSint64Extension)); + Assert.AreEqual("hello", message.GetExtension(DefaultStringExtension)); + Assert.AreEqual("abc", message.GetExtension(DefaultStringPieceExtension)); + Assert.AreEqual(43, message.GetExtension(DefaultUint32Extension)); + Assert.AreEqual(44, message.GetExtension(DefaultUint64Extension)); + + Assert.False(message.HasExtension(DefaultBoolExtension)); + Assert.False(message.HasExtension(DefaultBytesExtension)); + Assert.False(message.HasExtension(DefaultCordExtension)); + Assert.False(message.HasExtension(DefaultDoubleExtension)); + Assert.False(message.HasExtension(DefaultFixed32Extension)); + Assert.False(message.HasExtension(DefaultFixed64Extension)); + Assert.False(message.HasExtension(DefaultFloatExtension)); + Assert.False(message.HasExtension(DefaultForeignEnumExtension)); + Assert.False(message.HasExtension(DefaultImportEnumExtension)); + Assert.False(message.HasExtension(DefaultInt32Extension)); + Assert.False(message.HasExtension(DefaultInt64Extension)); + Assert.False(message.HasExtension(DefaultNestedEnumExtension)); + Assert.False(message.HasExtension(DefaultSfixed32Extension)); + Assert.False(message.HasExtension(DefaultSfixed64Extension)); + Assert.False(message.HasExtension(DefaultSint32Extension)); + Assert.False(message.HasExtension(DefaultSint64Extension)); + Assert.False(message.HasExtension(DefaultStringExtension)); + Assert.False(message.HasExtension(DefaultStringPieceExtension)); + Assert.False(message.HasExtension(DefaultUint32Extension)); + Assert.False(message.HasExtension(DefaultUint64Extension)); + } + + [Test] + public void FieldPresence() + { + var message = new TestAllTypes(); + + Assert.False(message.HasOptionalBool); + Assert.False(message.OptionalBool); + + message.OptionalBool = true; + + Assert.True(message.HasOptionalBool); + Assert.True(message.OptionalBool); + + message.OptionalBool = false; + + Assert.True(message.HasOptionalBool); + Assert.False(message.OptionalBool); + + message.ClearOptionalBool(); + + Assert.False(message.HasOptionalBool); + Assert.False(message.OptionalBool); + + Assert.False(message.HasDefaultBool); + Assert.True(message.DefaultBool); + + message.DefaultBool = false; + + Assert.True(message.HasDefaultBool); + Assert.False(message.DefaultBool); + + message.DefaultBool = true; + + Assert.True(message.HasDefaultBool); + Assert.True(message.DefaultBool); + + message.ClearDefaultBool(); + + Assert.False(message.HasDefaultBool); + Assert.True(message.DefaultBool); + } + + [Test] + public void RequiredFields() + { + var message = new TestRequired(); + Assert.False(message.IsInitialized()); + + message.A = 1; + message.B = 2; + message.C = 3; + + 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() + { + var message = new TestAllExtensions(); + Assert.True(message.IsInitialized()); + + message.SetExtension(TestRequired.Extensions.Single, new TestRequired()); + + Assert.False(message.IsInitialized()); + + var extensionMessage = message.GetExtension(TestRequired.Extensions.Single); + extensionMessage.A = 1; + extensionMessage.B = 2; + extensionMessage.C = 3; + + Assert.True(message.IsInitialized()); + + message.GetOrInitializeExtension(TestRequired.Extensions.Multi); + + Assert.True(message.IsInitialized()); + + message.GetExtension(TestRequired.Extensions.Multi).Add(new TestRequired()); + + Assert.False(message.IsInitialized()); + + extensionMessage = message.GetExtension(TestRequired.Extensions.Multi)[0]; + extensionMessage.A = 1; + extensionMessage.B = 2; + extensionMessage.C = 3; + + Assert.True(message.IsInitialized()); + + message.SetExtension(UnittestExtensions.OptionalBoolExtension, true); + + Assert.True(message.IsInitialized()); + + message.GetOrInitializeExtension(UnittestExtensions.RepeatedBoolExtension).Add(true); + + Assert.True(message.IsInitialized()); + } + + [Test] + public void RequiredFieldInNestedMessageMapValue() + { + var message = new TestRequiredMap(); + message.Foo.Add(0, new TestRequiredMap.Types.NestedMessage()); + + Assert.False(message.IsInitialized()); + + message.Foo[0].RequiredInt32 = 12; + + Assert.True(message.IsInitialized()); + } + + [Test] + public void RoundTrip_Groups() + { + var message = new TestAllTypes + { + OptionalGroup = new TestAllTypes.Types.OptionalGroup + { + A = 10 + }, + RepeatedGroup = + { + new TestAllTypes.Types.RepeatedGroup { A = 10 }, + new TestAllTypes.Types.RepeatedGroup { A = 20 }, + new TestAllTypes.Types.RepeatedGroup { A = 30 } + } + }; + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(Proto2.TestAllTypes.Parser, message); + } + + [Test] + public void RoundTrip_ExtensionGroups() + { + var message = new TestAllExtensions(); + message.SetExtension(UnittestExtensions.OptionalGroupExtension, new OptionalGroup_extension { A = 10 }); + message.GetOrInitializeExtension(UnittestExtensions.RepeatedGroupExtension).AddRange(new[] + { + new RepeatedGroup_extension { A = 10 }, + new RepeatedGroup_extension { A = 20 }, + new RepeatedGroup_extension { A = 30 } + }); + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip( + TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { UnittestExtensions.OptionalGroupExtension, UnittestExtensions.RepeatedGroupExtension }), + message); + } + + [Test] + public void RoundTrip_NestedExtensionGroup() + { + var message = new TestGroupExtension(); + message.SetExtension(TestNestedExtension.Extensions.OptionalGroupExtension, new TestNestedExtension.Types.OptionalGroup_extension { A = 10 }); + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip( + TestGroupExtension.Parser.WithExtensionRegistry(new ExtensionRegistry() { TestNestedExtension.Extensions.OptionalGroupExtension }), + message); + } + + [Test] + public void RoundTrip_ParseUsingCodedInput() + { + var message = new TestAllExtensions(); + message.SetExtension(UnittestExtensions.OptionalBoolExtension, true); + byte[] bytes = message.ToByteArray(); + using (CodedInputStream input = new CodedInputStream(bytes)) + { + var parsed = TestAllExtensions.Parser.WithExtensionRegistry(new ExtensionRegistry() { UnittestExtensions.OptionalBoolExtension }).ParseFrom(input); + Assert.AreEqual(message, parsed); + } + } + } +}
diff --git a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs index 06af5e9..41a0b91 100644 --- a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs +++ b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs
@@ -1,799 +1,799 @@ -#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 System; -using System.IO; -using Google.Protobuf.TestProtos; -using Proto2 = Google.Protobuf.TestProtos.Proto2; -using NUnit.Framework; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Google.Protobuf.WellKnownTypes; - -namespace Google.Protobuf -{ - /// <summary> - /// Tests around the generated TestAllTypes message. - /// </summary> - public partial class GeneratedMessageTest - { - [Test] - public void EmptyMessageFieldDistinctFromMissingMessageField() - { - // This demonstrates what we're really interested in... - var message1 = new TestAllTypes { SingleForeignMessage = new ForeignMessage() }; - var message2 = new TestAllTypes(); // SingleForeignMessage is null - EqualityTester.AssertInequality(message1, message2); - } - - [Test] - public void DefaultValues() - { - // Single fields - var message = new TestAllTypes(); - Assert.AreEqual(false, message.SingleBool); - Assert.AreEqual(ByteString.Empty, message.SingleBytes); - Assert.AreEqual(0.0, message.SingleDouble); - Assert.AreEqual(0, message.SingleFixed32); - Assert.AreEqual(0L, message.SingleFixed64); - Assert.AreEqual(0.0f, message.SingleFloat); - Assert.AreEqual(ForeignEnum.ForeignUnspecified, message.SingleForeignEnum); - Assert.IsNull(message.SingleForeignMessage); - Assert.AreEqual(ImportEnum.Unspecified, message.SingleImportEnum); - Assert.IsNull(message.SingleImportMessage); - Assert.AreEqual(0, message.SingleInt32); - Assert.AreEqual(0L, message.SingleInt64); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.Unspecified, message.SingleNestedEnum); - Assert.IsNull(message.SingleNestedMessage); - Assert.IsNull(message.SinglePublicImportMessage); - Assert.AreEqual(0, message.SingleSfixed32); - Assert.AreEqual(0L, message.SingleSfixed64); - Assert.AreEqual(0, message.SingleSint32); - Assert.AreEqual(0L, message.SingleSint64); - Assert.AreEqual("", message.SingleString); - Assert.AreEqual(0U, message.SingleUint32); - Assert.AreEqual(0UL, message.SingleUint64); - - // Repeated fields - Assert.AreEqual(0, message.RepeatedBool.Count); - Assert.AreEqual(0, message.RepeatedBytes.Count); - Assert.AreEqual(0, message.RepeatedDouble.Count); - Assert.AreEqual(0, message.RepeatedFixed32.Count); - Assert.AreEqual(0, message.RepeatedFixed64.Count); - Assert.AreEqual(0, message.RepeatedFloat.Count); - Assert.AreEqual(0, message.RepeatedForeignEnum.Count); - Assert.AreEqual(0, message.RepeatedForeignMessage.Count); - Assert.AreEqual(0, message.RepeatedImportEnum.Count); - Assert.AreEqual(0, message.RepeatedImportMessage.Count); - Assert.AreEqual(0, message.RepeatedNestedEnum.Count); - Assert.AreEqual(0, message.RepeatedNestedMessage.Count); - Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count); - Assert.AreEqual(0, message.RepeatedSfixed32.Count); - Assert.AreEqual(0, message.RepeatedSfixed64.Count); - Assert.AreEqual(0, message.RepeatedSint32.Count); - Assert.AreEqual(0, message.RepeatedSint64.Count); - Assert.AreEqual(0, message.RepeatedString.Count); - Assert.AreEqual(0, message.RepeatedUint32.Count); - Assert.AreEqual(0, message.RepeatedUint64.Count); - - // Oneof fields - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - } - - [Test] - public void NullStringAndBytesRejected() - { - var message = new TestAllTypes(); - Assert.Throws<ArgumentNullException>(() => message.SingleString = null); - Assert.Throws<ArgumentNullException>(() => message.OneofString = null); - Assert.Throws<ArgumentNullException>(() => message.SingleBytes = null); - Assert.Throws<ArgumentNullException>(() => message.OneofBytes = null); - } - - [Test] - public void RoundTrip_Empty() - { - var message = new TestAllTypes(); - // Without setting any values, there's nothing to write. - byte[] bytes = message.ToByteArray(); - Assert.AreEqual(0, bytes.Length); - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message); - } - - [Test] - public void RoundTrip_SingleValues() - { - var message = new TestAllTypes - { - SingleBool = true, - SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), - SingleDouble = 23.5, - SingleFixed32 = 23, - SingleFixed64 = 1234567890123, - SingleFloat = 12.25f, - SingleForeignEnum = ForeignEnum.ForeignBar, - SingleForeignMessage = new ForeignMessage { C = 10 }, - SingleImportEnum = ImportEnum.ImportBaz, - SingleImportMessage = new ImportMessage { D = 20 }, - SingleInt32 = 100, - SingleInt64 = 3210987654321, - SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, - SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, - SinglePublicImportMessage = new PublicImportMessage { E = 54 }, - SingleSfixed32 = -123, - SingleSfixed64 = -12345678901234, - SingleSint32 = -456, - SingleSint64 = -12345678901235, - SingleString = "test", - SingleUint32 = uint.MaxValue, - SingleUint64 = ulong.MaxValue - }; - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message); - } - - [Test] - public void RoundTrip_RepeatedValues() - { - var message = new TestAllTypes - { - RepeatedBool = { true, false }, - RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, - RepeatedDouble = { -12.25, 23.5 }, - RepeatedFixed32 = { uint.MaxValue, 23 }, - RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, - RepeatedFloat = { 100f, 12.25f }, - RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar }, - RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, - RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified }, - RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, - RepeatedInt32 = { 100, 200 }, - RepeatedInt64 = { 3210987654321, long.MaxValue }, - RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, - RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, - RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, - RepeatedSfixed32 = { -123, 123 }, - RepeatedSfixed64 = { -12345678901234, 12345678901234 }, - RepeatedSint32 = { -456, 100 }, - RepeatedSint64 = { -12345678901235, 123 }, - RepeatedString = { "foo", "bar" }, - RepeatedUint32 = { uint.MaxValue, uint.MinValue }, - RepeatedUint64 = { ulong.MaxValue, uint.MinValue } - }; - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message); - } - - // Note that not every map within map_unittest_proto3 is used. They all go through very - // similar code paths. The fact that all maps are present is validation that we have codecs - // for every type. - [Test] - public void RoundTrip_Maps() - { - var message = new TestMap - { - MapBoolBool = { - { false, true }, - { true, false } - }, - MapInt32Bytes = { - { 5, ByteString.CopyFrom(6, 7, 8) }, - { 25, ByteString.CopyFrom(1, 2, 3, 4, 5) }, - { 10, ByteString.Empty } - }, - MapInt32ForeignMessage = { - { 0, new ForeignMessage { C = 10 } }, - { 5, new ForeignMessage() }, - }, - MapInt32Enum = { - { 1, MapEnum.Bar }, - { 2000, MapEnum.Foo } - } - }; - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip(TestMap.Parser, message); - } - - [Test] - public void MapWithEmptyEntry() - { - var message = new TestMap - { - MapInt32Bytes = { { 0, ByteString.Empty } } - }; - - byte[] bytes = message.ToByteArray(); - Assert.AreEqual(2, bytes.Length); // Tag for field entry (1 byte), length of entry (0; 1 byte) - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertReadingMessage( - TestMap.Parser, - bytes, - parsed=> - { - Assert.AreEqual(1, parsed.MapInt32Bytes.Count); - Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]); - }); - } - - [Test] - public void MapWithOnlyValue() - { - // Hand-craft the stream to contain a single entry with just a value. - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); - var nestedMessage = new ForeignMessage { C = 20 }; - // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage) - output.WriteLength(2 + nestedMessage.CalculateSize()); - output.WriteTag(2, WireFormat.WireType.LengthDelimited); - output.WriteMessage(nestedMessage); - output.Flush(); - - MessageParsingHelpers.AssertReadingMessage( - TestMap.Parser, - memoryStream.ToArray(), - parsed => - { - Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]); - }); - } - - [Test] - public void MapWithOnlyKey_PrimitiveValue() - { - // Hand-craft the stream to contain a single entry with just a key. - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - output.WriteTag(TestMap.MapInt32DoubleFieldNumber, WireFormat.WireType.LengthDelimited); - int key = 10; - output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.Flush(); - - MessageParsingHelpers.AssertReadingMessage( - TestMap.Parser, - memoryStream.ToArray(), - parsed => - { - Assert.AreEqual(0.0, parsed.MapInt32Double[key]); - }); - } - - [Test] - public void MapWithOnlyKey_MessageValue() - { - // Hand-craft the stream to contain a single entry with just a key. - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); - int key = 10; - output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.Flush(); - - MessageParsingHelpers.AssertReadingMessage( - TestMap.Parser, - memoryStream.ToArray(), - parsed => - { - Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]); - }); - } - - [Test] - public void MapIgnoresExtraFieldsWithinEntryMessages() - { - // Hand-craft the stream to contain a single entry with three fields - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - - var key = 10; // Field 1 - var value = 20; // Field 2 - var extra = 30; // Field 3 - - // Each field can be represented in a single byte, with a single byte tag. - // Total message size: 6 bytes. - output.WriteLength(6); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value); - output.WriteTag(3, WireFormat.WireType.Varint); - output.WriteInt32(extra); - output.Flush(); - - MessageParsingHelpers.AssertReadingMessage( - TestMap.Parser, - memoryStream.ToArray(), - parsed => - { - Assert.AreEqual(value, parsed.MapInt32Int32[key]); - }); - } - - [Test] - public void MapFieldOrderIsIrrelevant() - { - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - - var key = 10; - var value = 20; - - // Each field can be represented in a single byte, with a single byte tag. - // Total message size: 4 bytes. - output.WriteLength(4); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.Flush(); - - MessageParsingHelpers.AssertReadingMessage( - TestMap.Parser, - memoryStream.ToArray(), - parsed => - { - Assert.AreEqual(value, parsed.MapInt32Int32[key]); - }); - } - - [Test] - public void MapNonContiguousEntries() - { - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - - // Message structure: - // Entry for MapInt32Int32 - // Entry for MapStringString - // Entry for MapInt32Int32 - - // First entry - var key1 = 10; - var value1 = 20; - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(4); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key1); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value1); - - // Second entry - var key2 = "a"; - var value2 = "b"; - output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(6); // 3 bytes per entry: tag, size, character - output.WriteTag(1, WireFormat.WireType.LengthDelimited); - output.WriteString(key2); - output.WriteTag(2, WireFormat.WireType.LengthDelimited); - output.WriteString(value2); - - // Third entry - var key3 = 15; - var value3 = 25; - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(4); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key3); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value3); - - output.Flush(); - - MessageParsingHelpers.AssertReadingMessage( - TestMap.Parser, - memoryStream.ToArray(), - parsed => - { - var expected = new TestMap - { - MapInt32Int32 = { { key1, value1 }, { key3, value3 } }, - MapStringString = { { key2, value2 } } - }; - Assert.AreEqual(expected, parsed); - }); - } - - [Test] - public void DuplicateKeys_LastEntryWins() - { - var memoryStream = new MemoryStream(); - var output = new CodedOutputStream(memoryStream); - - var key = 10; - var value1 = 20; - var value2 = 30; - - // First entry - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(4); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value1); - - // Second entry - same key, different value - output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteLength(4); - output.WriteTag(1, WireFormat.WireType.Varint); - output.WriteInt32(key); - output.WriteTag(2, WireFormat.WireType.Varint); - output.WriteInt32(value2); - output.Flush(); - - MessageParsingHelpers.AssertReadingMessage( - TestMap.Parser, - memoryStream.ToArray(), - parsed => - { - Assert.AreEqual(value2, parsed.MapInt32Int32[key]); - }); - } - - [Test] - public void CloneSingleNonMessageValues() - { - var original = new TestAllTypes - { - SingleBool = true, - SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), - SingleDouble = 23.5, - SingleFixed32 = 23, - SingleFixed64 = 1234567890123, - SingleFloat = 12.25f, - SingleInt32 = 100, - SingleInt64 = 3210987654321, - SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, - SingleSfixed32 = -123, - SingleSfixed64 = -12345678901234, - SingleSint32 = -456, - SingleSint64 = -12345678901235, - SingleString = "test", - SingleUint32 = uint.MaxValue, - SingleUint64 = ulong.MaxValue - }; - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreEqual(original, clone); - // Just as a single example - clone.SingleInt32 = 150; - Assert.AreNotEqual(original, clone); - } - - [Test] - public void CloneRepeatedNonMessageValues() - { - var original = new TestAllTypes - { - RepeatedBool = { true, false }, - RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, - RepeatedDouble = { -12.25, 23.5 }, - RepeatedFixed32 = { uint.MaxValue, 23 }, - RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, - RepeatedFloat = { 100f, 12.25f }, - RepeatedInt32 = { 100, 200 }, - RepeatedInt64 = { 3210987654321, long.MaxValue }, - RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, - RepeatedSfixed32 = { -123, 123 }, - RepeatedSfixed64 = { -12345678901234, 12345678901234 }, - RepeatedSint32 = { -456, 100 }, - RepeatedSint64 = { -12345678901235, 123 }, - RepeatedString = { "foo", "bar" }, - RepeatedUint32 = { uint.MaxValue, uint.MinValue }, - RepeatedUint64 = { ulong.MaxValue, uint.MinValue } - }; - - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreEqual(original, clone); - // Just as a single example - clone.RepeatedDouble.Add(25.5); - Assert.AreNotEqual(original, clone); - } - - [Test] - public void CloneSingleMessageField() - { - var original = new TestAllTypes - { - SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } - }; - - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreNotSame(original.SingleNestedMessage, clone.SingleNestedMessage); - Assert.AreEqual(original, clone); - - clone.SingleNestedMessage.Bb = 30; - Assert.AreNotEqual(original, clone); - } - - [Test] - public void CloneRepeatedMessageField() - { - var original = new TestAllTypes - { - RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 20 } } - }; - - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreNotSame(original.RepeatedNestedMessage, clone.RepeatedNestedMessage); - Assert.AreNotSame(original.RepeatedNestedMessage[0], clone.RepeatedNestedMessage[0]); - Assert.AreEqual(original, clone); - - clone.RepeatedNestedMessage[0].Bb = 30; - Assert.AreNotEqual(original, clone); - } - - [Test] - public void CloneOneofField() - { - var original = new TestAllTypes - { - OneofNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } - }; - - var clone = original.Clone(); - Assert.AreNotSame(original, clone); - Assert.AreEqual(original, clone); - - // We should have cloned the message - original.OneofNestedMessage.Bb = 30; - Assert.AreNotEqual(original, clone); - } - - [Test] - public void OneofProperties() - { - // Switch the oneof case between each of the different options, and check everything behaves - // as expected in each case. - var message = new TestAllTypes(); - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); - - message.OneofString = "sample"; - Assert.AreEqual("sample", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase); - - var bytes = ByteString.CopyFrom(1, 2, 3); - message.OneofBytes = bytes; - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(bytes, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofBytes, message.OneofFieldCase); - - message.OneofUint32 = 20; - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(20, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase); - - var nestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 25 }; - message.OneofNestedMessage = nestedMessage; - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.AreEqual(nestedMessage, message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofNestedMessage, message.OneofFieldCase); - - message.ClearOneofField(); - Assert.AreEqual("", message.OneofString); - Assert.AreEqual(0, message.OneofUint32); - Assert.AreEqual(ByteString.Empty, message.OneofBytes); - Assert.IsNull(message.OneofNestedMessage); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); - } - - [Test] - public void Oneof_DefaultValuesNotEqual() - { - var message1 = new TestAllTypes { OneofString = "" }; - var message2 = new TestAllTypes { OneofUint32 = 0 }; - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message1.OneofFieldCase); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); - Assert.AreNotEqual(message1, message2); - } - - [Test] - public void OneofSerialization_NonDefaultValue() - { - var message = new TestAllTypes(); - message.OneofString = "this would take a bit of space"; - message.OneofUint32 = 10; - var bytes = message.ToByteArray(); - Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - no string! - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message, parsedMessage => - { - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, parsedMessage.OneofFieldCase); - }); - } - - [Test] - public void OneofSerialization_DefaultValue() - { - var message = new TestAllTypes(); - message.OneofString = "this would take a bit of space"; - message.OneofUint32 = 0; // This is the default value for UInt32; normally wouldn't be serialized - var bytes = message.ToByteArray(); - Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - it's still serialized - - MessageParsingHelpers.AssertWritingMessage(message); - - MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message, parsedMessage => - { - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, parsedMessage.OneofFieldCase); - }); - } - - [Test] - public void DiscardUnknownFields_RealDataStillRead() - { - var message = SampleMessages.CreateFullTestAllTypes(); - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - var unusedFieldNumber = 23456; - Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber)); - output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited); - output.WriteString("ignore me"); - message.WriteTo(output); - output.Flush(); - - MessageParsingHelpers.AssertReadingMessage( - TestAllTypes.Parser, - stream.ToArray(), - parsed => - { - // TODO(jieluo): Add test back when DiscardUnknownFields API is supported. - // Assert.AreEqual(message, parsed); - }); - } - - [Test] - public void DiscardUnknownFields_AllTypes() - { - // Simple way of ensuring we can skip all kinds of fields. - var data = SampleMessages.CreateFullTestAllTypes().ToByteArray(); - var empty = Empty.Parser.ParseFrom(data); - - 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. - [Test] - public void TruncatedMessageFieldThrows() - { - // 130, 3 is the message tag - // 1 is the data length - but there's no data. - var data = new byte[] { 130, 3, 1 }; - MessageParsingHelpers.AssertReadingMessageThrows<TestAllTypes, InvalidProtocolBufferException>(TestAllTypes.Parser, data); - } - - /// <summary> - /// Demonstrates current behaviour with an extraneous end group tag - see issue 688 - /// for details; we may want to change this. - /// </summary> - [Test] - public void ExtraEndGroupThrows() - { - var message = SampleMessages.CreateFullTestAllTypes(); - var stream = new MemoryStream(); - var output = new CodedOutputStream(stream); - - output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32); - output.WriteFixed32(123); - output.WriteTag(100, WireFormat.WireType.EndGroup); - - output.Flush(); - - stream.Position = 0; - MessageParsingHelpers.AssertReadingMessageThrows<TestAllTypes, InvalidProtocolBufferException>(TestAllTypes.Parser, stream.ToArray()); - } - - [Test] - public void CustomDiagnosticMessage_DirectToStringCall() - { - var message = new ForeignMessage { C = 31 }; - Assert.AreEqual("{ \"c\": 31, \"@cInHex\": \"1f\" }", message.ToString()); - Assert.AreEqual("{ \"c\": 31 }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void CustomDiagnosticMessage_Nested() - { - var message = new TestAllTypes { SingleForeignMessage = new ForeignMessage { C = 16 } }; - Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16, \"@cInHex\": \"10\" } }", message.ToString()); - Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16 } }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void CustomDiagnosticMessage_DirectToTextWriterCall() - { - var message = new ForeignMessage { C = 31 }; - var writer = new StringWriter(); - JsonFormatter.Default.Format(message, writer); - Assert.AreEqual("{ \"c\": 31 }", writer.ToString()); - } - - [Test] - public void NaNComparisons() - { - var message1 = new TestAllTypes { SingleDouble = SampleNaNs.Regular }; - var message2 = new TestAllTypes { SingleDouble = SampleNaNs.PayloadFlipped }; - var message3 = new TestAllTypes { SingleDouble = SampleNaNs.Regular }; - - EqualityTester.AssertInequality(message1, message2); - EqualityTester.AssertEquality(message1, message3); - } - } +#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 System; +using System.IO; +using Google.Protobuf.TestProtos; +using Proto2 = Google.Protobuf.TestProtos.Proto2; +using NUnit.Framework; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Google.Protobuf.WellKnownTypes; + +namespace Google.Protobuf +{ + /// <summary> + /// Tests around the generated TestAllTypes message. + /// </summary> + public partial class GeneratedMessageTest + { + [Test] + public void EmptyMessageFieldDistinctFromMissingMessageField() + { + // This demonstrates what we're really interested in... + var message1 = new TestAllTypes { SingleForeignMessage = new ForeignMessage() }; + var message2 = new TestAllTypes(); // SingleForeignMessage is null + EqualityTester.AssertInequality(message1, message2); + } + + [Test] + public void DefaultValues() + { + // Single fields + var message = new TestAllTypes(); + Assert.AreEqual(false, message.SingleBool); + Assert.AreEqual(ByteString.Empty, message.SingleBytes); + Assert.AreEqual(0.0, message.SingleDouble); + Assert.AreEqual(0, message.SingleFixed32); + Assert.AreEqual(0L, message.SingleFixed64); + Assert.AreEqual(0.0f, message.SingleFloat); + Assert.AreEqual(ForeignEnum.ForeignUnspecified, message.SingleForeignEnum); + Assert.IsNull(message.SingleForeignMessage); + Assert.AreEqual(ImportEnum.Unspecified, message.SingleImportEnum); + Assert.IsNull(message.SingleImportMessage); + Assert.AreEqual(0, message.SingleInt32); + Assert.AreEqual(0L, message.SingleInt64); + Assert.AreEqual(TestAllTypes.Types.NestedEnum.Unspecified, message.SingleNestedEnum); + Assert.IsNull(message.SingleNestedMessage); + Assert.IsNull(message.SinglePublicImportMessage); + Assert.AreEqual(0, message.SingleSfixed32); + Assert.AreEqual(0L, message.SingleSfixed64); + Assert.AreEqual(0, message.SingleSint32); + Assert.AreEqual(0L, message.SingleSint64); + Assert.AreEqual("", message.SingleString); + Assert.AreEqual(0U, message.SingleUint32); + Assert.AreEqual(0UL, message.SingleUint64); + + // Repeated fields + Assert.AreEqual(0, message.RepeatedBool.Count); + Assert.AreEqual(0, message.RepeatedBytes.Count); + Assert.AreEqual(0, message.RepeatedDouble.Count); + Assert.AreEqual(0, message.RepeatedFixed32.Count); + Assert.AreEqual(0, message.RepeatedFixed64.Count); + Assert.AreEqual(0, message.RepeatedFloat.Count); + Assert.AreEqual(0, message.RepeatedForeignEnum.Count); + Assert.AreEqual(0, message.RepeatedForeignMessage.Count); + Assert.AreEqual(0, message.RepeatedImportEnum.Count); + Assert.AreEqual(0, message.RepeatedImportMessage.Count); + Assert.AreEqual(0, message.RepeatedNestedEnum.Count); + Assert.AreEqual(0, message.RepeatedNestedMessage.Count); + Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count); + Assert.AreEqual(0, message.RepeatedSfixed32.Count); + Assert.AreEqual(0, message.RepeatedSfixed64.Count); + Assert.AreEqual(0, message.RepeatedSint32.Count); + Assert.AreEqual(0, message.RepeatedSint64.Count); + Assert.AreEqual(0, message.RepeatedString.Count); + Assert.AreEqual(0, message.RepeatedUint32.Count); + Assert.AreEqual(0, message.RepeatedUint64.Count); + + // Oneof fields + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + } + + [Test] + public void NullStringAndBytesRejected() + { + var message = new TestAllTypes(); + Assert.Throws<ArgumentNullException>(() => message.SingleString = null); + Assert.Throws<ArgumentNullException>(() => message.OneofString = null); + Assert.Throws<ArgumentNullException>(() => message.SingleBytes = null); + Assert.Throws<ArgumentNullException>(() => message.OneofBytes = null); + } + + [Test] + public void RoundTrip_Empty() + { + var message = new TestAllTypes(); + // Without setting any values, there's nothing to write. + byte[] bytes = message.ToByteArray(); + Assert.AreEqual(0, bytes.Length); + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message); + } + + [Test] + public void RoundTrip_SingleValues() + { + var message = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleForeignEnum = ForeignEnum.ForeignBar, + SingleForeignMessage = new ForeignMessage { C = 10 }, + SingleImportEnum = ImportEnum.ImportBaz, + SingleImportMessage = new ImportMessage { D = 20 }, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, + SinglePublicImportMessage = new PublicImportMessage { E = 54 }, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message); + } + + [Test] + public void RoundTrip_RepeatedValues() + { + var message = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedForeignEnum = { ForeignEnum.ForeignFoo, ForeignEnum.ForeignBar }, + RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, + RepeatedImportEnum = { ImportEnum.ImportBaz, ImportEnum.Unspecified }, + RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, + RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { uint.MaxValue, uint.MinValue }, + RepeatedUint64 = { ulong.MaxValue, uint.MinValue } + }; + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message); + } + + // Note that not every map within map_unittest_proto3 is used. They all go through very + // similar code paths. The fact that all maps are present is validation that we have codecs + // for every type. + [Test] + public void RoundTrip_Maps() + { + var message = new TestMap + { + MapBoolBool = { + { false, true }, + { true, false } + }, + MapInt32Bytes = { + { 5, ByteString.CopyFrom(6, 7, 8) }, + { 25, ByteString.CopyFrom(1, 2, 3, 4, 5) }, + { 10, ByteString.Empty } + }, + MapInt32ForeignMessage = { + { 0, new ForeignMessage { C = 10 } }, + { 5, new ForeignMessage() }, + }, + MapInt32Enum = { + { 1, MapEnum.Bar }, + { 2000, MapEnum.Foo } + } + }; + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestMap.Parser, message); + } + + [Test] + public void MapWithEmptyEntry() + { + var message = new TestMap + { + MapInt32Bytes = { { 0, ByteString.Empty } } + }; + + byte[] bytes = message.ToByteArray(); + Assert.AreEqual(2, bytes.Length); // Tag for field entry (1 byte), length of entry (0; 1 byte) + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertReadingMessage( + TestMap.Parser, + bytes, + parsed=> + { + Assert.AreEqual(1, parsed.MapInt32Bytes.Count); + Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]); + }); + } + + [Test] + public void MapWithOnlyValue() + { + // Hand-craft the stream to contain a single entry with just a value. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); + var nestedMessage = new ForeignMessage { C = 20 }; + // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage) + output.WriteLength(2 + nestedMessage.CalculateSize()); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteMessage(nestedMessage); + output.Flush(); + + MessageParsingHelpers.AssertReadingMessage( + TestMap.Parser, + memoryStream.ToArray(), + parsed => + { + Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]); + }); + } + + [Test] + public void MapWithOnlyKey_PrimitiveValue() + { + // Hand-craft the stream to contain a single entry with just a key. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32DoubleFieldNumber, WireFormat.WireType.LengthDelimited); + int key = 10; + output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + MessageParsingHelpers.AssertReadingMessage( + TestMap.Parser, + memoryStream.ToArray(), + parsed => + { + Assert.AreEqual(0.0, parsed.MapInt32Double[key]); + }); + } + + [Test] + public void MapWithOnlyKey_MessageValue() + { + // Hand-craft the stream to contain a single entry with just a key. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); + int key = 10; + output.WriteLength(1 + CodedOutputStream.ComputeInt32Size(key)); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + MessageParsingHelpers.AssertReadingMessage( + TestMap.Parser, + memoryStream.ToArray(), + parsed => + { + Assert.AreEqual(new ForeignMessage(), parsed.MapInt32ForeignMessage[key]); + }); + } + + [Test] + public void MapIgnoresExtraFieldsWithinEntryMessages() + { + // Hand-craft the stream to contain a single entry with three fields + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + + var key = 10; // Field 1 + var value = 20; // Field 2 + var extra = 30; // Field 3 + + // Each field can be represented in a single byte, with a single byte tag. + // Total message size: 6 bytes. + output.WriteLength(6); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value); + output.WriteTag(3, WireFormat.WireType.Varint); + output.WriteInt32(extra); + output.Flush(); + + MessageParsingHelpers.AssertReadingMessage( + TestMap.Parser, + memoryStream.ToArray(), + parsed => + { + Assert.AreEqual(value, parsed.MapInt32Int32[key]); + }); + } + + [Test] + public void MapFieldOrderIsIrrelevant() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + + var key = 10; + var value = 20; + + // Each field can be represented in a single byte, with a single byte tag. + // Total message size: 4 bytes. + output.WriteLength(4); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + MessageParsingHelpers.AssertReadingMessage( + TestMap.Parser, + memoryStream.ToArray(), + parsed => + { + Assert.AreEqual(value, parsed.MapInt32Int32[key]); + }); + } + + [Test] + public void MapNonContiguousEntries() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + // Message structure: + // Entry for MapInt32Int32 + // Entry for MapStringString + // Entry for MapInt32Int32 + + // First entry + var key1 = 10; + var value1 = 20; + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key1); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value1); + + // Second entry + var key2 = "a"; + var value2 = "b"; + output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(6); // 3 bytes per entry: tag, size, character + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString(key2); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteString(value2); + + // Third entry + var key3 = 15; + var value3 = 25; + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key3); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value3); + + output.Flush(); + + MessageParsingHelpers.AssertReadingMessage( + TestMap.Parser, + memoryStream.ToArray(), + parsed => + { + var expected = new TestMap + { + MapInt32Int32 = { { key1, value1 }, { key3, value3 } }, + MapStringString = { { key2, value2 } } + }; + Assert.AreEqual(expected, parsed); + }); + } + + [Test] + public void DuplicateKeys_LastEntryWins() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + var key = 10; + var value1 = 20; + var value2 = 30; + + // First entry + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value1); + + // Second entry - same key, different value + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value2); + output.Flush(); + + MessageParsingHelpers.AssertReadingMessage( + TestMap.Parser, + memoryStream.ToArray(), + parsed => + { + Assert.AreEqual(value2, parsed.MapInt32Int32[key]); + }); + } + + [Test] + public void CloneSingleNonMessageValues() + { + var original = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + // Just as a single example + clone.SingleInt32 = 150; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneRepeatedNonMessageValues() + { + var original = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.Foo, TestAllTypes.Types.NestedEnum.Neg }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { uint.MaxValue, uint.MinValue }, + RepeatedUint64 = { ulong.MaxValue, uint.MinValue } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + // Just as a single example + clone.RepeatedDouble.Add(25.5); + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneSingleMessageField() + { + var original = new TestAllTypes + { + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreNotSame(original.SingleNestedMessage, clone.SingleNestedMessage); + Assert.AreEqual(original, clone); + + clone.SingleNestedMessage.Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneRepeatedMessageField() + { + var original = new TestAllTypes + { + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 20 } } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreNotSame(original.RepeatedNestedMessage, clone.RepeatedNestedMessage); + Assert.AreNotSame(original.RepeatedNestedMessage[0], clone.RepeatedNestedMessage[0]); + Assert.AreEqual(original, clone); + + clone.RepeatedNestedMessage[0].Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneOneofField() + { + var original = new TestAllTypes + { + OneofNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + + // We should have cloned the message + original.OneofNestedMessage.Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void OneofProperties() + { + // Switch the oneof case between each of the different options, and check everything behaves + // as expected in each case. + var message = new TestAllTypes(); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + + message.OneofString = "sample"; + Assert.AreEqual("sample", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase); + + var bytes = ByteString.CopyFrom(1, 2, 3); + message.OneofBytes = bytes; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(bytes, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofBytes, message.OneofFieldCase); + + message.OneofUint32 = 20; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(20, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase); + + var nestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 25 }; + message.OneofNestedMessage = nestedMessage; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.AreEqual(nestedMessage, message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofNestedMessage, message.OneofFieldCase); + + message.ClearOneofField(); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + } + + [Test] + public void Oneof_DefaultValuesNotEqual() + { + var message1 = new TestAllTypes { OneofString = "" }; + var message2 = new TestAllTypes { OneofUint32 = 0 }; + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message1.OneofFieldCase); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); + Assert.AreNotEqual(message1, message2); + } + + [Test] + public void OneofSerialization_NonDefaultValue() + { + var message = new TestAllTypes(); + message.OneofString = "this would take a bit of space"; + message.OneofUint32 = 10; + var bytes = message.ToByteArray(); + Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - no string! + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message, parsedMessage => + { + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, parsedMessage.OneofFieldCase); + }); + } + + [Test] + public void OneofSerialization_DefaultValue() + { + var message = new TestAllTypes(); + message.OneofString = "this would take a bit of space"; + message.OneofUint32 = 0; // This is the default value for UInt32; normally wouldn't be serialized + var bytes = message.ToByteArray(); + Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - it's still serialized + + MessageParsingHelpers.AssertWritingMessage(message); + + MessageParsingHelpers.AssertRoundtrip(TestAllTypes.Parser, message, parsedMessage => + { + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, parsedMessage.OneofFieldCase); + }); + } + + [Test] + public void DiscardUnknownFields_RealDataStillRead() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var unusedFieldNumber = 23456; + Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber)); + output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteString("ignore me"); + message.WriteTo(output); + output.Flush(); + + MessageParsingHelpers.AssertReadingMessage( + TestAllTypes.Parser, + stream.ToArray(), + parsed => + { + // TODO(jieluo): Add test back when DiscardUnknownFields API is supported. + // Assert.AreEqual(message, parsed); + }); + } + + [Test] + public void DiscardUnknownFields_AllTypes() + { + // Simple way of ensuring we can skip all kinds of fields. + var data = SampleMessages.CreateFullTestAllTypes().ToByteArray(); + var empty = Empty.Parser.ParseFrom(data); + + 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. + [Test] + public void TruncatedMessageFieldThrows() + { + // 130, 3 is the message tag + // 1 is the data length - but there's no data. + var data = new byte[] { 130, 3, 1 }; + MessageParsingHelpers.AssertReadingMessageThrows<TestAllTypes, InvalidProtocolBufferException>(TestAllTypes.Parser, data); + } + + /// <summary> + /// Demonstrates current behaviour with an extraneous end group tag - see issue 688 + /// for details; we may want to change this. + /// </summary> + [Test] + public void ExtraEndGroupThrows() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + + output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32); + output.WriteFixed32(123); + output.WriteTag(100, WireFormat.WireType.EndGroup); + + output.Flush(); + + stream.Position = 0; + MessageParsingHelpers.AssertReadingMessageThrows<TestAllTypes, InvalidProtocolBufferException>(TestAllTypes.Parser, stream.ToArray()); + } + + [Test] + public void CustomDiagnosticMessage_DirectToStringCall() + { + var message = new ForeignMessage { C = 31 }; + Assert.AreEqual("{ \"c\": 31, \"@cInHex\": \"1f\" }", message.ToString()); + Assert.AreEqual("{ \"c\": 31 }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void CustomDiagnosticMessage_Nested() + { + var message = new TestAllTypes { SingleForeignMessage = new ForeignMessage { C = 16 } }; + Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16, \"@cInHex\": \"10\" } }", message.ToString()); + Assert.AreEqual("{ \"singleForeignMessage\": { \"c\": 16 } }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void CustomDiagnosticMessage_DirectToTextWriterCall() + { + var message = new ForeignMessage { C = 31 }; + var writer = new StringWriter(); + JsonFormatter.Default.Format(message, writer); + Assert.AreEqual("{ \"c\": 31 }", writer.ToString()); + } + + [Test] + public void NaNComparisons() + { + var message1 = new TestAllTypes { SingleDouble = SampleNaNs.Regular }; + var message2 = new TestAllTypes { SingleDouble = SampleNaNs.PayloadFlipped }; + var message3 = new TestAllTypes { SingleDouble = SampleNaNs.Regular }; + + EqualityTester.AssertInequality(message1, message2); + EqualityTester.AssertEquality(message1, message3); + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj index deb17e9..fe5ff80 100644 --- a/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj +++ b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
@@ -1,7 +1,7 @@ <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> - <TargetFrameworks>net451;netcoreapp3.1;net60</TargetFrameworks> + <TargetFrameworks>net462;netcoreapp3.1;net60</TargetFrameworks> <AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile> <SignAssembly>true</SignAssembly> <IsPackable>False</IsPackable> @@ -14,14 +14,14 @@ </ItemGroup> <ItemGroup> - <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" /> - <PackageReference Include="NUnit" Version="3.9.0" /> - <PackageReference Include="NUnit3TestAdapter" Version="3.9.0" /> + <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" /> + <PackageReference Include="NUnit" Version="3.13.3" /> + <PackageReference Include="NUnit3TestAdapter" Version="4.2.1" /> </ItemGroup> <!-- Needed for the net45 build to work on Unix. See https://github.com/dotnet/designs/pull/33 --> <ItemGroup> - <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" /> + <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="All" /> </ItemGroup> <ItemGroup>
diff --git a/csharp/src/Google.Protobuf.Test/IssuesTest.cs b/csharp/src/Google.Protobuf.Test/IssuesTest.cs index 2904c46..6953989 100644 --- a/csharp/src/Google.Protobuf.Test/IssuesTest.cs +++ b/csharp/src/Google.Protobuf.Test/IssuesTest.cs
@@ -1,116 +1,132 @@ -#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.Reflection; -using UnitTest.Issues.TestProtos; -using NUnit.Framework; -using System.IO; -using static UnitTest.Issues.TestProtos.OneofMerging.Types; - -namespace Google.Protobuf -{ - /// <summary> - /// Tests for issues which aren't easily compartmentalized into other unit tests. - /// </summary> - public class IssuesTest - { - // Issue 45 - [Test] - public void FieldCalledItem() - { - ItemField message = new ItemField { Item = 3 }; - FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item"); - Assert.NotNull(field); - Assert.AreEqual(3, (int)field.Accessor.GetValue(message)); - } - - [Test] - public void ReservedNames() - { - var message = new ReservedNames { Types_ = 10, Descriptor_ = 20 }; - // Underscores aren't reflected in the JSON. - Assert.AreEqual("{ \"types\": 10, \"descriptor\": 20 }", message.ToString()); - } - - [Test] - public void JsonNameParseTest() - { - var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor)); - var parser = new JsonParser(settings); - - // It is safe to use either original field name or explicitly specified json_name - Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }, - parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }")); - } - - [Test] - public void JsonNameFormatTest() - { - var message = new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }; - Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }", - JsonFormatter.Default.Format(message)); - } - - [Test] - public void OneofMerging() - { - var message1 = new OneofMerging { Nested = new Nested { X = 10 } }; - var message2 = new OneofMerging { Nested = new Nested { Y = 20 } }; - var expected = new OneofMerging { Nested = new Nested { X = 10, Y = 20 } }; - - var merged = message1.Clone(); - 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 - // described 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)); - } - } -} +#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.Reflection; +using UnitTest.Issues.TestProtos; +using NUnit.Framework; +using System.IO; +using static UnitTest.Issues.TestProtos.OneofMerging.Types; + +namespace Google.Protobuf +{ + /// <summary> + /// Tests for issues which aren't easily compartmentalized into other unit tests. + /// </summary> + public class IssuesTest + { + // Issue 45 + [Test] + public void FieldCalledItem() + { + ItemField message = new ItemField { Item = 3 }; + FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item"); + Assert.NotNull(field); + Assert.AreEqual(3, (int)field.Accessor.GetValue(message)); + } + + [Test] + public void ReservedNames() + { + var message = new ReservedNames { Types_ = 10, Descriptor_ = 20 }; + // Underscores aren't reflected in the JSON. + Assert.AreEqual("{ \"types\": 10, \"descriptor\": 20 }", message.ToString()); + } + + [Test] + public void JsonNameParseTest() + { + var settings = new JsonParser.Settings(10, TypeRegistry.FromFiles(UnittestIssuesReflection.Descriptor)); + var parser = new JsonParser(settings); + + // It is safe to use either original field name or explicitly specified json_name + Assert.AreEqual(new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }, + parser.Parse<TestJsonName>("{ \"name\": \"test\", \"desc\": \"test2\", \"guid\": \"test3\" }")); + } + + [Test] + public void JsonNameFormatTest() + { + var message = new TestJsonName { Name = "test", Description = "test2", Guid = "test3" }; + Assert.AreEqual("{ \"name\": \"test\", \"desc\": \"test2\", \"exid\": \"test3\" }", + JsonFormatter.Default.Format(message)); + } + + [Test] + public void OneofMerging() + { + var message1 = new OneofMerging { Nested = new Nested { X = 10 } }; + var message2 = new OneofMerging { Nested = new Nested { Y = 20 } }; + var expected = new OneofMerging { Nested = new Nested { X = 10, Y = 20 } }; + + var merged = message1.Clone(); + 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 + // described 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)); + } + + [Test] + public void NoneFieldInOneof() + { + var message = new OneofWithNoneField(); + var emptyHashCode = message.GetHashCode(); + Assert.AreEqual(OneofWithNoneField.TestOneofCase.None, message.TestCase); + message.None = "test"; + Assert.AreEqual(OneofWithNoneField.TestOneofCase.None_, message.TestCase); + Assert.AreNotEqual(emptyHashCode, message.GetHashCode()); + + var bytes = message.ToByteArray(); + var parsed = OneofWithNoneField.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + Assert.AreEqual("test", parsed.None); + } + } +}
diff --git a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs index 51fa5e0..3a77990 100644 --- a/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs +++ b/csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs
@@ -1,705 +1,705 @@ -#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 Google.Protobuf.TestProtos; -using NUnit.Framework; -using UnitTest.Issues.TestProtos; -using Google.Protobuf.WellKnownTypes; -using Google.Protobuf.Reflection; - -using static Google.Protobuf.JsonParserTest; // For WrapInQuotes -using System.IO; -using Google.Protobuf.Collections; -using ProtobufUnittest; - -namespace Google.Protobuf -{ - /// <summary> - /// Tests for the JSON formatter. Note that in these tests, double quotes are replaced with apostrophes - /// for the sake of readability (embedding \" everywhere is painful). See the AssertJson method for details. - /// </summary> - public class JsonFormatterTest - { - [Test] - public void DefaultValues_WhenOmitted() - { - var formatter = JsonFormatter.Default; - - AssertJson("{ }", formatter.Format(new ForeignMessage())); - AssertJson("{ }", formatter.Format(new TestAllTypes())); - AssertJson("{ }", formatter.Format(new TestMap())); - } - - [Test] - public void DefaultValues_WhenIncluded() - { - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - AssertJson("{ 'c': 0 }", formatter.Format(new ForeignMessage())); - } - - [Test] - public void EnumAllowAlias() - { - var message = new TestEnumAllowAlias - { - Value = TestEnumWithDupValue.Foo2, - }; - var actualText = JsonFormatter.Default.Format(message); - var expectedText = "{ 'value': 'FOO1' }"; - AssertJson(expectedText, actualText); - } - - [Test] - public void EnumAsInt() - { - var message = new TestAllTypes - { - SingleForeignEnum = ForeignEnum.ForeignBar, - RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } - }; - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatEnumsAsIntegers(true)); - var actualText = formatter.Format(message); - var expectedText = "{ " + - "'singleForeignEnum': 5, " + - "'repeatedForeignEnum': [ 6, 100, 4 ]" + - " }"; - AssertJson(expectedText, actualText); - } - - [Test] - public void AllSingleFields() - { - var message = new TestAllTypes - { - SingleBool = true, - SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), - SingleDouble = 23.5, - SingleFixed32 = 23, - SingleFixed64 = 1234567890123, - SingleFloat = 12.25f, - SingleForeignEnum = ForeignEnum.ForeignBar, - SingleForeignMessage = new ForeignMessage { C = 10 }, - SingleImportEnum = ImportEnum.ImportBaz, - SingleImportMessage = new ImportMessage { D = 20 }, - SingleInt32 = 100, - SingleInt64 = 3210987654321, - SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, - SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, - SinglePublicImportMessage = new PublicImportMessage { E = 54 }, - SingleSfixed32 = -123, - SingleSfixed64 = -12345678901234, - SingleSint32 = -456, - SingleSint64 = -12345678901235, - SingleString = "test\twith\ttabs", - SingleUint32 = uint.MaxValue, - SingleUint64 = ulong.MaxValue, - }; - var actualText = JsonFormatter.Default.Format(message); - - // Fields in numeric order - var expectedText = "{ " + - "'singleInt32': 100, " + - "'singleInt64': '3210987654321', " + - "'singleUint32': 4294967295, " + - "'singleUint64': '18446744073709551615', " + - "'singleSint32': -456, " + - "'singleSint64': '-12345678901235', " + - "'singleFixed32': 23, " + - "'singleFixed64': '1234567890123', " + - "'singleSfixed32': -123, " + - "'singleSfixed64': '-12345678901234', " + - "'singleFloat': 12.25, " + - "'singleDouble': 23.5, " + - "'singleBool': true, " + - "'singleString': 'test\\twith\\ttabs', " + - "'singleBytes': 'AQIDBA==', " + - "'singleNestedMessage': { 'bb': 35 }, " + - "'singleForeignMessage': { 'c': 10 }, " + - "'singleImportMessage': { 'd': 20 }, " + - "'singleNestedEnum': 'FOO', " + - "'singleForeignEnum': 'FOREIGN_BAR', " + - "'singleImportEnum': 'IMPORT_BAZ', " + - "'singlePublicImportMessage': { 'e': 54 }" + - " }"; - AssertJson(expectedText, actualText); - } - - [Test] - public void WithFormatDefaultValues_DoesNotAffectMessageFields() - { - var message = new TestAllTypes(); - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - var json = formatter.Format(message); - Assert.IsFalse(json.Contains("\"singleNestedMessage\"")); - Assert.IsFalse(json.Contains("\"singleForeignMessage\"")); - Assert.IsFalse(json.Contains("\"singleImportMessage\"")); - } - - [Test] - public void WithFormatDefaultValues_DoesNotAffectProto3OptionalFields() - { - var message = new TestProto3Optional(); - message.OptionalInt32 = 0; - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - var json = formatter.Format(message); - // The non-optional proto3 fields are formatted, as is the optional-but-specified field. - AssertJson("{ 'optionalInt32': 0, 'singularInt32': 0, 'singularInt64': '0' }", json); - } - - [Test] - public void WithFormatDefaultValues_DoesNotAffectProto2Fields() - { - var message = new TestProtos.Proto2.ForeignMessage(); - message.C = 0; - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - var json = formatter.Format(message); - // The specified field is formatted, but the non-specified field (d) is not. - AssertJson("{ 'c': 0 }", json); - } - - [Test] - public void WithFormatDefaultValues_DoesNotAffectOneofFields() - { - var message = new TestOneof(); - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - var json = formatter.Format(message); - AssertJson("{ }", json); - } - - [Test] - public void RepeatedField() - { - AssertJson("{ 'repeatedInt32': [ 1, 2, 3, 4, 5 ] }", - JsonFormatter.Default.Format(new TestAllTypes { RepeatedInt32 = { 1, 2, 3, 4, 5 } })); - } - - [Test] - public void MapField_StringString() - { - AssertJson("{ 'mapStringString': { 'with spaces': 'bar', 'a': 'b' } }", - JsonFormatter.Default.Format(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } })); - } - - [Test] - public void MapField_Int32Int32() - { - // The keys are quoted, but the values aren't. - AssertJson("{ 'mapInt32Int32': { '0': 1, '2': 3 } }", - JsonFormatter.Default.Format(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } })); - } - - [Test] - public void MapField_BoolBool() - { - // The keys are quoted, but the values aren't. - AssertJson("{ 'mapBoolBool': { 'false': true, 'true': false } }", - JsonFormatter.Default.Format(new TestMap { MapBoolBool = { { false, true }, { true, false } } })); - } - - [Test] - public void NullValueOutsideStruct() - { - var message = new NullValueOutsideStruct { NullValue = NullValue.NullValue }; - AssertJson("{ 'nullValue': null }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void NullValueNotInOneof() - { - var message = new NullValueNotInOneof(); - AssertJson("{ }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void NullValueNotInOneof_FormatDefaults() - { - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - var message = new NullValueNotInOneof(); - AssertJson("{ 'nullValue': null }", formatter.Format(message)); - } - - [TestCase(1.0, "1")] - [TestCase(double.NaN, "'NaN'")] - [TestCase(double.PositiveInfinity, "'Infinity'")] - [TestCase(double.NegativeInfinity, "'-Infinity'")] - public void DoubleRepresentations(double value, string expectedValueText) - { - var message = new TestAllTypes { SingleDouble = value }; - string actualText = JsonFormatter.Default.Format(message); - string expectedText = "{ 'singleDouble': " + expectedValueText + " }"; - AssertJson(expectedText, actualText); - } - - [Test] - public void UnknownEnumValueNumeric_SingleField() - { - var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 }; - AssertJson("{ 'singleForeignEnum': 100 }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void UnknownEnumValueNumeric_RepeatedField() - { - var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } }; - AssertJson("{ 'repeatedForeignEnum': [ 'FOREIGN_BAZ', 100, 'FOREIGN_FOO' ] }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void UnknownEnumValueNumeric_MapField() - { - var message = new TestMap { MapInt32Enum = { { 1, MapEnum.Foo }, { 2, (MapEnum) 100 }, { 3, MapEnum.Bar } } }; - AssertJson("{ 'mapInt32Enum': { '1': 'MAP_ENUM_FOO', '2': 100, '3': 'MAP_ENUM_BAR' } }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void UnknownEnumValue_RepeatedField_AllEntriesUnknown() - { - var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } }; - AssertJson("{ 'repeatedForeignEnum': [ 200, 100 ] }", JsonFormatter.Default.Format(message)); - } - - [Test] - [TestCase("a\u17b4b", "a\\u17b4b")] // Explicit - [TestCase("a\u0601b", "a\\u0601b")] // Ranged - [TestCase("a\u0605b", "a\u0605b")] // Passthrough (note lack of double backslash...) - public void SimpleNonAscii(string text, string encoded) - { - var message = new TestAllTypes { SingleString = text }; - AssertJson("{ 'singleString': '" + encoded + "' }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void SurrogatePairEscaping() - { - var message = new TestAllTypes { SingleString = "a\uD801\uDC01b" }; - AssertJson("{ 'singleString': 'a\\ud801\\udc01b' }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void InvalidSurrogatePairsFail() - { - // Note: don't use TestCase for these, as the strings can't be reliably represented - // See http://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/ - - // Lone low surrogate - var message = new TestAllTypes { SingleString = "a\uDC01b" }; - Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message)); - - // Lone high surrogate - message = new TestAllTypes { SingleString = "a\uD801b" }; - Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message)); - } - - [Test] - [TestCase("foo_bar", "fooBar")] - [TestCase("bananaBanana", "bananaBanana")] - [TestCase("BANANABanana", "BANANABanana")] - [TestCase("simple", "simple")] - [TestCase("ACTION_AND_ADVENTURE", "ACTIONANDADVENTURE")] - [TestCase("action_and_adventure", "actionAndAdventure")] - [TestCase("kFoo", "kFoo")] - [TestCase("HTTPServer", "HTTPServer")] - [TestCase("CLIENT", "CLIENT")] - public void ToJsonName(string original, string expected) - { - Assert.AreEqual(expected, JsonFormatter.ToJsonName(original)); - } - - [Test] - [TestCase(null, "{ }")] - [TestCase("x", "{ 'fooString': 'x' }")] - [TestCase("", "{ 'fooString': '' }")] - public void Oneof(string fooStringValue, string expectedJson) - { - var message = new TestOneof(); - if (fooStringValue != null) - { - message.FooString = fooStringValue; - } - - // We should get the same result both with and without "format default values". - var formatter = JsonFormatter.Default; - AssertJson(expectedJson, formatter.Format(message)); - formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - AssertJson(expectedJson, formatter.Format(message)); - } - - [Test] - public void WrapperFormatting_Single() - { - // Just a few examples, handling both classes and value types, and - // default vs non-default values - var message = new TestWellKnownTypes - { - Int64Field = 10, - Int32Field = 0, - BytesField = ByteString.FromBase64("ABCD"), - StringField = "" - }; - var expectedJson = "{ 'int64Field': '10', 'int32Field': 0, 'stringField': '', 'bytesField': 'ABCD' }"; - AssertJson(expectedJson, JsonFormatter.Default.Format(message)); - } - - [Test] - public void WrapperFormatting_Message() - { - Assert.AreEqual("\"\"", JsonFormatter.Default.Format(new StringValue())); - Assert.AreEqual("0", JsonFormatter.Default.Format(new Int32Value())); - } - - [Test] - public void WrapperFormatting_FormatDefaultValuesDoesNotFormatNull() - { - // The actual JSON here is very large because there are lots of fields. Just test a couple of them. - var message = new TestWellKnownTypes { Int32Field = 10 }; - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - var actualJson = formatter.Format(message); - // This *used* to include "int64Field": null, but that was a bug. - // WithDefaultValues should not affect message fields, including wrapper types. - Assert.IsFalse(actualJson.Contains("\"int64Field\": null")); - Assert.IsTrue(actualJson.Contains("\"int32Field\": 10")); - } - - [Test] - public void OutputIsInNumericFieldOrder_NoDefaults() - { - var formatter = JsonFormatter.Default; - var message = new TestJsonFieldOrdering { PlainString = "p1", PlainInt32 = 2 }; - AssertJson("{ 'plainString': 'p1', 'plainInt32': 2 }", formatter.Format(message)); - message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" }; - AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message)); - message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" }; - AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message)); - } - - [Test] - public void OutputIsInNumericFieldOrder_WithDefaults() - { - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); - var message = new TestJsonFieldOrdering(); - AssertJson("{ 'plainString': '', 'plainInt32': 0 }", formatter.Format(message)); - message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" }; - AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message)); - message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" }; - AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message)); - } - - [Test] - [TestCase("1970-01-01T00:00:00Z", 0)] - [TestCase("1970-01-01T00:00:00.000000001Z", 1)] - [TestCase("1970-01-01T00:00:00.000000010Z", 10)] - [TestCase("1970-01-01T00:00:00.000000100Z", 100)] - [TestCase("1970-01-01T00:00:00.000001Z", 1000)] - [TestCase("1970-01-01T00:00:00.000010Z", 10000)] - [TestCase("1970-01-01T00:00:00.000100Z", 100000)] - [TestCase("1970-01-01T00:00:00.001Z", 1000000)] - [TestCase("1970-01-01T00:00:00.010Z", 10000000)] - [TestCase("1970-01-01T00:00:00.100Z", 100000000)] - [TestCase("1970-01-01T00:00:00.120Z", 120000000)] - [TestCase("1970-01-01T00:00:00.123Z", 123000000)] - [TestCase("1970-01-01T00:00:00.123400Z", 123400000)] - [TestCase("1970-01-01T00:00:00.123450Z", 123450000)] - [TestCase("1970-01-01T00:00:00.123456Z", 123456000)] - [TestCase("1970-01-01T00:00:00.123456700Z", 123456700)] - [TestCase("1970-01-01T00:00:00.123456780Z", 123456780)] - [TestCase("1970-01-01T00:00:00.123456789Z", 123456789)] - public void TimestampStandalone(string expected, int nanos) - { - Assert.AreEqual(WrapInQuotes(expected), new Timestamp { Nanos = nanos }.ToString()); - } - - [Test] - public void TimestampStandalone_FromDateTime() - { - // One before and one after the Unix epoch, more easily represented via DateTime. - Assert.AreEqual("\"1673-06-19T12:34:56Z\"", - new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp().ToString()); - Assert.AreEqual("\"2015-07-31T10:29:34Z\"", - new DateTime(2015, 7, 31, 10, 29, 34, DateTimeKind.Utc).ToTimestamp().ToString()); - } - - [Test] - [TestCase(-1, -1)] // Would be valid as duration - [TestCase(1, Timestamp.MaxNanos + 1)] - [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)] - [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, 0)] - public void TimestampStandalone_NonNormalized(long seconds, int nanoseconds) - { - var timestamp = new Timestamp { Seconds = seconds, Nanos = nanoseconds }; - Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(timestamp)); - } - - [Test] - public void TimestampField() - { - var message = new TestWellKnownTypes { TimestampField = new Timestamp() }; - AssertJson("{ 'timestampField': '1970-01-01T00:00:00Z' }", JsonFormatter.Default.Format(message)); - } - - [Test] - [TestCase(0, 0, "0s")] - [TestCase(1, 0, "1s")] - [TestCase(-1, 0, "-1s")] - [TestCase(0, 1, "0.000000001s")] - [TestCase(0, 10, "0.000000010s")] - [TestCase(0, 100, "0.000000100s")] - [TestCase(0, 1000, "0.000001s")] - [TestCase(0, 10000, "0.000010s")] - [TestCase(0, 100000, "0.000100s")] - [TestCase(0, 1000000, "0.001s")] - [TestCase(0, 10000000, "0.010s")] - [TestCase(0, 100000000, "0.100s")] - [TestCase(0, 120000000, "0.120s")] - [TestCase(0, 123000000, "0.123s")] - [TestCase(0, 123400000, "0.123400s")] - [TestCase(0, 123450000, "0.123450s")] - [TestCase(0, 123456000, "0.123456s")] - [TestCase(0, 123456700, "0.123456700s")] - [TestCase(0, 123456780, "0.123456780s")] - [TestCase(0, 123456789, "0.123456789s")] - [TestCase(0, -100000000, "-0.100s")] - [TestCase(1, 100000000, "1.100s")] - [TestCase(-1, -100000000, "-1.100s")] - public void DurationStandalone(long seconds, int nanoseconds, string expected) - { - var json = JsonFormatter.Default.Format(new Duration { Seconds = seconds, Nanos = nanoseconds }); - Assert.AreEqual(WrapInQuotes(expected), json); - } - - [Test] - [TestCase(1, 2123456789)] - [TestCase(1, -100000000)] - public void DurationStandalone_NonNormalized(long seconds, int nanoseconds) - { - var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; - Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(duration)); - } - - [Test] - public void DurationField() - { - var message = new TestWellKnownTypes { DurationField = new Duration() }; - AssertJson("{ 'durationField': '0s' }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void StructSample() - { - var message = new Struct - { - Fields = - { - { "a", Value.ForNull() }, - { "b", Value.ForBool(false) }, - { "c", Value.ForNumber(10.5) }, - { "d", Value.ForString("text") }, - { "e", Value.ForList(Value.ForString("t1"), Value.ForNumber(5)) }, - { "f", Value.ForStruct(new Struct { Fields = { { "nested", Value.ForString("value") } } }) } - } - }; - AssertJson("{ 'a': null, 'b': false, 'c': 10.5, 'd': 'text', 'e': [ 't1', 5 ], 'f': { 'nested': 'value' } }", message.ToString()); - } - - [Test] - [TestCase("foo__bar")] - [TestCase("foo_3_ar")] - [TestCase("fooBar")] - public void FieldMaskInvalid(string input) - { - var mask = new FieldMask { Paths = { input } }; - Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(mask)); - } - - [Test] - public void FieldMaskStandalone() - { - var fieldMask = new FieldMask { Paths = { "", "single", "with_underscore", "nested.field.name", "nested..double_dot" } }; - Assert.AreEqual("\",single,withUnderscore,nested.field.name,nested..doubleDot\"", fieldMask.ToString()); - - // Invalid, but we shouldn't create broken JSON... - fieldMask = new FieldMask { Paths = { "x\\y" } }; - Assert.AreEqual(@"""x\\y""", fieldMask.ToString()); - } - - [Test] - public void FieldMaskField() - { - var message = new TestWellKnownTypes { FieldMaskField = new FieldMask { Paths = { "user.display_name", "photo" } } }; - AssertJson("{ 'fieldMaskField': 'user.displayName,photo' }", JsonFormatter.Default.Format(message)); - } - - // SourceContext is an example of a well-known type with no special JSON handling - [Test] - public void SourceContextStandalone() - { - var message = new SourceContext { FileName = "foo.proto" }; - AssertJson("{ 'fileName': 'foo.proto' }", JsonFormatter.Default.Format(message)); - } - - [Test] - public void AnyWellKnownType() - { - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(Timestamp.Descriptor))); - var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); - var any = Any.Pack(timestamp); - AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any)); - } - - [Test] - public void AnyMessageType() - { - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor))); - var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } }; - var any = Any.Pack(message); - AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any)); - } - - [Test] - public void AnyMessageType_CustomPrefix() - { - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor))); - var message = new TestAllTypes { SingleInt32 = 10 }; - var any = Any.Pack(message, "foo.bar/baz"); - AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest3.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any)); - } - - [Test] - public void AnyNested() - { - var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor); - var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(registry)); - - // Nest an Any as the value of an Any. - var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 }; - var nestedMessage = Any.Pack(doubleNestedMessage); - var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) }; - AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 20 } } }", - formatter.Format(message)); - } - - [Test] - public void AnyUnknownType() - { - // The default type registry doesn't have any types in it. - var message = new TestAllTypes(); - var any = Any.Pack(message); - Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(any)); - } - - [Test] - [TestCase(typeof(BoolValue), true, "true")] - [TestCase(typeof(Int32Value), 32, "32")] - [TestCase(typeof(Int64Value), 32L, "\"32\"")] - [TestCase(typeof(UInt32Value), 32U, "32")] - [TestCase(typeof(UInt64Value), 32UL, "\"32\"")] - [TestCase(typeof(StringValue), "foo", "\"foo\"")] - [TestCase(typeof(FloatValue), 1.5f, "1.5")] - [TestCase(typeof(DoubleValue), 1.5d, "1.5")] - public void Wrappers_Standalone(System.Type wrapperType, object value, string expectedJson) - { - IMessage populated = (IMessage)Activator.CreateInstance(wrapperType); - populated.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(populated, value); - Assert.AreEqual(expectedJson, JsonFormatter.Default.Format(populated)); - } - - // Sanity tests for WriteValue. Not particularly comprehensive, as it's all covered above already, - // as FormatMessage uses WriteValue. - - [TestCase(null, "null")] - [TestCase(1, "1")] - [TestCase(1L, "'1'")] - [TestCase(0.5f, "0.5")] - [TestCase(0.5d, "0.5")] - [TestCase("text", "'text'")] - [TestCase("x\ny", @"'x\ny'")] - [TestCase(ForeignEnum.ForeignBar, "'FOREIGN_BAR'")] - public void WriteValue_Constant(object value, string expectedJson) - { - AssertWriteValue(value, expectedJson); - } - - [Test] - public void WriteValue_Timestamp() - { - var value = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); - AssertWriteValue(value, "'1673-06-19T12:34:56Z'"); - } - - [Test] - public void WriteValue_Message() - { - var value = new TestAllTypes { SingleInt32 = 100, SingleInt64 = 3210987654321L }; - AssertWriteValue(value, "{ 'singleInt32': 100, 'singleInt64': '3210987654321' }"); - } - - [Test] - public void WriteValue_Message_PreserveNames() - { - var value = new TestAllTypes { SingleInt32 = 100, SingleInt64 = 3210987654321L }; - AssertWriteValue(value, "{ 'single_int32': 100, 'single_int64': '3210987654321' }", JsonFormatter.Settings.Default.WithPreserveProtoFieldNames(true)); - } - - [Test] - public void WriteValue_List() - { - var value = new RepeatedField<int> { 1, 2, 3 }; - AssertWriteValue(value, "[ 1, 2, 3 ]"); - } - - [Test] - public void Proto2_DefaultValuesWritten() - { - var value = new ProtobufTestMessages.Proto2.TestAllTypesProto2() { FieldName13 = 0 }; - AssertWriteValue(value, "{ 'FieldName13': 0 }"); - } - - private static void AssertWriteValue(object value, string expectedJson, JsonFormatter.Settings settings = null) - { - var writer = new StringWriter(); - new JsonFormatter(settings ?? JsonFormatter.Settings.Default).WriteValue(writer, value); - string actual = writer.ToString(); - AssertJson(expectedJson, actual); - } - - /// <summary> - /// Checks that the actual JSON is the same as the expected JSON - but after replacing - /// all apostrophes in the expected JSON with double quotes. This basically makes the tests easier - /// to read. - /// </summary> - private static void AssertJson(string expectedJsonWithApostrophes, string actualJson) - { - var expectedJson = expectedJsonWithApostrophes.Replace("'", "\""); - Assert.AreEqual(expectedJson, actualJson); - } - } -} +#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 Google.Protobuf.TestProtos; +using NUnit.Framework; +using UnitTest.Issues.TestProtos; +using Google.Protobuf.WellKnownTypes; +using Google.Protobuf.Reflection; + +using static Google.Protobuf.JsonParserTest; // For WrapInQuotes +using System.IO; +using Google.Protobuf.Collections; +using ProtobufUnittest; + +namespace Google.Protobuf +{ + /// <summary> + /// Tests for the JSON formatter. Note that in these tests, double quotes are replaced with apostrophes + /// for the sake of readability (embedding \" everywhere is painful). See the AssertJson method for details. + /// </summary> + public class JsonFormatterTest + { + [Test] + public void DefaultValues_WhenOmitted() + { + var formatter = JsonFormatter.Default; + + AssertJson("{ }", formatter.Format(new ForeignMessage())); + AssertJson("{ }", formatter.Format(new TestAllTypes())); + AssertJson("{ }", formatter.Format(new TestMap())); + } + + [Test] + public void DefaultValues_WhenIncluded() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + AssertJson("{ 'c': 0 }", formatter.Format(new ForeignMessage())); + } + + [Test] + public void EnumAllowAlias() + { + var message = new TestEnumAllowAlias + { + Value = TestEnumWithDupValue.Foo2, + }; + var actualText = JsonFormatter.Default.Format(message); + var expectedText = "{ 'value': 'FOO1' }"; + AssertJson(expectedText, actualText); + } + + [Test] + public void EnumAsInt() + { + var message = new TestAllTypes + { + SingleForeignEnum = ForeignEnum.ForeignBar, + RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } + }; + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatEnumsAsIntegers(true)); + var actualText = formatter.Format(message); + var expectedText = "{ " + + "'singleForeignEnum': 5, " + + "'repeatedForeignEnum': [ 6, 100, 4 ]" + + " }"; + AssertJson(expectedText, actualText); + } + + [Test] + public void AllSingleFields() + { + var message = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleForeignEnum = ForeignEnum.ForeignBar, + SingleForeignMessage = new ForeignMessage { C = 10 }, + SingleImportEnum = ImportEnum.ImportBaz, + SingleImportMessage = new ImportMessage { D = 20 }, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, + SinglePublicImportMessage = new PublicImportMessage { E = 54 }, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test\twith\ttabs", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue, + }; + var actualText = JsonFormatter.Default.Format(message); + + // Fields in numeric order + var expectedText = "{ " + + "'singleInt32': 100, " + + "'singleInt64': '3210987654321', " + + "'singleUint32': 4294967295, " + + "'singleUint64': '18446744073709551615', " + + "'singleSint32': -456, " + + "'singleSint64': '-12345678901235', " + + "'singleFixed32': 23, " + + "'singleFixed64': '1234567890123', " + + "'singleSfixed32': -123, " + + "'singleSfixed64': '-12345678901234', " + + "'singleFloat': 12.25, " + + "'singleDouble': 23.5, " + + "'singleBool': true, " + + "'singleString': 'test\\twith\\ttabs', " + + "'singleBytes': 'AQIDBA==', " + + "'singleNestedMessage': { 'bb': 35 }, " + + "'singleForeignMessage': { 'c': 10 }, " + + "'singleImportMessage': { 'd': 20 }, " + + "'singleNestedEnum': 'FOO', " + + "'singleForeignEnum': 'FOREIGN_BAR', " + + "'singleImportEnum': 'IMPORT_BAZ', " + + "'singlePublicImportMessage': { 'e': 54 }" + + " }"; + AssertJson(expectedText, actualText); + } + + [Test] + public void WithFormatDefaultValues_DoesNotAffectMessageFields() + { + var message = new TestAllTypes(); + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var json = formatter.Format(message); + Assert.IsFalse(json.Contains("\"singleNestedMessage\"")); + Assert.IsFalse(json.Contains("\"singleForeignMessage\"")); + Assert.IsFalse(json.Contains("\"singleImportMessage\"")); + } + + [Test] + public void WithFormatDefaultValues_DoesNotAffectProto3OptionalFields() + { + var message = new TestProto3Optional(); + message.OptionalInt32 = 0; + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var json = formatter.Format(message); + // The non-optional proto3 fields are formatted, as is the optional-but-specified field. + AssertJson("{ 'optionalInt32': 0, 'singularInt32': 0, 'singularInt64': '0' }", json); + } + + [Test] + public void WithFormatDefaultValues_DoesNotAffectProto2Fields() + { + var message = new TestProtos.Proto2.ForeignMessage(); + message.C = 0; + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var json = formatter.Format(message); + // The specified field is formatted, but the non-specified field (d) is not. + AssertJson("{ 'c': 0 }", json); + } + + [Test] + public void WithFormatDefaultValues_DoesNotAffectOneofFields() + { + var message = new TestOneof(); + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var json = formatter.Format(message); + AssertJson("{ }", json); + } + + [Test] + public void RepeatedField() + { + AssertJson("{ 'repeatedInt32': [ 1, 2, 3, 4, 5 ] }", + JsonFormatter.Default.Format(new TestAllTypes { RepeatedInt32 = { 1, 2, 3, 4, 5 } })); + } + + [Test] + public void MapField_StringString() + { + AssertJson("{ 'mapStringString': { 'with spaces': 'bar', 'a': 'b' } }", + JsonFormatter.Default.Format(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } })); + } + + [Test] + public void MapField_Int32Int32() + { + // The keys are quoted, but the values aren't. + AssertJson("{ 'mapInt32Int32': { '0': 1, '2': 3 } }", + JsonFormatter.Default.Format(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } })); + } + + [Test] + public void MapField_BoolBool() + { + // The keys are quoted, but the values aren't. + AssertJson("{ 'mapBoolBool': { 'false': true, 'true': false } }", + JsonFormatter.Default.Format(new TestMap { MapBoolBool = { { false, true }, { true, false } } })); + } + + [Test] + public void NullValueOutsideStruct() + { + var message = new NullValueOutsideStruct { NullValue = NullValue.NullValue }; + AssertJson("{ 'nullValue': null }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void NullValueNotInOneof() + { + var message = new NullValueNotInOneof(); + AssertJson("{ }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void NullValueNotInOneof_FormatDefaults() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var message = new NullValueNotInOneof(); + AssertJson("{ 'nullValue': null }", formatter.Format(message)); + } + + [TestCase(1.0, "1")] + [TestCase(double.NaN, "'NaN'")] + [TestCase(double.PositiveInfinity, "'Infinity'")] + [TestCase(double.NegativeInfinity, "'-Infinity'")] + public void DoubleRepresentations(double value, string expectedValueText) + { + var message = new TestAllTypes { SingleDouble = value }; + string actualText = JsonFormatter.Default.Format(message); + string expectedText = "{ 'singleDouble': " + expectedValueText + " }"; + AssertJson(expectedText, actualText); + } + + [Test] + public void UnknownEnumValueNumeric_SingleField() + { + var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 }; + AssertJson("{ 'singleForeignEnum': 100 }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void UnknownEnumValueNumeric_RepeatedField() + { + var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } }; + AssertJson("{ 'repeatedForeignEnum': [ 'FOREIGN_BAZ', 100, 'FOREIGN_FOO' ] }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void UnknownEnumValueNumeric_MapField() + { + var message = new TestMap { MapInt32Enum = { { 1, MapEnum.Foo }, { 2, (MapEnum) 100 }, { 3, MapEnum.Bar } } }; + AssertJson("{ 'mapInt32Enum': { '1': 'MAP_ENUM_FOO', '2': 100, '3': 'MAP_ENUM_BAR' } }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void UnknownEnumValue_RepeatedField_AllEntriesUnknown() + { + var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } }; + AssertJson("{ 'repeatedForeignEnum': [ 200, 100 ] }", JsonFormatter.Default.Format(message)); + } + + [Test] + [TestCase("a\u17b4b", "a\\u17b4b")] // Explicit + [TestCase("a\u0601b", "a\\u0601b")] // Ranged + [TestCase("a\u0605b", "a\u0605b")] // Passthrough (note lack of double backslash...) + public void SimpleNonAscii(string text, string encoded) + { + var message = new TestAllTypes { SingleString = text }; + AssertJson("{ 'singleString': '" + encoded + "' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void SurrogatePairEscaping() + { + var message = new TestAllTypes { SingleString = "a\uD801\uDC01b" }; + AssertJson("{ 'singleString': 'a\\ud801\\udc01b' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void InvalidSurrogatePairsFail() + { + // Note: don't use TestCase for these, as the strings can't be reliably represented + // See http://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/ + + // Lone low surrogate + var message = new TestAllTypes { SingleString = "a\uDC01b" }; + Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message)); + + // Lone high surrogate + message = new TestAllTypes { SingleString = "a\uD801b" }; + Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message)); + } + + [Test] + [TestCase("foo_bar", "fooBar")] + [TestCase("bananaBanana", "bananaBanana")] + [TestCase("BANANABanana", "BANANABanana")] + [TestCase("simple", "simple")] + [TestCase("ACTION_AND_ADVENTURE", "ACTIONANDADVENTURE")] + [TestCase("action_and_adventure", "actionAndAdventure")] + [TestCase("kFoo", "kFoo")] + [TestCase("HTTPServer", "HTTPServer")] + [TestCase("CLIENT", "CLIENT")] + public void ToJsonName(string original, string expected) + { + Assert.AreEqual(expected, JsonFormatter.ToJsonName(original)); + } + + [Test] + [TestCase(null, "{ }")] + [TestCase("x", "{ 'fooString': 'x' }")] + [TestCase("", "{ 'fooString': '' }")] + public void Oneof(string fooStringValue, string expectedJson) + { + var message = new TestOneof(); + if (fooStringValue != null) + { + message.FooString = fooStringValue; + } + + // We should get the same result both with and without "format default values". + var formatter = JsonFormatter.Default; + AssertJson(expectedJson, formatter.Format(message)); + formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + AssertJson(expectedJson, formatter.Format(message)); + } + + [Test] + public void WrapperFormatting_Single() + { + // Just a few examples, handling both classes and value types, and + // default vs non-default values + var message = new TestWellKnownTypes + { + Int64Field = 10, + Int32Field = 0, + BytesField = ByteString.FromBase64("ABCD"), + StringField = "" + }; + var expectedJson = "{ 'int64Field': '10', 'int32Field': 0, 'stringField': '', 'bytesField': 'ABCD' }"; + AssertJson(expectedJson, JsonFormatter.Default.Format(message)); + } + + [Test] + public void WrapperFormatting_Message() + { + Assert.AreEqual("\"\"", JsonFormatter.Default.Format(new StringValue())); + Assert.AreEqual("0", JsonFormatter.Default.Format(new Int32Value())); + } + + [Test] + public void WrapperFormatting_FormatDefaultValuesDoesNotFormatNull() + { + // The actual JSON here is very large because there are lots of fields. Just test a couple of them. + var message = new TestWellKnownTypes { Int32Field = 10 }; + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var actualJson = formatter.Format(message); + // This *used* to include "int64Field": null, but that was a bug. + // WithDefaultValues should not affect message fields, including wrapper types. + Assert.IsFalse(actualJson.Contains("\"int64Field\": null")); + Assert.IsTrue(actualJson.Contains("\"int32Field\": 10")); + } + + [Test] + public void OutputIsInNumericFieldOrder_NoDefaults() + { + var formatter = JsonFormatter.Default; + var message = new TestJsonFieldOrdering { PlainString = "p1", PlainInt32 = 2 }; + AssertJson("{ 'plainString': 'p1', 'plainInt32': 2 }", formatter.Format(message)); + message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" }; + AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message)); + message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" }; + AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message)); + } + + [Test] + public void OutputIsInNumericFieldOrder_WithDefaults() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true)); + var message = new TestJsonFieldOrdering(); + AssertJson("{ 'plainString': '', 'plainInt32': 0 }", formatter.Format(message)); + message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" }; + AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message)); + message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" }; + AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message)); + } + + [Test] + [TestCase("1970-01-01T00:00:00Z", 0)] + [TestCase("1970-01-01T00:00:00.000000001Z", 1)] + [TestCase("1970-01-01T00:00:00.000000010Z", 10)] + [TestCase("1970-01-01T00:00:00.000000100Z", 100)] + [TestCase("1970-01-01T00:00:00.000001Z", 1000)] + [TestCase("1970-01-01T00:00:00.000010Z", 10000)] + [TestCase("1970-01-01T00:00:00.000100Z", 100000)] + [TestCase("1970-01-01T00:00:00.001Z", 1000000)] + [TestCase("1970-01-01T00:00:00.010Z", 10000000)] + [TestCase("1970-01-01T00:00:00.100Z", 100000000)] + [TestCase("1970-01-01T00:00:00.120Z", 120000000)] + [TestCase("1970-01-01T00:00:00.123Z", 123000000)] + [TestCase("1970-01-01T00:00:00.123400Z", 123400000)] + [TestCase("1970-01-01T00:00:00.123450Z", 123450000)] + [TestCase("1970-01-01T00:00:00.123456Z", 123456000)] + [TestCase("1970-01-01T00:00:00.123456700Z", 123456700)] + [TestCase("1970-01-01T00:00:00.123456780Z", 123456780)] + [TestCase("1970-01-01T00:00:00.123456789Z", 123456789)] + public void TimestampStandalone(string expected, int nanos) + { + Assert.AreEqual(WrapInQuotes(expected), new Timestamp { Nanos = nanos }.ToString()); + } + + [Test] + public void TimestampStandalone_FromDateTime() + { + // One before and one after the Unix epoch, more easily represented via DateTime. + Assert.AreEqual("\"1673-06-19T12:34:56Z\"", + new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp().ToString()); + Assert.AreEqual("\"2015-07-31T10:29:34Z\"", + new DateTime(2015, 7, 31, 10, 29, 34, DateTimeKind.Utc).ToTimestamp().ToString()); + } + + [Test] + [TestCase(-1, -1)] // Would be valid as duration + [TestCase(1, Timestamp.MaxNanos + 1)] + [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)] + [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, 0)] + public void TimestampStandalone_NonNormalized(long seconds, int nanoseconds) + { + var timestamp = new Timestamp { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(timestamp)); + } + + [Test] + public void TimestampField() + { + var message = new TestWellKnownTypes { TimestampField = new Timestamp() }; + AssertJson("{ 'timestampField': '1970-01-01T00:00:00Z' }", JsonFormatter.Default.Format(message)); + } + + [Test] + [TestCase(0, 0, "0s")] + [TestCase(1, 0, "1s")] + [TestCase(-1, 0, "-1s")] + [TestCase(0, 1, "0.000000001s")] + [TestCase(0, 10, "0.000000010s")] + [TestCase(0, 100, "0.000000100s")] + [TestCase(0, 1000, "0.000001s")] + [TestCase(0, 10000, "0.000010s")] + [TestCase(0, 100000, "0.000100s")] + [TestCase(0, 1000000, "0.001s")] + [TestCase(0, 10000000, "0.010s")] + [TestCase(0, 100000000, "0.100s")] + [TestCase(0, 120000000, "0.120s")] + [TestCase(0, 123000000, "0.123s")] + [TestCase(0, 123400000, "0.123400s")] + [TestCase(0, 123450000, "0.123450s")] + [TestCase(0, 123456000, "0.123456s")] + [TestCase(0, 123456700, "0.123456700s")] + [TestCase(0, 123456780, "0.123456780s")] + [TestCase(0, 123456789, "0.123456789s")] + [TestCase(0, -100000000, "-0.100s")] + [TestCase(1, 100000000, "1.100s")] + [TestCase(-1, -100000000, "-1.100s")] + public void DurationStandalone(long seconds, int nanoseconds, string expected) + { + var json = JsonFormatter.Default.Format(new Duration { Seconds = seconds, Nanos = nanoseconds }); + Assert.AreEqual(WrapInQuotes(expected), json); + } + + [Test] + [TestCase(1, 2123456789)] + [TestCase(1, -100000000)] + public void DurationStandalone_NonNormalized(long seconds, int nanoseconds) + { + var duration = new Duration { Seconds = seconds, Nanos = nanoseconds }; + Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(duration)); + } + + [Test] + public void DurationField() + { + var message = new TestWellKnownTypes { DurationField = new Duration() }; + AssertJson("{ 'durationField': '0s' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void StructSample() + { + var message = new Struct + { + Fields = + { + { "a", Value.ForNull() }, + { "b", Value.ForBool(false) }, + { "c", Value.ForNumber(10.5) }, + { "d", Value.ForString("text") }, + { "e", Value.ForList(Value.ForString("t1"), Value.ForNumber(5)) }, + { "f", Value.ForStruct(new Struct { Fields = { { "nested", Value.ForString("value") } } }) } + } + }; + AssertJson("{ 'a': null, 'b': false, 'c': 10.5, 'd': 'text', 'e': [ 't1', 5 ], 'f': { 'nested': 'value' } }", message.ToString()); + } + + [Test] + [TestCase("foo__bar")] + [TestCase("foo_3_ar")] + [TestCase("fooBar")] + public void FieldMaskInvalid(string input) + { + var mask = new FieldMask { Paths = { input } }; + Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(mask)); + } + + [Test] + public void FieldMaskStandalone() + { + var fieldMask = new FieldMask { Paths = { "", "single", "with_underscore", "nested.field.name", "nested..double_dot" } }; + Assert.AreEqual("\",single,withUnderscore,nested.field.name,nested..doubleDot\"", fieldMask.ToString()); + + // Invalid, but we shouldn't create broken JSON... + fieldMask = new FieldMask { Paths = { "x\\y" } }; + Assert.AreEqual(@"""x\\y""", fieldMask.ToString()); + } + + [Test] + public void FieldMaskField() + { + var message = new TestWellKnownTypes { FieldMaskField = new FieldMask { Paths = { "user.display_name", "photo" } } }; + AssertJson("{ 'fieldMaskField': 'user.displayName,photo' }", JsonFormatter.Default.Format(message)); + } + + // SourceContext is an example of a well-known type with no special JSON handling + [Test] + public void SourceContextStandalone() + { + var message = new SourceContext { FileName = "foo.proto" }; + AssertJson("{ 'fileName': 'foo.proto' }", JsonFormatter.Default.Format(message)); + } + + [Test] + public void AnyWellKnownType() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(Timestamp.Descriptor))); + var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); + var any = Any.Pack(timestamp); + AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any)); + } + + [Test] + public void AnyMessageType() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } }; + var any = Any.Pack(message); + AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any)); + } + + [Test] + public void AnyMessageType_CustomPrefix() + { + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor))); + var message = new TestAllTypes { SingleInt32 = 10 }; + var any = Any.Pack(message, "foo.bar/baz"); + AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest3.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any)); + } + + [Test] + public void AnyNested() + { + var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor); + var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(registry)); + + // Nest an Any as the value of an Any. + var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 }; + var nestedMessage = Any.Pack(doubleNestedMessage); + var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) }; + AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 20 } } }", + formatter.Format(message)); + } + + [Test] + public void AnyUnknownType() + { + // The default type registry doesn't have any types in it. + var message = new TestAllTypes(); + var any = Any.Pack(message); + Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(any)); + } + + [Test] + [TestCase(typeof(BoolValue), true, "true")] + [TestCase(typeof(Int32Value), 32, "32")] + [TestCase(typeof(Int64Value), 32L, "\"32\"")] + [TestCase(typeof(UInt32Value), 32U, "32")] + [TestCase(typeof(UInt64Value), 32UL, "\"32\"")] + [TestCase(typeof(StringValue), "foo", "\"foo\"")] + [TestCase(typeof(FloatValue), 1.5f, "1.5")] + [TestCase(typeof(DoubleValue), 1.5d, "1.5")] + public void Wrappers_Standalone(System.Type wrapperType, object value, string expectedJson) + { + IMessage populated = (IMessage)Activator.CreateInstance(wrapperType); + populated.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(populated, value); + Assert.AreEqual(expectedJson, JsonFormatter.Default.Format(populated)); + } + + // Sanity tests for WriteValue. Not particularly comprehensive, as it's all covered above already, + // as FormatMessage uses WriteValue. + + [TestCase(null, "null")] + [TestCase(1, "1")] + [TestCase(1L, "'1'")] + [TestCase(0.5f, "0.5")] + [TestCase(0.5d, "0.5")] + [TestCase("text", "'text'")] + [TestCase("x\ny", @"'x\ny'")] + [TestCase(ForeignEnum.ForeignBar, "'FOREIGN_BAR'")] + public void WriteValue_Constant(object value, string expectedJson) + { + AssertWriteValue(value, expectedJson); + } + + [Test] + public void WriteValue_Timestamp() + { + var value = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp(); + AssertWriteValue(value, "'1673-06-19T12:34:56Z'"); + } + + [Test] + public void WriteValue_Message() + { + var value = new TestAllTypes { SingleInt32 = 100, SingleInt64 = 3210987654321L }; + AssertWriteValue(value, "{ 'singleInt32': 100, 'singleInt64': '3210987654321' }"); + } + + [Test] + public void WriteValue_Message_PreserveNames() + { + var value = new TestAllTypes { SingleInt32 = 100, SingleInt64 = 3210987654321L }; + AssertWriteValue(value, "{ 'single_int32': 100, 'single_int64': '3210987654321' }", JsonFormatter.Settings.Default.WithPreserveProtoFieldNames(true)); + } + + [Test] + public void WriteValue_List() + { + var value = new RepeatedField<int> { 1, 2, 3 }; + AssertWriteValue(value, "[ 1, 2, 3 ]"); + } + + [Test] + public void Proto2_DefaultValuesWritten() + { + var value = new ProtobufTestMessages.Proto2.TestAllTypesProto2() { FieldName13 = 0 }; + AssertWriteValue(value, "{ 'FieldName13': 0 }"); + } + + private static void AssertWriteValue(object value, string expectedJson, JsonFormatter.Settings settings = null) + { + var writer = new StringWriter(); + new JsonFormatter(settings ?? JsonFormatter.Settings.Default).WriteValue(writer, value); + string actual = writer.ToString(); + AssertJson(expectedJson, actual); + } + + /// <summary> + /// Checks that the actual JSON is the same as the expected JSON - but after replacing + /// all apostrophes in the expected JSON with double quotes. This basically makes the tests easier + /// to read. + /// </summary> + private static void AssertJson(string expectedJsonWithApostrophes, string actualJson) + { + var expectedJson = expectedJsonWithApostrophes.Replace("'", "\""); + Assert.AreEqual(expectedJson, actualJson); + } + } +}
diff --git a/csharp/src/Google.Protobuf.Test/RefStructCompatibilityTest.cs b/csharp/src/Google.Protobuf.Test/RefStructCompatibilityTest.cs index f2d9a2d..9dca501 100644 --- a/csharp/src/Google.Protobuf.Test/RefStructCompatibilityTest.cs +++ b/csharp/src/Google.Protobuf.Test/RefStructCompatibilityTest.cs
@@ -60,7 +60,7 @@ var currentAssemblyDir = Path.GetDirectoryName(typeof(RefStructCompatibilityTest).GetTypeInfo().Assembly.Location); var testProtosProjectDir = Path.GetFullPath(Path.Combine(currentAssemblyDir, "..", "..", "..", "..", "Google.Protobuf.Test.TestProtos")); - var testProtosOutputDir = (currentAssemblyDir.Contains("bin/Debug/") || currentAssemblyDir.Contains("bin\\Debug\\")) ? "bin\\Debug\\net45" : "bin\\Release\\net45"; + var testProtosOutputDir = (currentAssemblyDir.Contains("bin/Debug/") || currentAssemblyDir.Contains("bin\\Debug\\")) ? "bin\\Debug\\net462" : "bin\\Release\\net462"; // If "ref struct" types are used in the generated code, compilation with an old compiler will fail with the following error: // "XYZ is obsolete: 'Types with embedded references are not supported in this version of your compiler.'"
diff --git a/csharp/src/Google.Protobuf.Test/TestCornerCases.cs b/csharp/src/Google.Protobuf.Test/TestCornerCases.cs index 248f5fa..859b49c 100644 --- a/csharp/src/Google.Protobuf.Test/TestCornerCases.cs +++ b/csharp/src/Google.Protobuf.Test/TestCornerCases.cs
@@ -1,62 +1,62 @@ -#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 UnitTest.Issues.TestProtos; -using NUnit.Framework; - -namespace Google.Protobuf -{ - public class TestCornerCases - { - [Test] - public void TestRoundTripNegativeEnums() - { - NegativeEnumMessage msg = new NegativeEnumMessage - { - Value = NegativeEnum.MinusOne, - Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }, - PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow } - }; - - Assert.AreEqual(58, msg.CalculateSize()); - - byte[] bytes = new byte[58]; - CodedOutputStream output = new CodedOutputStream(bytes); - - msg.WriteTo(output); - Assert.AreEqual(0, output.SpaceLeft); - - NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes); - Assert.AreEqual(msg, copy); - } - } -} +#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 UnitTest.Issues.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class TestCornerCases + { + [Test] + public void TestRoundTripNegativeEnums() + { + NegativeEnumMessage msg = new NegativeEnumMessage + { + Value = NegativeEnum.MinusOne, + Values = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }, + PackedValues = { NegativeEnum.Zero, NegativeEnum.MinusOne, NegativeEnum.FiveBelow } + }; + + Assert.AreEqual(58, msg.CalculateSize()); + + byte[] bytes = new byte[58]; + CodedOutputStream output = new CodedOutputStream(bytes); + + msg.WriteTo(output); + Assert.AreEqual(0, output.SpaceLeft); + + NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes); + Assert.AreEqual(msg, copy); + } + } +}
diff --git a/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs b/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs index 4b9a569..c05cb08 100644 --- a/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs +++ b/csharp/src/Google.Protobuf.Test/WellKnownTypes/AnyTest.cs
@@ -1,4 +1,4 @@ -#region Copyright notice and license +#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/ @@ -142,16 +142,16 @@ } [Test] - public void IsWrongType() - { - var any = Any.Pack(SampleMessages.CreateFullTestAllTypes()); - Assert.False(any.Is(TestOneof.Descriptor)); + public void IsWrongType() + { + var any = Any.Pack(SampleMessages.CreateFullTestAllTypes()); + Assert.False(any.Is(TestOneof.Descriptor)); } - public void IsRightType() - { - var any = Any.Pack(SampleMessages.CreateFullTestAllTypes()); - Assert.True(any.Is(TestAllTypes.Descriptor)); + public void IsRightType() + { + var any = Any.Pack(SampleMessages.CreateFullTestAllTypes()); + Assert.True(any.Is(TestAllTypes.Descriptor)); } } }
diff --git a/csharp/src/Google.Protobuf.Test/testprotos.pb b/csharp/src/Google.Protobuf.Test/testprotos.pb index ab60703..b1dfc97 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/ByteArray.cs b/csharp/src/Google.Protobuf/ByteArray.cs index 69b6ef8..094a81e 100644 --- a/csharp/src/Google.Protobuf/ByteArray.cs +++ b/csharp/src/Google.Protobuf/ByteArray.cs
@@ -1,79 +1,79 @@ -#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; - -namespace Google.Protobuf -{ - /// <summary> - /// Provides a utility routine to copy small arrays much more quickly than Buffer.BlockCopy - /// </summary> - internal static class ByteArray - { - /// <summary> - /// The threshold above which you should use Buffer.BlockCopy rather than ByteArray.Copy - /// </summary> - private const int CopyThreshold = 12; - - /// <summary> - /// Determines which copy routine to use based on the number of bytes to be copied. - /// </summary> - internal static void Copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) - { - if (count > CopyThreshold) - { - Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count); - } - else - { - int stop = srcOffset + count; - for (int i = srcOffset; i < stop; i++) - { - dst[dstOffset++] = src[i]; - } - } - } - - /// <summary> - /// Reverses the order of bytes in the array - /// </summary> - internal static void Reverse(byte[] bytes) - { - for (int first = 0, last = bytes.Length - 1; first < last; first++, last--) - { - byte temp = bytes[first]; - bytes[first] = bytes[last]; - bytes[last] = temp; - } - } - } +#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; + +namespace Google.Protobuf +{ + /// <summary> + /// Provides a utility routine to copy small arrays much more quickly than Buffer.BlockCopy + /// </summary> + internal static class ByteArray + { + /// <summary> + /// The threshold above which you should use Buffer.BlockCopy rather than ByteArray.Copy + /// </summary> + private const int CopyThreshold = 12; + + /// <summary> + /// Determines which copy routine to use based on the number of bytes to be copied. + /// </summary> + internal static void Copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) + { + if (count > CopyThreshold) + { + Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count); + } + else + { + int stop = srcOffset + count; + for (int i = srcOffset; i < stop; i++) + { + dst[dstOffset++] = src[i]; + } + } + } + + /// <summary> + /// Reverses the order of bytes in the array + /// </summary> + internal static void Reverse(byte[] bytes) + { + for (int first = 0, last = bytes.Length - 1; first < last; first++, last--) + { + byte temp = bytes[first]; + bytes[first] = bytes[last]; + bytes[last] = temp; + } + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/ByteString.cs b/csharp/src/Google.Protobuf/ByteString.cs index 063b543..8c6eb5b 100644 --- a/csharp/src/Google.Protobuf/ByteString.cs +++ b/csharp/src/Google.Protobuf/ByteString.cs
@@ -1,434 +1,434 @@ -#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.Collections; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; -using System.Security; -using System.Text; -#if !NET35 -using System.Threading; -using System.Threading.Tasks; -#endif -#if NET35 -using Google.Protobuf.Compatibility; -#endif - -namespace Google.Protobuf -{ - /// <summary> - /// Immutable array of bytes. - /// </summary> - [SecuritySafeCritical] - public sealed class ByteString : IEnumerable<byte>, IEquatable<ByteString> - { - private static readonly ByteString empty = new ByteString(new byte[0]); - - private readonly ReadOnlyMemory<byte> bytes; - - /// <summary> - /// Internal use only. Ensure that the provided memory is not mutated and belongs to this instance. - /// </summary> - internal static ByteString AttachBytes(ReadOnlyMemory<byte> bytes) - { - return new ByteString(bytes); - } - - /// <summary> - /// Internal use only. Ensure that the provided memory is not mutated and belongs to this instance. - /// This method encapsulates converting array to memory. Reduces need for SecuritySafeCritical - /// in .NET Framework. - /// </summary> - internal static ByteString AttachBytes(byte[] bytes) - { - return AttachBytes(bytes.AsMemory()); - } - - /// <summary> - /// Constructs a new ByteString from the given memory. The memory is - /// *not* copied, and must not be modified after this constructor is called. - /// </summary> - private ByteString(ReadOnlyMemory<byte> bytes) - { - this.bytes = bytes; - } - - /// <summary> - /// Returns an empty ByteString. - /// </summary> - public static ByteString Empty - { - get { return empty; } - } - - /// <summary> - /// Returns the length of this ByteString in bytes. - /// </summary> - public int Length - { - get { return bytes.Length; } - } - - /// <summary> - /// Returns <c>true</c> if this byte string is empty, <c>false</c> otherwise. - /// </summary> - public bool IsEmpty - { - get { return Length == 0; } - } - - /// <summary> - /// Provides read-only access to the data of this <see cref="ByteString"/>. - /// No data is copied so this is the most efficient way of accessing. - /// </summary> - public ReadOnlySpan<byte> Span - { - get { return bytes.Span; } - } - - /// <summary> - /// Provides read-only access to the data of this <see cref="ByteString"/>. - /// No data is copied so this is the most efficient way of accessing. - /// </summary> - public ReadOnlyMemory<byte> Memory - { - get { return bytes; } - } - - /// <summary> - /// Converts this <see cref="ByteString"/> into a byte array. - /// </summary> - /// <remarks>The data is copied - changes to the returned array will not be reflected in this <c>ByteString</c>.</remarks> - /// <returns>A byte array with the same data as this <c>ByteString</c>.</returns> - public byte[] ToByteArray() - { - return bytes.ToArray(); - } - - /// <summary> - /// Converts this <see cref="ByteString"/> into a standard base64 representation. - /// </summary> - /// <returns>A base64 representation of this <c>ByteString</c>.</returns> - public string ToBase64() - { - if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment)) - { - // Fast path. ByteString was created with an array, so pass the underlying array. - return Convert.ToBase64String(segment.Array, segment.Offset, segment.Count); - } - else - { - // Slow path. BytesString is not an array. Convert memory and pass result to ToBase64String. - return Convert.ToBase64String(bytes.ToArray()); - } - } - - /// <summary> - /// Constructs a <see cref="ByteString" /> from the Base64 Encoded String. - /// </summary> - public static ByteString FromBase64(string bytes) - { - // By handling the empty string explicitly, we not only optimize but we fix a - // problem on CF 2.0. See issue 61 for details. - return bytes == "" ? Empty : new ByteString(Convert.FromBase64String(bytes)); - } - - /// <summary> - /// Constructs a <see cref="ByteString"/> from data in the given stream, synchronously. - /// </summary> - /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position - /// at the start of the call.</remarks> - /// <param name="stream">The stream to copy into a ByteString.</param> - /// <returns>A ByteString with content read from the given stream.</returns> - public static ByteString FromStream(Stream stream) - { - ProtoPreconditions.CheckNotNull(stream, nameof(stream)); - int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0; - var memoryStream = new MemoryStream(capacity); - stream.CopyTo(memoryStream); -#if NETSTANDARD1_1 || NETSTANDARD2_0 - byte[] bytes = memoryStream.ToArray(); -#else - // Avoid an extra copy if we can. - byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray(); -#endif - return AttachBytes(bytes); - } - -#if !NET35 - /// <summary> - /// Constructs a <see cref="ByteString"/> from data in the given stream, asynchronously. - /// </summary> - /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position - /// at the start of the call.</remarks> - /// <param name="stream">The stream to copy into a ByteString.</param> - /// <param name="cancellationToken">The cancellation token to use when reading from the stream, if any.</param> - /// <returns>A ByteString with content read from the given stream.</returns> - public static Task<ByteString> FromStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) - { - ProtoPreconditions.CheckNotNull(stream, nameof(stream)); - return ByteStringAsync.FromStreamAsyncCore(stream, cancellationToken); - } -#endif - - /// <summary> - /// Constructs a <see cref="ByteString" /> from the given array. The contents - /// are copied, so further modifications to the array will not - /// be reflected in the returned ByteString. - /// This method can also be invoked in <c>ByteString.CopyFrom(0xaa, 0xbb, ...)</c> form - /// which is primarily useful for testing. - /// </summary> - public static ByteString CopyFrom(params byte[] bytes) - { - return new ByteString((byte[]) bytes.Clone()); - } - - /// <summary> - /// Constructs a <see cref="ByteString" /> from a portion of a byte array. - /// </summary> - public static ByteString CopyFrom(byte[] bytes, int offset, int count) - { - byte[] portion = new byte[count]; - ByteArray.Copy(bytes, offset, portion, 0, count); - return new ByteString(portion); - } - - /// <summary> - /// Constructs a <see cref="ByteString" /> from a read only span. The contents - /// are copied, so further modifications to the span will not - /// be reflected in the returned <see cref="ByteString" />. - /// </summary> - public static ByteString CopyFrom(ReadOnlySpan<byte> bytes) - { - return new ByteString(bytes.ToArray()); - } - - /// <summary> - /// Creates a new <see cref="ByteString" /> by encoding the specified text with - /// the given encoding. - /// </summary> - public static ByteString CopyFrom(string text, Encoding encoding) - { - return new ByteString(encoding.GetBytes(text)); - } - - /// <summary> - /// Creates a new <see cref="ByteString" /> by encoding the specified text in UTF-8. - /// </summary> - public static ByteString CopyFromUtf8(string text) - { - return CopyFrom(text, Encoding.UTF8); - } - - /// <summary> - /// Returns the byte at the given index. - /// </summary> - public byte this[int index] - { - get { return bytes.Span[index]; } - } - - /// <summary> - /// Converts this <see cref="ByteString"/> into a string by applying the given encoding. - /// </summary> - /// <remarks> - /// This method should only be used to convert binary data which was the result of encoding - /// text with the given encoding. - /// </remarks> - /// <param name="encoding">The encoding to use to decode the binary data into text.</param> - /// <returns>The result of decoding the binary data with the given decoding.</returns> - public string ToString(Encoding encoding) - { - if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment)) - { - // Fast path. ByteString was created with an array. - return encoding.GetString(segment.Array, segment.Offset, segment.Count); - } - else - { - // Slow path. BytesString is not an array. Convert memory and pass result to GetString. - // TODO: Consider using GetString overload that takes a pointer. - byte[] array = bytes.ToArray(); - return encoding.GetString(array, 0, array.Length); - } - } - - /// <summary> - /// Converts this <see cref="ByteString"/> into a string by applying the UTF-8 encoding. - /// </summary> - /// <remarks> - /// This method should only be used to convert binary data which was the result of encoding - /// text with UTF-8. - /// </remarks> - /// <returns>The result of decoding the binary data with the given decoding.</returns> - public string ToStringUtf8() - { - return ToString(Encoding.UTF8); - } - - /// <summary> - /// Returns an iterator over the bytes in this <see cref="ByteString"/>. - /// </summary> - /// <returns>An iterator over the bytes in this object.</returns> - [SecuritySafeCritical] - public IEnumerator<byte> GetEnumerator() - { - return MemoryMarshal.ToEnumerable(bytes).GetEnumerator(); - } - - /// <summary> - /// Returns an iterator over the bytes in this <see cref="ByteString"/>. - /// </summary> - /// <returns>An iterator over the bytes in this object.</returns> - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - /// <summary> - /// Creates a CodedInputStream from this ByteString's data. - /// </summary> - public CodedInputStream CreateCodedInput() - { - // We trust CodedInputStream not to reveal the provided byte array or modify it - if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment) && segment.Count == bytes.Length) - { - // Fast path. ByteString was created with a complete array. - return new CodedInputStream(segment.Array, segment.Offset, segment.Count); - } - else - { - // Slow path. BytesString is not an array, or is a slice of an array. - // Convert memory and pass result to WriteRawBytes. - return new CodedInputStream(bytes.ToArray()); - } - } - - /// <summary> - /// Compares two byte strings for equality. - /// </summary> - /// <param name="lhs">The first byte string to compare.</param> - /// <param name="rhs">The second byte string to compare.</param> - /// <returns><c>true</c> if the byte strings are equal; false otherwise.</returns> - public static bool operator ==(ByteString lhs, ByteString rhs) - { - if (ReferenceEquals(lhs, rhs)) - { - return true; - } - if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null)) - { - return false; - } - - return lhs.bytes.Span.SequenceEqual(rhs.bytes.Span); - } - - /// <summary> - /// Compares two byte strings for inequality. - /// </summary> - /// <param name="lhs">The first byte string to compare.</param> - /// <param name="rhs">The second byte string to compare.</param> - /// <returns><c>false</c> if the byte strings are equal; true otherwise.</returns> - public static bool operator !=(ByteString lhs, ByteString rhs) - { - return !(lhs == rhs); - } - - /// <summary> - /// Compares this byte string with another object. - /// </summary> - /// <param name="obj">The object to compare this with.</param> - /// <returns><c>true</c> if <paramref name="obj"/> refers to an equal <see cref="ByteString"/>; <c>false</c> otherwise.</returns> - [SecuritySafeCritical] - public override bool Equals(object obj) - { - return this == (obj as ByteString); - } - - /// <summary> - /// Returns a hash code for this object. Two equal byte strings - /// will return the same hash code. - /// </summary> - /// <returns>A hash code for this object.</returns> - [SecuritySafeCritical] - public override int GetHashCode() - { - ReadOnlySpan<byte> b = bytes.Span; - - int ret = 23; - for (int i = 0; i < b.Length; i++) - { - ret = (ret * 31) + b[i]; - } - return ret; - } - - /// <summary> - /// Compares this byte string with another. - /// </summary> - /// <param name="other">The <see cref="ByteString"/> to compare this with.</param> - /// <returns><c>true</c> if <paramref name="other"/> refers to an equal byte string; <c>false</c> otherwise.</returns> - public bool Equals(ByteString other) - { - return this == other; - } - - /// <summary> - /// Copies the entire byte array to the destination array provided at the offset specified. - /// </summary> - public void CopyTo(byte[] array, int position) - { - bytes.CopyTo(array.AsMemory(position)); - } - - /// <summary> - /// Writes the entire byte array to the provided stream - /// </summary> - public void WriteTo(Stream outputStream) - { - if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment)) - { - // Fast path. ByteString was created with an array, so pass the underlying array. - outputStream.Write(segment.Array, segment.Offset, segment.Count); - } - else - { - // Slow path. BytesString is not an array. Convert memory and pass result to WriteRawBytes. - var array = bytes.ToArray(); - outputStream.Write(array, 0, array.Length); - } - } - } +#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.Collections; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using System.Text; +#if !NET35 +using System.Threading; +using System.Threading.Tasks; +#endif +#if NET35 +using Google.Protobuf.Compatibility; +#endif + +namespace Google.Protobuf +{ + /// <summary> + /// Immutable array of bytes. + /// </summary> + [SecuritySafeCritical] + public sealed class ByteString : IEnumerable<byte>, IEquatable<ByteString> + { + private static readonly ByteString empty = new ByteString(new byte[0]); + + private readonly ReadOnlyMemory<byte> bytes; + + /// <summary> + /// Internal use only. Ensure that the provided memory is not mutated and belongs to this instance. + /// </summary> + internal static ByteString AttachBytes(ReadOnlyMemory<byte> bytes) + { + return new ByteString(bytes); + } + + /// <summary> + /// Internal use only. Ensure that the provided memory is not mutated and belongs to this instance. + /// This method encapsulates converting array to memory. Reduces need for SecuritySafeCritical + /// in .NET Framework. + /// </summary> + internal static ByteString AttachBytes(byte[] bytes) + { + return AttachBytes(bytes.AsMemory()); + } + + /// <summary> + /// Constructs a new ByteString from the given memory. The memory is + /// *not* copied, and must not be modified after this constructor is called. + /// </summary> + private ByteString(ReadOnlyMemory<byte> bytes) + { + this.bytes = bytes; + } + + /// <summary> + /// Returns an empty ByteString. + /// </summary> + public static ByteString Empty + { + get { return empty; } + } + + /// <summary> + /// Returns the length of this ByteString in bytes. + /// </summary> + public int Length + { + get { return bytes.Length; } + } + + /// <summary> + /// Returns <c>true</c> if this byte string is empty, <c>false</c> otherwise. + /// </summary> + public bool IsEmpty + { + get { return Length == 0; } + } + + /// <summary> + /// Provides read-only access to the data of this <see cref="ByteString"/>. + /// No data is copied so this is the most efficient way of accessing. + /// </summary> + public ReadOnlySpan<byte> Span + { + get { return bytes.Span; } + } + + /// <summary> + /// Provides read-only access to the data of this <see cref="ByteString"/>. + /// No data is copied so this is the most efficient way of accessing. + /// </summary> + public ReadOnlyMemory<byte> Memory + { + get { return bytes; } + } + + /// <summary> + /// Converts this <see cref="ByteString"/> into a byte array. + /// </summary> + /// <remarks>The data is copied - changes to the returned array will not be reflected in this <c>ByteString</c>.</remarks> + /// <returns>A byte array with the same data as this <c>ByteString</c>.</returns> + public byte[] ToByteArray() + { + return bytes.ToArray(); + } + + /// <summary> + /// Converts this <see cref="ByteString"/> into a standard base64 representation. + /// </summary> + /// <returns>A base64 representation of this <c>ByteString</c>.</returns> + public string ToBase64() + { + if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment)) + { + // Fast path. ByteString was created with an array, so pass the underlying array. + return Convert.ToBase64String(segment.Array, segment.Offset, segment.Count); + } + else + { + // Slow path. BytesString is not an array. Convert memory and pass result to ToBase64String. + return Convert.ToBase64String(bytes.ToArray()); + } + } + + /// <summary> + /// Constructs a <see cref="ByteString" /> from the Base64 Encoded String. + /// </summary> + public static ByteString FromBase64(string bytes) + { + // By handling the empty string explicitly, we not only optimize but we fix a + // problem on CF 2.0. See issue 61 for details. + return bytes == "" ? Empty : new ByteString(Convert.FromBase64String(bytes)); + } + + /// <summary> + /// Constructs a <see cref="ByteString"/> from data in the given stream, synchronously. + /// </summary> + /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position + /// at the start of the call.</remarks> + /// <param name="stream">The stream to copy into a ByteString.</param> + /// <returns>A ByteString with content read from the given stream.</returns> + public static ByteString FromStream(Stream stream) + { + ProtoPreconditions.CheckNotNull(stream, nameof(stream)); + int capacity = stream.CanSeek ? checked((int) (stream.Length - stream.Position)) : 0; + var memoryStream = new MemoryStream(capacity); + stream.CopyTo(memoryStream); +#if NETSTANDARD1_1 || NETSTANDARD2_0 + byte[] bytes = memoryStream.ToArray(); +#else + // Avoid an extra copy if we can. + byte[] bytes = memoryStream.Length == memoryStream.Capacity ? memoryStream.GetBuffer() : memoryStream.ToArray(); +#endif + return AttachBytes(bytes); + } + +#if !NET35 + /// <summary> + /// Constructs a <see cref="ByteString"/> from data in the given stream, asynchronously. + /// </summary> + /// <remarks>If successful, <paramref name="stream"/> will be read completely, from the position + /// at the start of the call.</remarks> + /// <param name="stream">The stream to copy into a ByteString.</param> + /// <param name="cancellationToken">The cancellation token to use when reading from the stream, if any.</param> + /// <returns>A ByteString with content read from the given stream.</returns> + public static Task<ByteString> FromStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) + { + ProtoPreconditions.CheckNotNull(stream, nameof(stream)); + return ByteStringAsync.FromStreamAsyncCore(stream, cancellationToken); + } +#endif + + /// <summary> + /// Constructs a <see cref="ByteString" /> from the given array. The contents + /// are copied, so further modifications to the array will not + /// be reflected in the returned ByteString. + /// This method can also be invoked in <c>ByteString.CopyFrom(0xaa, 0xbb, ...)</c> form + /// which is primarily useful for testing. + /// </summary> + public static ByteString CopyFrom(params byte[] bytes) + { + return new ByteString((byte[]) bytes.Clone()); + } + + /// <summary> + /// Constructs a <see cref="ByteString" /> from a portion of a byte array. + /// </summary> + public static ByteString CopyFrom(byte[] bytes, int offset, int count) + { + byte[] portion = new byte[count]; + ByteArray.Copy(bytes, offset, portion, 0, count); + return new ByteString(portion); + } + + /// <summary> + /// Constructs a <see cref="ByteString" /> from a read only span. The contents + /// are copied, so further modifications to the span will not + /// be reflected in the returned <see cref="ByteString" />. + /// </summary> + public static ByteString CopyFrom(ReadOnlySpan<byte> bytes) + { + return new ByteString(bytes.ToArray()); + } + + /// <summary> + /// Creates a new <see cref="ByteString" /> by encoding the specified text with + /// the given encoding. + /// </summary> + public static ByteString CopyFrom(string text, Encoding encoding) + { + return new ByteString(encoding.GetBytes(text)); + } + + /// <summary> + /// Creates a new <see cref="ByteString" /> by encoding the specified text in UTF-8. + /// </summary> + public static ByteString CopyFromUtf8(string text) + { + return CopyFrom(text, Encoding.UTF8); + } + + /// <summary> + /// Returns the byte at the given index. + /// </summary> + public byte this[int index] + { + get { return bytes.Span[index]; } + } + + /// <summary> + /// Converts this <see cref="ByteString"/> into a string by applying the given encoding. + /// </summary> + /// <remarks> + /// This method should only be used to convert binary data which was the result of encoding + /// text with the given encoding. + /// </remarks> + /// <param name="encoding">The encoding to use to decode the binary data into text.</param> + /// <returns>The result of decoding the binary data with the given decoding.</returns> + public string ToString(Encoding encoding) + { + if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment)) + { + // Fast path. ByteString was created with an array. + return encoding.GetString(segment.Array, segment.Offset, segment.Count); + } + else + { + // Slow path. BytesString is not an array. Convert memory and pass result to GetString. + // TODO: Consider using GetString overload that takes a pointer. + byte[] array = bytes.ToArray(); + return encoding.GetString(array, 0, array.Length); + } + } + + /// <summary> + /// Converts this <see cref="ByteString"/> into a string by applying the UTF-8 encoding. + /// </summary> + /// <remarks> + /// This method should only be used to convert binary data which was the result of encoding + /// text with UTF-8. + /// </remarks> + /// <returns>The result of decoding the binary data with the given decoding.</returns> + public string ToStringUtf8() + { + return ToString(Encoding.UTF8); + } + + /// <summary> + /// Returns an iterator over the bytes in this <see cref="ByteString"/>. + /// </summary> + /// <returns>An iterator over the bytes in this object.</returns> + [SecuritySafeCritical] + public IEnumerator<byte> GetEnumerator() + { + return MemoryMarshal.ToEnumerable(bytes).GetEnumerator(); + } + + /// <summary> + /// Returns an iterator over the bytes in this <see cref="ByteString"/>. + /// </summary> + /// <returns>An iterator over the bytes in this object.</returns> + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// <summary> + /// Creates a CodedInputStream from this ByteString's data. + /// </summary> + public CodedInputStream CreateCodedInput() + { + // We trust CodedInputStream not to reveal the provided byte array or modify it + if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment) && segment.Count == bytes.Length) + { + // Fast path. ByteString was created with a complete array. + return new CodedInputStream(segment.Array, segment.Offset, segment.Count); + } + else + { + // Slow path. BytesString is not an array, or is a slice of an array. + // Convert memory and pass result to WriteRawBytes. + return new CodedInputStream(bytes.ToArray()); + } + } + + /// <summary> + /// Compares two byte strings for equality. + /// </summary> + /// <param name="lhs">The first byte string to compare.</param> + /// <param name="rhs">The second byte string to compare.</param> + /// <returns><c>true</c> if the byte strings are equal; false otherwise.</returns> + public static bool operator ==(ByteString lhs, ByteString rhs) + { + if (ReferenceEquals(lhs, rhs)) + { + return true; + } + if (ReferenceEquals(lhs, null) || ReferenceEquals(rhs, null)) + { + return false; + } + + return lhs.bytes.Span.SequenceEqual(rhs.bytes.Span); + } + + /// <summary> + /// Compares two byte strings for inequality. + /// </summary> + /// <param name="lhs">The first byte string to compare.</param> + /// <param name="rhs">The second byte string to compare.</param> + /// <returns><c>false</c> if the byte strings are equal; true otherwise.</returns> + public static bool operator !=(ByteString lhs, ByteString rhs) + { + return !(lhs == rhs); + } + + /// <summary> + /// Compares this byte string with another object. + /// </summary> + /// <param name="obj">The object to compare this with.</param> + /// <returns><c>true</c> if <paramref name="obj"/> refers to an equal <see cref="ByteString"/>; <c>false</c> otherwise.</returns> + [SecuritySafeCritical] + public override bool Equals(object obj) + { + return this == (obj as ByteString); + } + + /// <summary> + /// Returns a hash code for this object. Two equal byte strings + /// will return the same hash code. + /// </summary> + /// <returns>A hash code for this object.</returns> + [SecuritySafeCritical] + public override int GetHashCode() + { + ReadOnlySpan<byte> b = bytes.Span; + + int ret = 23; + for (int i = 0; i < b.Length; i++) + { + ret = (ret * 31) + b[i]; + } + return ret; + } + + /// <summary> + /// Compares this byte string with another. + /// </summary> + /// <param name="other">The <see cref="ByteString"/> to compare this with.</param> + /// <returns><c>true</c> if <paramref name="other"/> refers to an equal byte string; <c>false</c> otherwise.</returns> + public bool Equals(ByteString other) + { + return this == other; + } + + /// <summary> + /// Copies the entire byte array to the destination array provided at the offset specified. + /// </summary> + public void CopyTo(byte[] array, int position) + { + bytes.CopyTo(array.AsMemory(position)); + } + + /// <summary> + /// Writes the entire byte array to the provided stream + /// </summary> + public void WriteTo(Stream outputStream) + { + if (MemoryMarshal.TryGetArray(bytes, out ArraySegment<byte> segment)) + { + // Fast path. ByteString was created with an array, so pass the underlying array. + outputStream.Write(segment.Array, segment.Offset, segment.Count); + } + else + { + // Slow path. BytesString is not an array. Convert memory and pass result to WriteRawBytes. + var array = bytes.ToArray(); + outputStream.Write(array, 0, array.Length); + } + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/CodedInputStream.cs b/csharp/src/Google.Protobuf/CodedInputStream.cs index 27b23c0..912c11f 100644 --- a/csharp/src/Google.Protobuf/CodedInputStream.cs +++ b/csharp/src/Google.Protobuf/CodedInputStream.cs
@@ -1,698 +1,698 @@ -#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.Collections; -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Security; - -namespace Google.Protobuf -{ - /// <summary> - /// Reads and decodes protocol message fields. - /// </summary> - /// <remarks> - /// <para> - /// This class is generally used by generated code to read appropriate - /// primitives from the stream. It effectively encapsulates the lowest - /// levels of protocol buffer format. - /// </para> - /// <para> - /// Repeated fields and map fields are not handled by this class; use <see cref="RepeatedField{T}"/> - /// and <see cref="MapField{TKey, TValue}"/> to serialize such fields. - /// </para> - /// </remarks> - [SecuritySafeCritical] - public sealed class CodedInputStream : IDisposable - { - /// <summary> - /// Whether to leave the underlying stream open when disposing of this stream. - /// This is always true when there's no stream. - /// </summary> - private readonly bool leaveOpen; - - /// <summary> - /// Buffer of data read from the stream or provided at construction time. - /// </summary> - private readonly byte[] buffer; - - /// <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 parser state is kept separately so that other parse implementations can reuse the same - /// parsing primitives. - /// </summary> - private ParserInternalState state; - - internal const int DefaultRecursionLimit = 100; - internal const int DefaultSizeLimit = Int32.MaxValue; - internal const int BufferSize = 4096; - - #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. - - /// <summary> - /// Creates a new CodedInputStream reading data from the given byte array. - /// </summary> - public CodedInputStream(byte[] buffer) : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), 0, buffer.Length, true) - { - } - - /// <summary> - /// Creates a new <see cref="CodedInputStream"/> that reads from the given byte array slice. - /// </summary> - public CodedInputStream(byte[] buffer, int offset, int length) - : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), offset, offset + length, true) - { - if (offset < 0 || offset > buffer.Length) - { - throw new ArgumentOutOfRangeException("offset", "Offset must be within the buffer"); - } - if (length < 0 || offset + length > buffer.Length) - { - throw new ArgumentOutOfRangeException("length", "Length must be non-negative and within the buffer"); - } - } - - /// <summary> - /// Creates a new <see cref="CodedInputStream"/> reading data from the given stream, which will be disposed - /// when the returned object is disposed. - /// </summary> - /// <param name="input">The stream to read from.</param> - public CodedInputStream(Stream input) : this(input, false) - { - } - - /// <summary> - /// Creates a new <see cref="CodedInputStream"/> reading data from the given stream. - /// </summary> - /// <param name="input">The stream to read from.</param> - /// <param name="leaveOpen"><c>true</c> to leave <paramref name="input"/> open when the returned - /// <c cref="CodedInputStream"/> is disposed; <c>false</c> to dispose of the given stream when the - /// returned object is disposed.</param> - public CodedInputStream(Stream input, bool leaveOpen) - : this(ProtoPreconditions.CheckNotNull(input, "input"), new byte[BufferSize], 0, 0, leaveOpen) - { - } - - /// <summary> - /// Creates a new CodedInputStream reading data from the given - /// stream and buffer, using the default limits. - /// </summary> - internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, bool leaveOpen) - { - this.input = input; - this.buffer = buffer; - 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> - /// Creates a new CodedInputStream reading data from the given - /// stream and buffer, using the specified limits. - /// </summary> - /// <remarks> - /// This chains to the version with the default limits instead of vice versa to avoid - /// having to check that the default values are valid every time. - /// </remarks> - internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, int sizeLimit, int recursionLimit, bool leaveOpen) - : this(input, buffer, bufferPos, bufferSize, leaveOpen) - { - if (sizeLimit <= 0) - { - throw new ArgumentOutOfRangeException("sizeLimit", "Size limit must be positive"); - } - if (recursionLimit <= 0) - { - throw new ArgumentOutOfRangeException("recursionLimit!", "Recursion limit must be positive"); - } - this.state.sizeLimit = sizeLimit; - this.state.recursionLimit = recursionLimit; - } - #endregion - - /// <summary> - /// Creates a <see cref="CodedInputStream"/> with the specified size and recursion limits, reading - /// from an input stream. - /// </summary> - /// <remarks> - /// This method exists separately from the constructor to reduce the number of constructor overloads. - /// It is likely to be used considerably less frequently than the constructors, as the default limits - /// are suitable for most use cases. - /// </remarks> - /// <param name="input">The input stream to read from</param> - /// <param name="sizeLimit">The total limit of data to read from the stream.</param> - /// <param name="recursionLimit">The maximum recursion depth to allow while reading.</param> - /// <returns>A <c>CodedInputStream</c> reading from <paramref name="input"/> with the specified size - /// and recursion limits.</returns> - public static CodedInputStream CreateWithLimits(Stream input, int sizeLimit, int recursionLimit) - { - // Note: we may want an overload accepting leaveOpen - return new CodedInputStream(input, new byte[BufferSize], 0, 0, sizeLimit, recursionLimit, false); - } - - /// <summary> - /// Returns the current position in the input stream, or the position in the input buffer - /// </summary> - public long Position - { - get - { - if (input != null) - { - return input.Position - ((state.bufferSize + state.bufferSizeAfterLimit) - state.bufferPos); - } - return state.bufferPos; - } - } - - /// <summary> - /// 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 state.lastTag; } } - - /// <summary> - /// Returns the size limit for this stream. - /// </summary> - /// <remarks> - /// This limit is applied when reading from the underlying stream, as a sanity check. It is - /// not applied when reading from a byte array data source without an underlying stream. - /// The default value is Int32.MaxValue. - /// </remarks> - /// <value> - /// The size limit. - /// </value> - public int SizeLimit { get { return state.sizeLimit; } } - - /// <summary> - /// Returns the recursion limit for this stream. This limit is applied whilst reading messages, - /// to avoid maliciously-recursive data. - /// </summary> - /// <remarks> - /// The default limit is 100. - /// </remarks> - /// <value> - /// The recursion limit for this stream. - /// </value> - 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 { 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; } - } - - internal byte[] InternalBuffer => buffer; - - internal Stream InternalInputStream => input; - - internal ref ParserInternalState InternalState => ref state; - - /// <summary> - /// Disposes of this instance, potentially closing any underlying stream. - /// </summary> - /// <remarks> - /// As there is no flushing to perform here, disposing of a <see cref="CodedInputStream"/> which - /// was constructed with the <c>leaveOpen</c> option parameter set to <c>true</c> (or one which - /// was constructed to read from a byte array) has no effect. - /// </remarks> - public void Dispose() - { - if (!leaveOpen) - { - input.Dispose(); - } - } - - #region Validation - /// <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> - internal void CheckReadEndOfStreamTag() - { - ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref state); - } - #endregion - - #region Reading of tags etc - - /// <summary> - /// Peeks at the next field tag. This is like calling <see cref="ReadTag"/>, but the - /// tag is not consumed. (So a subsequent call to <see cref="ReadTag"/> will return the - /// same value.) - /// </summary> - public uint PeekTag() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.PeekTag(ref span, ref state); - } - - /// <summary> - /// Reads a field tag, returning the tag of 0 for "end of stream". - /// </summary> - /// <remarks> - /// If this method returns 0, it doesn't necessarily mean the end of all - /// the data in this CodedInputStream; it may be the end of the logical stream - /// for an embedded message, for example. - /// </remarks> - /// <returns>The next field tag, or 0 for end of stream. (0 is never a valid tag.)</returns> - public uint ReadTag() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ParseTag(ref span, ref state); - } - - /// <summary> - /// Skips the data for the field with the tag we've just read. - /// This should be called directly after <see cref="ReadTag"/>, when - /// the caller wishes to skip an unknown field. - /// </summary> - /// <remarks> - /// This method throws <see cref="InvalidProtocolBufferException"/> if the last-read tag was an end-group tag. - /// If a caller wishes to skip a group, they should skip the whole group, by calling this method after reading the - /// start-group tag. This behavior allows callers to call this method on any field they don't understand, correctly - /// resulting in an error if an end-group tag has not been paired with an earlier start-group tag. - /// </remarks> - /// <exception cref="InvalidProtocolBufferException">The last tag was an end-group tag</exception> - /// <exception cref="InvalidOperationException">The last read operation read to the end of the logical stream</exception> - public void SkipLastField() - { - var span = new ReadOnlySpan<byte>(buffer); - ParsingPrimitivesMessages.SkipLastField(ref span, ref state); - } - - /// <summary> - /// Skip a group. - /// </summary> - internal void SkipGroup(uint startGroupTag) - { - var span = new ReadOnlySpan<byte>(buffer); - ParsingPrimitivesMessages.SkipGroup(ref span, ref state, startGroupTag); - } - - /// <summary> - /// Reads a double field from the stream. - /// </summary> - public double ReadDouble() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ParseDouble(ref span, ref state); - } - - /// <summary> - /// Reads a float field from the stream. - /// </summary> - public float ReadFloat() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ParseFloat(ref span, ref state); - } - - /// <summary> - /// Reads a uint64 field from the stream. - /// </summary> - public ulong ReadUInt64() - { - return ReadRawVarint64(); - } - - /// <summary> - /// Reads an int64 field from the stream. - /// </summary> - public long ReadInt64() - { - return (long) ReadRawVarint64(); - } - - /// <summary> - /// Reads an int32 field from the stream. - /// </summary> - public int ReadInt32() - { - return (int) ReadRawVarint32(); - } - - /// <summary> - /// Reads a fixed64 field from the stream. - /// </summary> - public ulong ReadFixed64() - { - return ReadRawLittleEndian64(); - } - - /// <summary> - /// Reads a fixed32 field from the stream. - /// </summary> - public uint ReadFixed32() - { - return ReadRawLittleEndian32(); - } - - /// <summary> - /// Reads a bool field from the stream. - /// </summary> - public bool ReadBool() - { - return ReadRawVarint64() != 0; - } - - /// <summary> - /// Reads a string field from the stream. - /// </summary> - public string ReadString() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ReadString(ref span, ref state); - } - - /// <summary> - /// Reads an embedded message field value from the stream. - /// </summary> - public void ReadMessage(IMessage builder) - { - // 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). - ParseContext.Initialize(buffer.AsSpan(), ref state, out ParseContext ctx); - try - { - ParsingPrimitivesMessages.ReadMessage(ref ctx, builder); - } - finally - { - ctx.CopyStateTo(this); - } - } - - /// <summary> - /// Reads an embedded group field from the stream. - /// </summary> - public void ReadGroup(IMessage builder) - { - ParseContext.Initialize(this, out ParseContext ctx); - try - { - ParsingPrimitivesMessages.ReadGroup(ref ctx, builder); - } - finally - { - ctx.CopyStateTo(this); - } - } - - /// <summary> - /// Reads a bytes field value from the stream. - /// </summary> - public ByteString ReadBytes() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ReadBytes(ref span, ref state); - } - - /// <summary> - /// Reads a uint32 field value from the stream. - /// </summary> - public uint ReadUInt32() - { - return ReadRawVarint32(); - } - - /// <summary> - /// Reads an enum field value from the stream. - /// </summary> - public int ReadEnum() - { - // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. - return (int) ReadRawVarint32(); - } - - /// <summary> - /// Reads an sfixed32 field value from the stream. - /// </summary> - public int ReadSFixed32() - { - return (int) ReadRawLittleEndian32(); - } - - /// <summary> - /// Reads an sfixed64 field value from the stream. - /// </summary> - public long ReadSFixed64() - { - return (long) ReadRawLittleEndian64(); - } - - /// <summary> - /// Reads an sint32 field value from the stream. - /// </summary> - public int ReadSInt32() - { - return ParsingPrimitives.DecodeZigZag32(ReadRawVarint32()); - } - - /// <summary> - /// Reads an sint64 field value from the stream. - /// </summary> - public long ReadSInt64() - { - return ParsingPrimitives.DecodeZigZag64(ReadRawVarint64()); - } - - /// <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> - public int ReadLength() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ParseLength(ref span, ref state); - } - - /// <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 bool MaybeConsumeTag(uint tag) - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.MaybeConsumeTag(ref span, ref state, tag); - } - -#endregion - - #region Underlying reading primitives - - /// <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 - /// without constant rechecking of the buffer length. - /// </summary> - internal uint ReadRawVarint32() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ParseRawVarint32(ref span, ref state); - } - - /// <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> - internal static uint ReadRawVarint32(Stream input) - { - return ParsingPrimitives.ReadRawVarint32(input); - } - - /// <summary> - /// Reads a raw varint from the stream. - /// </summary> - internal ulong ReadRawVarint64() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ParseRawVarint64(ref span, ref state); - } - - /// <summary> - /// Reads a 32-bit little-endian integer from the stream. - /// </summary> - internal uint ReadRawLittleEndian32() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ParseRawLittleEndian32(ref span, ref state); - } - - /// <summary> - /// Reads a 64-bit little-endian integer from the stream. - /// </summary> - internal ulong ReadRawLittleEndian64() - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ParseRawLittleEndian64(ref span, ref state); - } - #endregion - - #region Internal reading and buffer management - - /// <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> - internal int PushLimit(int byteLimit) - { - return SegmentedBufferHelper.PushLimit(ref state, byteLimit); - } - - /// <summary> - /// Discards the current limit, returning the previous limit. - /// </summary> - internal void PopLimit(int oldLimit) - { - SegmentedBufferHelper.PopLimit(ref state, oldLimit); - } - - /// <summary> - /// Returns whether or not all the data before the limit has been read. - /// </summary> - /// <returns></returns> - internal bool ReachedLimit - { - get - { - return SegmentedBufferHelper.IsReachedLimit(ref state); - } - } - - /// <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> - public bool IsAtEnd - { - get - { - var span = new ReadOnlySpan<byte>(buffer); - return SegmentedBufferHelper.IsAtEnd(ref span, ref state); - } - } - - /// <summary> - /// Called when buffer is empty to read more bytes from the - /// input. If <paramref name="mustSucceed"/> is true, RefillBuffer() guarantees that - /// either there will be at least one byte in the buffer when it returns - /// or it will throw an exception. If <paramref name="mustSucceed"/> is false, - /// RefillBuffer() returns false if no more bytes were available. - /// </summary> - /// <param name="mustSucceed"></param> - /// <returns></returns> - private bool RefillBuffer(bool mustSucceed) - { - var span = new ReadOnlySpan<byte>(buffer); - return state.segmentedBufferHelper.RefillBuffer(ref span, ref state, mustSucceed); - } - - /// <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> - internal byte[] ReadRawBytes(int size) - { - var span = new ReadOnlySpan<byte>(buffer); - return ParsingPrimitives.ReadRawBytes(ref span, ref state, size); - } - - /// <summary> - /// 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> - public void ReadRawMessage(IMessage message) - { - ParseContext.Initialize(this, out ParseContext ctx); - try - { - ParsingPrimitivesMessages.ReadRawMessage(ref ctx, message); - } - finally - { - ctx.CopyStateTo(this); - } - } -#endregion - } -} +#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.Collections; +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security; + +namespace Google.Protobuf +{ + /// <summary> + /// Reads and decodes protocol message fields. + /// </summary> + /// <remarks> + /// <para> + /// This class is generally used by generated code to read appropriate + /// primitives from the stream. It effectively encapsulates the lowest + /// levels of protocol buffer format. + /// </para> + /// <para> + /// Repeated fields and map fields are not handled by this class; use <see cref="RepeatedField{T}"/> + /// and <see cref="MapField{TKey, TValue}"/> to serialize such fields. + /// </para> + /// </remarks> + [SecuritySafeCritical] + public sealed class CodedInputStream : IDisposable + { + /// <summary> + /// Whether to leave the underlying stream open when disposing of this stream. + /// This is always true when there's no stream. + /// </summary> + private readonly bool leaveOpen; + + /// <summary> + /// Buffer of data read from the stream or provided at construction time. + /// </summary> + private readonly byte[] buffer; + + /// <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 parser state is kept separately so that other parse implementations can reuse the same + /// parsing primitives. + /// </summary> + private ParserInternalState state; + + internal const int DefaultRecursionLimit = 100; + internal const int DefaultSizeLimit = Int32.MaxValue; + internal const int BufferSize = 4096; + + #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. + + /// <summary> + /// Creates a new CodedInputStream reading data from the given byte array. + /// </summary> + public CodedInputStream(byte[] buffer) : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), 0, buffer.Length, true) + { + } + + /// <summary> + /// Creates a new <see cref="CodedInputStream"/> that reads from the given byte array slice. + /// </summary> + public CodedInputStream(byte[] buffer, int offset, int length) + : this(null, ProtoPreconditions.CheckNotNull(buffer, "buffer"), offset, offset + length, true) + { + if (offset < 0 || offset > buffer.Length) + { + throw new ArgumentOutOfRangeException("offset", "Offset must be within the buffer"); + } + if (length < 0 || offset + length > buffer.Length) + { + throw new ArgumentOutOfRangeException("length", "Length must be non-negative and within the buffer"); + } + } + + /// <summary> + /// Creates a new <see cref="CodedInputStream"/> reading data from the given stream, which will be disposed + /// when the returned object is disposed. + /// </summary> + /// <param name="input">The stream to read from.</param> + public CodedInputStream(Stream input) : this(input, false) + { + } + + /// <summary> + /// Creates a new <see cref="CodedInputStream"/> reading data from the given stream. + /// </summary> + /// <param name="input">The stream to read from.</param> + /// <param name="leaveOpen"><c>true</c> to leave <paramref name="input"/> open when the returned + /// <c cref="CodedInputStream"/> is disposed; <c>false</c> to dispose of the given stream when the + /// returned object is disposed.</param> + public CodedInputStream(Stream input, bool leaveOpen) + : this(ProtoPreconditions.CheckNotNull(input, "input"), new byte[BufferSize], 0, 0, leaveOpen) + { + } + + /// <summary> + /// Creates a new CodedInputStream reading data from the given + /// stream and buffer, using the default limits. + /// </summary> + internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, bool leaveOpen) + { + this.input = input; + this.buffer = buffer; + 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> + /// Creates a new CodedInputStream reading data from the given + /// stream and buffer, using the specified limits. + /// </summary> + /// <remarks> + /// This chains to the version with the default limits instead of vice versa to avoid + /// having to check that the default values are valid every time. + /// </remarks> + internal CodedInputStream(Stream input, byte[] buffer, int bufferPos, int bufferSize, int sizeLimit, int recursionLimit, bool leaveOpen) + : this(input, buffer, bufferPos, bufferSize, leaveOpen) + { + if (sizeLimit <= 0) + { + throw new ArgumentOutOfRangeException("sizeLimit", "Size limit must be positive"); + } + if (recursionLimit <= 0) + { + throw new ArgumentOutOfRangeException("recursionLimit!", "Recursion limit must be positive"); + } + this.state.sizeLimit = sizeLimit; + this.state.recursionLimit = recursionLimit; + } + #endregion + + /// <summary> + /// Creates a <see cref="CodedInputStream"/> with the specified size and recursion limits, reading + /// from an input stream. + /// </summary> + /// <remarks> + /// This method exists separately from the constructor to reduce the number of constructor overloads. + /// It is likely to be used considerably less frequently than the constructors, as the default limits + /// are suitable for most use cases. + /// </remarks> + /// <param name="input">The input stream to read from</param> + /// <param name="sizeLimit">The total limit of data to read from the stream.</param> + /// <param name="recursionLimit">The maximum recursion depth to allow while reading.</param> + /// <returns>A <c>CodedInputStream</c> reading from <paramref name="input"/> with the specified size + /// and recursion limits.</returns> + public static CodedInputStream CreateWithLimits(Stream input, int sizeLimit, int recursionLimit) + { + // Note: we may want an overload accepting leaveOpen + return new CodedInputStream(input, new byte[BufferSize], 0, 0, sizeLimit, recursionLimit, false); + } + + /// <summary> + /// Returns the current position in the input stream, or the position in the input buffer + /// </summary> + public long Position + { + get + { + if (input != null) + { + return input.Position - ((state.bufferSize + state.bufferSizeAfterLimit) - state.bufferPos); + } + return state.bufferPos; + } + } + + /// <summary> + /// 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 state.lastTag; } } + + /// <summary> + /// Returns the size limit for this stream. + /// </summary> + /// <remarks> + /// This limit is applied when reading from the underlying stream, as a sanity check. It is + /// not applied when reading from a byte array data source without an underlying stream. + /// The default value is Int32.MaxValue. + /// </remarks> + /// <value> + /// The size limit. + /// </value> + public int SizeLimit { get { return state.sizeLimit; } } + + /// <summary> + /// Returns the recursion limit for this stream. This limit is applied whilst reading messages, + /// to avoid maliciously-recursive data. + /// </summary> + /// <remarks> + /// The default limit is 100. + /// </remarks> + /// <value> + /// The recursion limit for this stream. + /// </value> + 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 { 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; } + } + + internal byte[] InternalBuffer => buffer; + + internal Stream InternalInputStream => input; + + internal ref ParserInternalState InternalState => ref state; + + /// <summary> + /// Disposes of this instance, potentially closing any underlying stream. + /// </summary> + /// <remarks> + /// As there is no flushing to perform here, disposing of a <see cref="CodedInputStream"/> which + /// was constructed with the <c>leaveOpen</c> option parameter set to <c>true</c> (or one which + /// was constructed to read from a byte array) has no effect. + /// </remarks> + public void Dispose() + { + if (!leaveOpen) + { + input.Dispose(); + } + } + + #region Validation + /// <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> + internal void CheckReadEndOfStreamTag() + { + ParsingPrimitivesMessages.CheckReadEndOfStreamTag(ref state); + } + #endregion + + #region Reading of tags etc + + /// <summary> + /// Peeks at the next field tag. This is like calling <see cref="ReadTag"/>, but the + /// tag is not consumed. (So a subsequent call to <see cref="ReadTag"/> will return the + /// same value.) + /// </summary> + public uint PeekTag() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.PeekTag(ref span, ref state); + } + + /// <summary> + /// Reads a field tag, returning the tag of 0 for "end of stream". + /// </summary> + /// <remarks> + /// If this method returns 0, it doesn't necessarily mean the end of all + /// the data in this CodedInputStream; it may be the end of the logical stream + /// for an embedded message, for example. + /// </remarks> + /// <returns>The next field tag, or 0 for end of stream. (0 is never a valid tag.)</returns> + public uint ReadTag() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ParseTag(ref span, ref state); + } + + /// <summary> + /// Skips the data for the field with the tag we've just read. + /// This should be called directly after <see cref="ReadTag"/>, when + /// the caller wishes to skip an unknown field. + /// </summary> + /// <remarks> + /// This method throws <see cref="InvalidProtocolBufferException"/> if the last-read tag was an end-group tag. + /// If a caller wishes to skip a group, they should skip the whole group, by calling this method after reading the + /// start-group tag. This behavior allows callers to call this method on any field they don't understand, correctly + /// resulting in an error if an end-group tag has not been paired with an earlier start-group tag. + /// </remarks> + /// <exception cref="InvalidProtocolBufferException">The last tag was an end-group tag</exception> + /// <exception cref="InvalidOperationException">The last read operation read to the end of the logical stream</exception> + public void SkipLastField() + { + var span = new ReadOnlySpan<byte>(buffer); + ParsingPrimitivesMessages.SkipLastField(ref span, ref state); + } + + /// <summary> + /// Skip a group. + /// </summary> + internal void SkipGroup(uint startGroupTag) + { + var span = new ReadOnlySpan<byte>(buffer); + ParsingPrimitivesMessages.SkipGroup(ref span, ref state, startGroupTag); + } + + /// <summary> + /// Reads a double field from the stream. + /// </summary> + public double ReadDouble() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ParseDouble(ref span, ref state); + } + + /// <summary> + /// Reads a float field from the stream. + /// </summary> + public float ReadFloat() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ParseFloat(ref span, ref state); + } + + /// <summary> + /// Reads a uint64 field from the stream. + /// </summary> + public ulong ReadUInt64() + { + return ReadRawVarint64(); + } + + /// <summary> + /// Reads an int64 field from the stream. + /// </summary> + public long ReadInt64() + { + return (long) ReadRawVarint64(); + } + + /// <summary> + /// Reads an int32 field from the stream. + /// </summary> + public int ReadInt32() + { + return (int) ReadRawVarint32(); + } + + /// <summary> + /// Reads a fixed64 field from the stream. + /// </summary> + public ulong ReadFixed64() + { + return ReadRawLittleEndian64(); + } + + /// <summary> + /// Reads a fixed32 field from the stream. + /// </summary> + public uint ReadFixed32() + { + return ReadRawLittleEndian32(); + } + + /// <summary> + /// Reads a bool field from the stream. + /// </summary> + public bool ReadBool() + { + return ReadRawVarint64() != 0; + } + + /// <summary> + /// Reads a string field from the stream. + /// </summary> + public string ReadString() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ReadString(ref span, ref state); + } + + /// <summary> + /// Reads an embedded message field value from the stream. + /// </summary> + public void ReadMessage(IMessage builder) + { + // 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). + ParseContext.Initialize(buffer.AsSpan(), ref state, out ParseContext ctx); + try + { + ParsingPrimitivesMessages.ReadMessage(ref ctx, builder); + } + finally + { + ctx.CopyStateTo(this); + } + } + + /// <summary> + /// Reads an embedded group field from the stream. + /// </summary> + public void ReadGroup(IMessage builder) + { + ParseContext.Initialize(this, out ParseContext ctx); + try + { + ParsingPrimitivesMessages.ReadGroup(ref ctx, builder); + } + finally + { + ctx.CopyStateTo(this); + } + } + + /// <summary> + /// Reads a bytes field value from the stream. + /// </summary> + public ByteString ReadBytes() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ReadBytes(ref span, ref state); + } + + /// <summary> + /// Reads a uint32 field value from the stream. + /// </summary> + public uint ReadUInt32() + { + return ReadRawVarint32(); + } + + /// <summary> + /// Reads an enum field value from the stream. + /// </summary> + public int ReadEnum() + { + // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. + return (int) ReadRawVarint32(); + } + + /// <summary> + /// Reads an sfixed32 field value from the stream. + /// </summary> + public int ReadSFixed32() + { + return (int) ReadRawLittleEndian32(); + } + + /// <summary> + /// Reads an sfixed64 field value from the stream. + /// </summary> + public long ReadSFixed64() + { + return (long) ReadRawLittleEndian64(); + } + + /// <summary> + /// Reads an sint32 field value from the stream. + /// </summary> + public int ReadSInt32() + { + return ParsingPrimitives.DecodeZigZag32(ReadRawVarint32()); + } + + /// <summary> + /// Reads an sint64 field value from the stream. + /// </summary> + public long ReadSInt64() + { + return ParsingPrimitives.DecodeZigZag64(ReadRawVarint64()); + } + + /// <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> + public int ReadLength() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ParseLength(ref span, ref state); + } + + /// <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 bool MaybeConsumeTag(uint tag) + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.MaybeConsumeTag(ref span, ref state, tag); + } + +#endregion + + #region Underlying reading primitives + + /// <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 + /// without constant rechecking of the buffer length. + /// </summary> + internal uint ReadRawVarint32() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ParseRawVarint32(ref span, ref state); + } + + /// <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> + internal static uint ReadRawVarint32(Stream input) + { + return ParsingPrimitives.ReadRawVarint32(input); + } + + /// <summary> + /// Reads a raw varint from the stream. + /// </summary> + internal ulong ReadRawVarint64() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ParseRawVarint64(ref span, ref state); + } + + /// <summary> + /// Reads a 32-bit little-endian integer from the stream. + /// </summary> + internal uint ReadRawLittleEndian32() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ParseRawLittleEndian32(ref span, ref state); + } + + /// <summary> + /// Reads a 64-bit little-endian integer from the stream. + /// </summary> + internal ulong ReadRawLittleEndian64() + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ParseRawLittleEndian64(ref span, ref state); + } + #endregion + + #region Internal reading and buffer management + + /// <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> + internal int PushLimit(int byteLimit) + { + return SegmentedBufferHelper.PushLimit(ref state, byteLimit); + } + + /// <summary> + /// Discards the current limit, returning the previous limit. + /// </summary> + internal void PopLimit(int oldLimit) + { + SegmentedBufferHelper.PopLimit(ref state, oldLimit); + } + + /// <summary> + /// Returns whether or not all the data before the limit has been read. + /// </summary> + /// <returns></returns> + internal bool ReachedLimit + { + get + { + return SegmentedBufferHelper.IsReachedLimit(ref state); + } + } + + /// <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> + public bool IsAtEnd + { + get + { + var span = new ReadOnlySpan<byte>(buffer); + return SegmentedBufferHelper.IsAtEnd(ref span, ref state); + } + } + + /// <summary> + /// Called when buffer is empty to read more bytes from the + /// input. If <paramref name="mustSucceed"/> is true, RefillBuffer() guarantees that + /// either there will be at least one byte in the buffer when it returns + /// or it will throw an exception. If <paramref name="mustSucceed"/> is false, + /// RefillBuffer() returns false if no more bytes were available. + /// </summary> + /// <param name="mustSucceed"></param> + /// <returns></returns> + private bool RefillBuffer(bool mustSucceed) + { + var span = new ReadOnlySpan<byte>(buffer); + return state.segmentedBufferHelper.RefillBuffer(ref span, ref state, mustSucceed); + } + + /// <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> + internal byte[] ReadRawBytes(int size) + { + var span = new ReadOnlySpan<byte>(buffer); + return ParsingPrimitives.ReadRawBytes(ref span, ref state, size); + } + + /// <summary> + /// 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> + public void ReadRawMessage(IMessage message) + { + ParseContext.Initialize(this, out ParseContext ctx); + try + { + ParsingPrimitivesMessages.ReadRawMessage(ref ctx, message); + } + finally + { + ctx.CopyStateTo(this); + } + } +#endregion + } +}
diff --git a/csharp/src/Google.Protobuf/CodedOutputStream.ComputeSize.cs b/csharp/src/Google.Protobuf/CodedOutputStream.ComputeSize.cs index cb92354..6f18afb 100644 --- a/csharp/src/Google.Protobuf/CodedOutputStream.ComputeSize.cs +++ b/csharp/src/Google.Protobuf/CodedOutputStream.ComputeSize.cs
@@ -1,308 +1,308 @@ -#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; - -namespace Google.Protobuf -{ - // This part of CodedOutputStream provides all the static entry points that are used - // by generated code and internally to compute the size of messages prior to being - // written to an instance of CodedOutputStream. - public sealed partial class CodedOutputStream - { - private const int LittleEndian64Size = 8; - private const int LittleEndian32Size = 4; - - internal const int DoubleSize = LittleEndian64Size; - internal const int FloatSize = LittleEndian32Size; - internal const int BoolSize = 1; - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// double field, including the tag. - /// </summary> - public static int ComputeDoubleSize(double value) - { - return DoubleSize; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// float field, including the tag. - /// </summary> - public static int ComputeFloatSize(float value) - { - return FloatSize; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// uint64 field, including the tag. - /// </summary> - public static int ComputeUInt64Size(ulong value) - { - return ComputeRawVarint64Size(value); - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode an - /// int64 field, including the tag. - /// </summary> - public static int ComputeInt64Size(long value) - { - return ComputeRawVarint64Size((ulong) value); - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode an - /// int32 field, including the tag. - /// </summary> - public static int ComputeInt32Size(int value) - { - if (value >= 0) - { - return ComputeRawVarint32Size((uint) value); - } - else - { - // Must sign-extend. - return 10; - } - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// fixed64 field, including the tag. - /// </summary> - public static int ComputeFixed64Size(ulong value) - { - return LittleEndian64Size; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// fixed32 field, including the tag. - /// </summary> - public static int ComputeFixed32Size(uint value) - { - return LittleEndian32Size; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// bool field, including the tag. - /// </summary> - public static int ComputeBoolSize(bool value) - { - return BoolSize; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// string field, including the tag. - /// </summary> - public static int ComputeStringSize(String value) - { - int byteArraySize = WritingPrimitives.Utf8Encoding.GetByteCount(value); - return ComputeLengthSize(byteArraySize) + byteArraySize; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// group field, including the tag. - /// </summary> - public static int ComputeGroupSize(IMessage value) - { - return value.CalculateSize(); - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode an - /// embedded message field, including the tag. - /// </summary> - public static int ComputeMessageSize(IMessage value) - { - int size = value.CalculateSize(); - return ComputeLengthSize(size) + size; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// bytes field, including the tag. - /// </summary> - public static int ComputeBytesSize(ByteString value) - { - return ComputeLengthSize(value.Length) + value.Length; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// uint32 field, including the tag. - /// </summary> - public static int ComputeUInt32Size(uint value) - { - return ComputeRawVarint32Size(value); - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a - /// enum field, including the tag. The caller is responsible for - /// converting the enum value to its numeric value. - /// </summary> - public static int ComputeEnumSize(int value) - { - // Currently just a pass-through, but it's nice to separate it logically. - return ComputeInt32Size(value); - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode an - /// sfixed32 field, including the tag. - /// </summary> - public static int ComputeSFixed32Size(int value) - { - return LittleEndian32Size; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode an - /// sfixed64 field, including the tag. - /// </summary> - public static int ComputeSFixed64Size(long value) - { - return LittleEndian64Size; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode an - /// sint32 field, including the tag. - /// </summary> - public static int ComputeSInt32Size(int value) - { - return ComputeRawVarint32Size(WritingPrimitives.EncodeZigZag32(value)); - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode an - /// sint64 field, including the tag. - /// </summary> - public static int ComputeSInt64Size(long value) - { - return ComputeRawVarint64Size(WritingPrimitives.EncodeZigZag64(value)); - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a length, - /// as written by <see cref="WriteLength"/>. - /// </summary> - public static int ComputeLengthSize(int length) - { - return ComputeRawVarint32Size((uint) length); - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a varint. - /// </summary> - public static int ComputeRawVarint32Size(uint value) - { - if ((value & (0xffffffff << 7)) == 0) - { - return 1; - } - if ((value & (0xffffffff << 14)) == 0) - { - return 2; - } - if ((value & (0xffffffff << 21)) == 0) - { - return 3; - } - if ((value & (0xffffffff << 28)) == 0) - { - return 4; - } - return 5; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a varint. - /// </summary> - public static int ComputeRawVarint64Size(ulong value) - { - if ((value & (0xffffffffffffffffL << 7)) == 0) - { - return 1; - } - if ((value & (0xffffffffffffffffL << 14)) == 0) - { - return 2; - } - if ((value & (0xffffffffffffffffL << 21)) == 0) - { - return 3; - } - if ((value & (0xffffffffffffffffL << 28)) == 0) - { - return 4; - } - if ((value & (0xffffffffffffffffL << 35)) == 0) - { - return 5; - } - if ((value & (0xffffffffffffffffL << 42)) == 0) - { - return 6; - } - if ((value & (0xffffffffffffffffL << 49)) == 0) - { - return 7; - } - if ((value & (0xffffffffffffffffL << 56)) == 0) - { - return 8; - } - if ((value & (0xffffffffffffffffL << 63)) == 0) - { - return 9; - } - return 10; - } - - /// <summary> - /// Computes the number of bytes that would be needed to encode a tag. - /// </summary> - public static int ComputeTagSize(int fieldNumber) - { - return ComputeRawVarint32Size(WireFormat.MakeTag(fieldNumber, 0)); - } - } +#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; + +namespace Google.Protobuf +{ + // This part of CodedOutputStream provides all the static entry points that are used + // by generated code and internally to compute the size of messages prior to being + // written to an instance of CodedOutputStream. + public sealed partial class CodedOutputStream + { + private const int LittleEndian64Size = 8; + private const int LittleEndian32Size = 4; + + internal const int DoubleSize = LittleEndian64Size; + internal const int FloatSize = LittleEndian32Size; + internal const int BoolSize = 1; + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// double field, including the tag. + /// </summary> + public static int ComputeDoubleSize(double value) + { + return DoubleSize; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// float field, including the tag. + /// </summary> + public static int ComputeFloatSize(float value) + { + return FloatSize; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// uint64 field, including the tag. + /// </summary> + public static int ComputeUInt64Size(ulong value) + { + return ComputeRawVarint64Size(value); + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode an + /// int64 field, including the tag. + /// </summary> + public static int ComputeInt64Size(long value) + { + return ComputeRawVarint64Size((ulong) value); + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode an + /// int32 field, including the tag. + /// </summary> + public static int ComputeInt32Size(int value) + { + if (value >= 0) + { + return ComputeRawVarint32Size((uint) value); + } + else + { + // Must sign-extend. + return 10; + } + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// fixed64 field, including the tag. + /// </summary> + public static int ComputeFixed64Size(ulong value) + { + return LittleEndian64Size; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// fixed32 field, including the tag. + /// </summary> + public static int ComputeFixed32Size(uint value) + { + return LittleEndian32Size; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// bool field, including the tag. + /// </summary> + public static int ComputeBoolSize(bool value) + { + return BoolSize; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// string field, including the tag. + /// </summary> + public static int ComputeStringSize(String value) + { + int byteArraySize = WritingPrimitives.Utf8Encoding.GetByteCount(value); + return ComputeLengthSize(byteArraySize) + byteArraySize; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// group field, including the tag. + /// </summary> + public static int ComputeGroupSize(IMessage value) + { + return value.CalculateSize(); + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode an + /// embedded message field, including the tag. + /// </summary> + public static int ComputeMessageSize(IMessage value) + { + int size = value.CalculateSize(); + return ComputeLengthSize(size) + size; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// bytes field, including the tag. + /// </summary> + public static int ComputeBytesSize(ByteString value) + { + return ComputeLengthSize(value.Length) + value.Length; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// uint32 field, including the tag. + /// </summary> + public static int ComputeUInt32Size(uint value) + { + return ComputeRawVarint32Size(value); + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a + /// enum field, including the tag. The caller is responsible for + /// converting the enum value to its numeric value. + /// </summary> + public static int ComputeEnumSize(int value) + { + // Currently just a pass-through, but it's nice to separate it logically. + return ComputeInt32Size(value); + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode an + /// sfixed32 field, including the tag. + /// </summary> + public static int ComputeSFixed32Size(int value) + { + return LittleEndian32Size; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode an + /// sfixed64 field, including the tag. + /// </summary> + public static int ComputeSFixed64Size(long value) + { + return LittleEndian64Size; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode an + /// sint32 field, including the tag. + /// </summary> + public static int ComputeSInt32Size(int value) + { + return ComputeRawVarint32Size(WritingPrimitives.EncodeZigZag32(value)); + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode an + /// sint64 field, including the tag. + /// </summary> + public static int ComputeSInt64Size(long value) + { + return ComputeRawVarint64Size(WritingPrimitives.EncodeZigZag64(value)); + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a length, + /// as written by <see cref="WriteLength"/>. + /// </summary> + public static int ComputeLengthSize(int length) + { + return ComputeRawVarint32Size((uint) length); + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a varint. + /// </summary> + public static int ComputeRawVarint32Size(uint value) + { + if ((value & (0xffffffff << 7)) == 0) + { + return 1; + } + if ((value & (0xffffffff << 14)) == 0) + { + return 2; + } + if ((value & (0xffffffff << 21)) == 0) + { + return 3; + } + if ((value & (0xffffffff << 28)) == 0) + { + return 4; + } + return 5; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a varint. + /// </summary> + public static int ComputeRawVarint64Size(ulong value) + { + if ((value & (0xffffffffffffffffL << 7)) == 0) + { + return 1; + } + if ((value & (0xffffffffffffffffL << 14)) == 0) + { + return 2; + } + if ((value & (0xffffffffffffffffL << 21)) == 0) + { + return 3; + } + if ((value & (0xffffffffffffffffL << 28)) == 0) + { + return 4; + } + if ((value & (0xffffffffffffffffL << 35)) == 0) + { + return 5; + } + if ((value & (0xffffffffffffffffL << 42)) == 0) + { + return 6; + } + if ((value & (0xffffffffffffffffL << 49)) == 0) + { + return 7; + } + if ((value & (0xffffffffffffffffL << 56)) == 0) + { + return 8; + } + if ((value & (0xffffffffffffffffL << 63)) == 0) + { + return 9; + } + return 10; + } + + /// <summary> + /// Computes the number of bytes that would be needed to encode a tag. + /// </summary> + public static int ComputeTagSize(int fieldNumber) + { + return ComputeRawVarint32Size(WireFormat.MakeTag(fieldNumber, 0)); + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/CodedOutputStream.cs b/csharp/src/Google.Protobuf/CodedOutputStream.cs index 20d88ea..5b8cca1 100644 --- a/csharp/src/Google.Protobuf/CodedOutputStream.cs +++ b/csharp/src/Google.Protobuf/CodedOutputStream.cs
@@ -1,607 +1,607 @@ -#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.Collections; -using System; -using System.IO; -using System.Security; -using System.Text; - -namespace Google.Protobuf -{ - /// <summary> - /// Encodes and writes protocol message fields. - /// </summary> - /// <remarks> - /// <para> - /// This class is generally used by generated code to write appropriate - /// primitives to the stream. It effectively encapsulates the lowest - /// levels of protocol buffer format. Unlike some other implementations, - /// this does not include combined "write tag and value" methods. Generated - /// code knows the exact byte representations of the tags they're going to write, - /// so there's no need to re-encode them each time. Manually-written code calling - /// this class should just call one of the <c>WriteTag</c> overloads before each value. - /// </para> - /// <para> - /// Repeated fields and map fields are not handled by this class; use <c>RepeatedField<T></c> - /// and <c>MapField<TKey, TValue></c> to serialize such fields. - /// </para> - /// </remarks> - [SecuritySafeCritical] - public sealed partial class CodedOutputStream : IDisposable - { - /// <summary> - /// The buffer size used by CreateInstance(Stream). - /// </summary> - public static readonly int DefaultBufferSize = 4096; - - private readonly bool leaveOpen; - private readonly byte[] buffer; - private WriterInternalState state; - - private readonly Stream output; - - #region Construction - /// <summary> - /// Creates a new CodedOutputStream that writes directly to the given - /// byte array. If more bytes are written than fit in the array, - /// OutOfSpaceException will be thrown. - /// </summary> - public CodedOutputStream(byte[] flatArray) : this(flatArray, 0, flatArray.Length) - { - } - - /// <summary> - /// Creates a new CodedOutputStream that writes directly to the given - /// byte array slice. If more bytes are written than fit in the array, - /// OutOfSpaceException will be thrown. - /// </summary> - private CodedOutputStream(byte[] buffer, int offset, int length) - { - this.output = null; - this.buffer = ProtoPreconditions.CheckNotNull(buffer, nameof(buffer)); - this.state.position = offset; - this.state.limit = offset + length; - WriteBufferHelper.Initialize(this, out this.state.writeBufferHelper); - leaveOpen = true; // Simple way of avoiding trying to dispose of a null reference - } - - private CodedOutputStream(Stream output, byte[] buffer, bool leaveOpen) - { - this.output = ProtoPreconditions.CheckNotNull(output, nameof(output)); - this.buffer = buffer; - this.state.position = 0; - this.state.limit = buffer.Length; - WriteBufferHelper.Initialize(this, out this.state.writeBufferHelper); - this.leaveOpen = leaveOpen; - } - - /// <summary> - /// Creates a new <see cref="CodedOutputStream" /> which write to the given stream, and disposes of that - /// stream when the returned <c>CodedOutputStream</c> is disposed. - /// </summary> - /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param> - public CodedOutputStream(Stream output) : this(output, DefaultBufferSize, false) - { - } - - /// <summary> - /// Creates a new CodedOutputStream which write to the given stream and uses - /// the specified buffer size. - /// </summary> - /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param> - /// <param name="bufferSize">The size of buffer to use internally.</param> - public CodedOutputStream(Stream output, int bufferSize) : this(output, new byte[bufferSize], false) - { - } - - /// <summary> - /// Creates a new CodedOutputStream which write to the given stream. - /// </summary> - /// <param name="output">The stream to write to.</param> - /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed; - /// if <c>false</c>, the provided stream is disposed as well.</param> - public CodedOutputStream(Stream output, bool leaveOpen) : this(output, DefaultBufferSize, leaveOpen) - { - } - - /// <summary> - /// Creates a new CodedOutputStream which write to the given stream and uses - /// the specified buffer size. - /// </summary> - /// <param name="output">The stream to write to.</param> - /// <param name="bufferSize">The size of buffer to use internally.</param> - /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed; - /// if <c>false</c>, the provided stream is disposed as well.</param> - public CodedOutputStream(Stream output, int bufferSize, bool leaveOpen) : this(output, new byte[bufferSize], leaveOpen) - { - } - #endregion - - /// <summary> - /// Returns the current position in the stream, or the position in the output buffer - /// </summary> - public long Position - { - get - { - if (output != null) - { - return output.Position + state.position; - } - return state.position; - } - } - - #region Writing of values (not including tags) - - /// <summary> - /// Writes a double field value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteDouble(double value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteDouble(ref span, ref state, value); - } - - /// <summary> - /// Writes a float field value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteFloat(float value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteFloat(ref span, ref state, value); - } - - /// <summary> - /// Writes a uint64 field value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteUInt64(ulong value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteUInt64(ref span, ref state, value); - } - - /// <summary> - /// Writes an int64 field value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteInt64(long value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteInt64(ref span, ref state, value); - } - - /// <summary> - /// Writes an int32 field value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteInt32(int value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteInt32(ref span, ref state, value); - } - - /// <summary> - /// Writes a fixed64 field value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteFixed64(ulong value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteFixed64(ref span, ref state, value); - } - - /// <summary> - /// Writes a fixed32 field value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteFixed32(uint value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteFixed32(ref span, ref state, value); - } - - /// <summary> - /// Writes a bool field value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteBool(bool value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteBool(ref span, ref state, value); - } - - /// <summary> - /// Writes a string field value, without a tag, to the stream. - /// The data is length-prefixed. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteString(string value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteString(ref span, ref state, value); - } - - /// <summary> - /// Writes a message, without a tag, to the stream. - /// The data is length-prefixed. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteMessage(IMessage value) - { - // TODO(jtattermusch): if the message doesn't implement IBufferMessage (and thus does not provide the InternalWriteTo method), - // what we're doing here works fine, but could be more efficient. - // For now, this inefficiency is fine, considering this is only a backward-compatibility scenario (and regenerating the code fixes it). - var span = new Span<byte>(buffer); - WriteContext.Initialize(ref span, ref state, out WriteContext ctx); - try - { - WritingPrimitivesMessages.WriteMessage(ref ctx, value); - } - finally - { - ctx.CopyStateTo(this); - } - } - - /// <summary> - /// Writes a message, without a tag, to the stream. - /// Only the message data is written, without a length-delimiter. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteRawMessage(IMessage value) - { - // TODO(jtattermusch): if the message doesn't implement IBufferMessage (and thus does not provide the InternalWriteTo method), - // what we're doing here works fine, but could be more efficient. - // For now, this inefficiency is fine, considering this is only a backward-compatibility scenario (and regenerating the code fixes it). - var span = new Span<byte>(buffer); - WriteContext.Initialize(ref span, ref state, out WriteContext ctx); - try - { - WritingPrimitivesMessages.WriteRawMessage(ref ctx, value); - } - finally - { - ctx.CopyStateTo(this); - } - } - - /// <summary> - /// Writes a group, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteGroup(IMessage value) - { - var span = new Span<byte>(buffer); - WriteContext.Initialize(ref span, ref state, out WriteContext ctx); - try - { - WritingPrimitivesMessages.WriteGroup(ref ctx, value); - } - finally - { - ctx.CopyStateTo(this); - } - } - - /// <summary> - /// Write a byte string, without a tag, to the stream. - /// The data is length-prefixed. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteBytes(ByteString value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteBytes(ref span, ref state, value); - } - - /// <summary> - /// Writes a uint32 value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteUInt32(uint value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteUInt32(ref span, ref state, value); - } - - /// <summary> - /// Writes an enum value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteEnum(int value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteEnum(ref span, ref state, value); - } - - /// <summary> - /// Writes an sfixed32 value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write.</param> - public void WriteSFixed32(int value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteSFixed32(ref span, ref state, value); - } - - /// <summary> - /// Writes an sfixed64 value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteSFixed64(long value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteSFixed64(ref span, ref state, value); - } - - /// <summary> - /// Writes an sint32 value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteSInt32(int value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteSInt32(ref span, ref state, value); - } - - /// <summary> - /// Writes an sint64 value, without a tag, to the stream. - /// </summary> - /// <param name="value">The value to write</param> - public void WriteSInt64(long value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteSInt64(ref span, ref state, value); - } - - /// <summary> - /// Writes a length (in bytes) for length-delimited data. - /// </summary> - /// <remarks> - /// This method simply writes a rawint, but exists for clarity in calling code. - /// </remarks> - /// <param name="length">Length value, in bytes.</param> - public void WriteLength(int length) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteLength(ref span, ref state, length); - } - - #endregion - - #region Raw tag writing - /// <summary> - /// Encodes and writes a tag. - /// </summary> - /// <param name="fieldNumber">The number of the field to write the tag for</param> - /// <param name="type">The wire format type of the tag to write</param> - public void WriteTag(int fieldNumber, WireFormat.WireType type) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteTag(ref span, ref state, fieldNumber, type); - } - - /// <summary> - /// Writes an already-encoded tag. - /// </summary> - /// <param name="tag">The encoded tag</param> - public void WriteTag(uint tag) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteTag(ref span, ref state, tag); - } - - /// <summary> - /// Writes the given single-byte tag directly to the stream. - /// </summary> - /// <param name="b1">The encoded tag</param> - public void WriteRawTag(byte b1) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawTag(ref span, ref state, b1); - } - - /// <summary> - /// Writes the given two-byte tag directly to the stream. - /// </summary> - /// <param name="b1">The first byte of the encoded tag</param> - /// <param name="b2">The second byte of the encoded tag</param> - public void WriteRawTag(byte b1, byte b2) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2); - } - - /// <summary> - /// Writes the given three-byte tag directly to the stream. - /// </summary> - /// <param name="b1">The first byte of the encoded tag</param> - /// <param name="b2">The second byte of the encoded tag</param> - /// <param name="b3">The third byte of the encoded tag</param> - public void WriteRawTag(byte b1, byte b2, byte b3) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3); - } - - /// <summary> - /// Writes the given four-byte tag directly to the stream. - /// </summary> - /// <param name="b1">The first byte of the encoded tag</param> - /// <param name="b2">The second byte of the encoded tag</param> - /// <param name="b3">The third byte of the encoded tag</param> - /// <param name="b4">The fourth byte of the encoded tag</param> - public void WriteRawTag(byte b1, byte b2, byte b3, byte b4) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3, b4); - } - - /// <summary> - /// Writes the given five-byte tag directly to the stream. - /// </summary> - /// <param name="b1">The first byte of the encoded tag</param> - /// <param name="b2">The second byte of the encoded tag</param> - /// <param name="b3">The third byte of the encoded tag</param> - /// <param name="b4">The fourth byte of the encoded tag</param> - /// <param name="b5">The fifth byte of the encoded tag</param> - public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3, b4, b5); - } - #endregion - - #region Underlying writing primitives - - /// <summary> - /// Writes a 32 bit value as a varint. The fast route is taken when - /// there's enough buffer space left to whizz through without checking - /// for each byte; otherwise, we resort to calling WriteRawByte each time. - /// </summary> - internal void WriteRawVarint32(uint value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawVarint32(ref span, ref state, value); - } - - internal void WriteRawVarint64(ulong value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawVarint64(ref span, ref state, value); - } - - internal void WriteRawLittleEndian32(uint value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawLittleEndian32(ref span, ref state, value); - } - - internal void WriteRawLittleEndian64(ulong value) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawLittleEndian64(ref span, ref state, value); - } - - /// <summary> - /// Writes out an array of bytes. - /// </summary> - internal void WriteRawBytes(byte[] value) - { - WriteRawBytes(value, 0, value.Length); - } - - /// <summary> - /// Writes out part of an array of bytes. - /// </summary> - internal void WriteRawBytes(byte[] value, int offset, int length) - { - var span = new Span<byte>(buffer); - WritingPrimitives.WriteRawBytes(ref span, ref state, value, offset, length); - } - - #endregion - - /// <summary> - /// Indicates that a CodedOutputStream wrapping a flat byte array - /// ran out of space. - /// </summary> - public sealed class OutOfSpaceException : IOException - { - internal OutOfSpaceException() - : base("CodedOutputStream was writing to a flat byte array and ran out of space.") - { - } - } - - /// <summary> - /// Flushes any buffered data and optionally closes the underlying stream, if any. - /// </summary> - /// <remarks> - /// <para> - /// By default, any underlying stream is closed by this method. To configure this behaviour, - /// use a constructor overload with a <c>leaveOpen</c> parameter. If this instance does not - /// have an underlying stream, this method does nothing. - /// </para> - /// <para> - /// For the sake of efficiency, calling this method does not prevent future write calls - but - /// if a later write ends up writing to a stream which has been disposed, that is likely to - /// fail. It is recommend that you not call any other methods after this. - /// </para> - /// </remarks> - public void Dispose() - { - Flush(); - if (!leaveOpen) - { - output.Dispose(); - } - } - - /// <summary> - /// Flushes any buffered data to the underlying stream (if there is one). - /// </summary> - public void Flush() - { - var span = new Span<byte>(buffer); - WriteBufferHelper.Flush(ref span, ref state); - } - - /// <summary> - /// Verifies that SpaceLeft returns zero. It's common to create a byte array - /// that is exactly big enough to hold a message, then write to it with - /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that - /// the message was actually as big as expected, which can help finding bugs. - /// </summary> - public void CheckNoSpaceLeft() - { - WriteBufferHelper.CheckNoSpaceLeft(ref state); - } - - /// <summary> - /// If writing to a flat array, returns the space left in the array. Otherwise, - /// throws an InvalidOperationException. - /// </summary> - public int SpaceLeft => WriteBufferHelper.GetSpaceLeft(ref state); - - internal byte[] InternalBuffer => buffer; - - internal Stream InternalOutputStream => output; - - internal ref WriterInternalState InternalState => ref state; - } -} +#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.Collections; +using System; +using System.IO; +using System.Security; +using System.Text; + +namespace Google.Protobuf +{ + /// <summary> + /// Encodes and writes protocol message fields. + /// </summary> + /// <remarks> + /// <para> + /// This class is generally used by generated code to write appropriate + /// primitives to the stream. It effectively encapsulates the lowest + /// levels of protocol buffer format. Unlike some other implementations, + /// this does not include combined "write tag and value" methods. Generated + /// code knows the exact byte representations of the tags they're going to write, + /// so there's no need to re-encode them each time. Manually-written code calling + /// this class should just call one of the <c>WriteTag</c> overloads before each value. + /// </para> + /// <para> + /// Repeated fields and map fields are not handled by this class; use <c>RepeatedField<T></c> + /// and <c>MapField<TKey, TValue></c> to serialize such fields. + /// </para> + /// </remarks> + [SecuritySafeCritical] + public sealed partial class CodedOutputStream : IDisposable + { + /// <summary> + /// The buffer size used by CreateInstance(Stream). + /// </summary> + public static readonly int DefaultBufferSize = 4096; + + private readonly bool leaveOpen; + private readonly byte[] buffer; + private WriterInternalState state; + + private readonly Stream output; + + #region Construction + /// <summary> + /// Creates a new CodedOutputStream that writes directly to the given + /// byte array. If more bytes are written than fit in the array, + /// OutOfSpaceException will be thrown. + /// </summary> + public CodedOutputStream(byte[] flatArray) : this(flatArray, 0, flatArray.Length) + { + } + + /// <summary> + /// Creates a new CodedOutputStream that writes directly to the given + /// byte array slice. If more bytes are written than fit in the array, + /// OutOfSpaceException will be thrown. + /// </summary> + private CodedOutputStream(byte[] buffer, int offset, int length) + { + this.output = null; + this.buffer = ProtoPreconditions.CheckNotNull(buffer, nameof(buffer)); + this.state.position = offset; + this.state.limit = offset + length; + WriteBufferHelper.Initialize(this, out this.state.writeBufferHelper); + leaveOpen = true; // Simple way of avoiding trying to dispose of a null reference + } + + private CodedOutputStream(Stream output, byte[] buffer, bool leaveOpen) + { + this.output = ProtoPreconditions.CheckNotNull(output, nameof(output)); + this.buffer = buffer; + this.state.position = 0; + this.state.limit = buffer.Length; + WriteBufferHelper.Initialize(this, out this.state.writeBufferHelper); + this.leaveOpen = leaveOpen; + } + + /// <summary> + /// Creates a new <see cref="CodedOutputStream" /> which write to the given stream, and disposes of that + /// stream when the returned <c>CodedOutputStream</c> is disposed. + /// </summary> + /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param> + public CodedOutputStream(Stream output) : this(output, DefaultBufferSize, false) + { + } + + /// <summary> + /// Creates a new CodedOutputStream which write to the given stream and uses + /// the specified buffer size. + /// </summary> + /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param> + /// <param name="bufferSize">The size of buffer to use internally.</param> + public CodedOutputStream(Stream output, int bufferSize) : this(output, new byte[bufferSize], false) + { + } + + /// <summary> + /// Creates a new CodedOutputStream which write to the given stream. + /// </summary> + /// <param name="output">The stream to write to.</param> + /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed; + /// if <c>false</c>, the provided stream is disposed as well.</param> + public CodedOutputStream(Stream output, bool leaveOpen) : this(output, DefaultBufferSize, leaveOpen) + { + } + + /// <summary> + /// Creates a new CodedOutputStream which write to the given stream and uses + /// the specified buffer size. + /// </summary> + /// <param name="output">The stream to write to.</param> + /// <param name="bufferSize">The size of buffer to use internally.</param> + /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed; + /// if <c>false</c>, the provided stream is disposed as well.</param> + public CodedOutputStream(Stream output, int bufferSize, bool leaveOpen) : this(output, new byte[bufferSize], leaveOpen) + { + } + #endregion + + /// <summary> + /// Returns the current position in the stream, or the position in the output buffer + /// </summary> + public long Position + { + get + { + if (output != null) + { + return output.Position + state.position; + } + return state.position; + } + } + + #region Writing of values (not including tags) + + /// <summary> + /// Writes a double field value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteDouble(double value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteDouble(ref span, ref state, value); + } + + /// <summary> + /// Writes a float field value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteFloat(float value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteFloat(ref span, ref state, value); + } + + /// <summary> + /// Writes a uint64 field value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteUInt64(ulong value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteUInt64(ref span, ref state, value); + } + + /// <summary> + /// Writes an int64 field value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteInt64(long value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteInt64(ref span, ref state, value); + } + + /// <summary> + /// Writes an int32 field value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteInt32(int value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteInt32(ref span, ref state, value); + } + + /// <summary> + /// Writes a fixed64 field value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteFixed64(ulong value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteFixed64(ref span, ref state, value); + } + + /// <summary> + /// Writes a fixed32 field value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteFixed32(uint value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteFixed32(ref span, ref state, value); + } + + /// <summary> + /// Writes a bool field value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteBool(bool value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteBool(ref span, ref state, value); + } + + /// <summary> + /// Writes a string field value, without a tag, to the stream. + /// The data is length-prefixed. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteString(string value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteString(ref span, ref state, value); + } + + /// <summary> + /// Writes a message, without a tag, to the stream. + /// The data is length-prefixed. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteMessage(IMessage value) + { + // TODO(jtattermusch): if the message doesn't implement IBufferMessage (and thus does not provide the InternalWriteTo method), + // what we're doing here works fine, but could be more efficient. + // For now, this inefficiency is fine, considering this is only a backward-compatibility scenario (and regenerating the code fixes it). + var span = new Span<byte>(buffer); + WriteContext.Initialize(ref span, ref state, out WriteContext ctx); + try + { + WritingPrimitivesMessages.WriteMessage(ref ctx, value); + } + finally + { + ctx.CopyStateTo(this); + } + } + + /// <summary> + /// Writes a message, without a tag, to the stream. + /// Only the message data is written, without a length-delimiter. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteRawMessage(IMessage value) + { + // TODO(jtattermusch): if the message doesn't implement IBufferMessage (and thus does not provide the InternalWriteTo method), + // what we're doing here works fine, but could be more efficient. + // For now, this inefficiency is fine, considering this is only a backward-compatibility scenario (and regenerating the code fixes it). + var span = new Span<byte>(buffer); + WriteContext.Initialize(ref span, ref state, out WriteContext ctx); + try + { + WritingPrimitivesMessages.WriteRawMessage(ref ctx, value); + } + finally + { + ctx.CopyStateTo(this); + } + } + + /// <summary> + /// Writes a group, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteGroup(IMessage value) + { + var span = new Span<byte>(buffer); + WriteContext.Initialize(ref span, ref state, out WriteContext ctx); + try + { + WritingPrimitivesMessages.WriteGroup(ref ctx, value); + } + finally + { + ctx.CopyStateTo(this); + } + } + + /// <summary> + /// Write a byte string, without a tag, to the stream. + /// The data is length-prefixed. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteBytes(ByteString value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteBytes(ref span, ref state, value); + } + + /// <summary> + /// Writes a uint32 value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteUInt32(uint value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteUInt32(ref span, ref state, value); + } + + /// <summary> + /// Writes an enum value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteEnum(int value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteEnum(ref span, ref state, value); + } + + /// <summary> + /// Writes an sfixed32 value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write.</param> + public void WriteSFixed32(int value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteSFixed32(ref span, ref state, value); + } + + /// <summary> + /// Writes an sfixed64 value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteSFixed64(long value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteSFixed64(ref span, ref state, value); + } + + /// <summary> + /// Writes an sint32 value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteSInt32(int value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteSInt32(ref span, ref state, value); + } + + /// <summary> + /// Writes an sint64 value, without a tag, to the stream. + /// </summary> + /// <param name="value">The value to write</param> + public void WriteSInt64(long value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteSInt64(ref span, ref state, value); + } + + /// <summary> + /// Writes a length (in bytes) for length-delimited data. + /// </summary> + /// <remarks> + /// This method simply writes a rawint, but exists for clarity in calling code. + /// </remarks> + /// <param name="length">Length value, in bytes.</param> + public void WriteLength(int length) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteLength(ref span, ref state, length); + } + + #endregion + + #region Raw tag writing + /// <summary> + /// Encodes and writes a tag. + /// </summary> + /// <param name="fieldNumber">The number of the field to write the tag for</param> + /// <param name="type">The wire format type of the tag to write</param> + public void WriteTag(int fieldNumber, WireFormat.WireType type) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteTag(ref span, ref state, fieldNumber, type); + } + + /// <summary> + /// Writes an already-encoded tag. + /// </summary> + /// <param name="tag">The encoded tag</param> + public void WriteTag(uint tag) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteTag(ref span, ref state, tag); + } + + /// <summary> + /// Writes the given single-byte tag directly to the stream. + /// </summary> + /// <param name="b1">The encoded tag</param> + public void WriteRawTag(byte b1) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawTag(ref span, ref state, b1); + } + + /// <summary> + /// Writes the given two-byte tag directly to the stream. + /// </summary> + /// <param name="b1">The first byte of the encoded tag</param> + /// <param name="b2">The second byte of the encoded tag</param> + public void WriteRawTag(byte b1, byte b2) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2); + } + + /// <summary> + /// Writes the given three-byte tag directly to the stream. + /// </summary> + /// <param name="b1">The first byte of the encoded tag</param> + /// <param name="b2">The second byte of the encoded tag</param> + /// <param name="b3">The third byte of the encoded tag</param> + public void WriteRawTag(byte b1, byte b2, byte b3) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3); + } + + /// <summary> + /// Writes the given four-byte tag directly to the stream. + /// </summary> + /// <param name="b1">The first byte of the encoded tag</param> + /// <param name="b2">The second byte of the encoded tag</param> + /// <param name="b3">The third byte of the encoded tag</param> + /// <param name="b4">The fourth byte of the encoded tag</param> + public void WriteRawTag(byte b1, byte b2, byte b3, byte b4) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3, b4); + } + + /// <summary> + /// Writes the given five-byte tag directly to the stream. + /// </summary> + /// <param name="b1">The first byte of the encoded tag</param> + /// <param name="b2">The second byte of the encoded tag</param> + /// <param name="b3">The third byte of the encoded tag</param> + /// <param name="b4">The fourth byte of the encoded tag</param> + /// <param name="b5">The fifth byte of the encoded tag</param> + public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3, b4, b5); + } + #endregion + + #region Underlying writing primitives + + /// <summary> + /// Writes a 32 bit value as a varint. The fast route is taken when + /// there's enough buffer space left to whizz through without checking + /// for each byte; otherwise, we resort to calling WriteRawByte each time. + /// </summary> + internal void WriteRawVarint32(uint value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawVarint32(ref span, ref state, value); + } + + internal void WriteRawVarint64(ulong value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawVarint64(ref span, ref state, value); + } + + internal void WriteRawLittleEndian32(uint value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawLittleEndian32(ref span, ref state, value); + } + + internal void WriteRawLittleEndian64(ulong value) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawLittleEndian64(ref span, ref state, value); + } + + /// <summary> + /// Writes out an array of bytes. + /// </summary> + internal void WriteRawBytes(byte[] value) + { + WriteRawBytes(value, 0, value.Length); + } + + /// <summary> + /// Writes out part of an array of bytes. + /// </summary> + internal void WriteRawBytes(byte[] value, int offset, int length) + { + var span = new Span<byte>(buffer); + WritingPrimitives.WriteRawBytes(ref span, ref state, value, offset, length); + } + + #endregion + + /// <summary> + /// Indicates that a CodedOutputStream wrapping a flat byte array + /// ran out of space. + /// </summary> + public sealed class OutOfSpaceException : IOException + { + internal OutOfSpaceException() + : base("CodedOutputStream was writing to a flat byte array and ran out of space.") + { + } + } + + /// <summary> + /// Flushes any buffered data and optionally closes the underlying stream, if any. + /// </summary> + /// <remarks> + /// <para> + /// By default, any underlying stream is closed by this method. To configure this behaviour, + /// use a constructor overload with a <c>leaveOpen</c> parameter. If this instance does not + /// have an underlying stream, this method does nothing. + /// </para> + /// <para> + /// For the sake of efficiency, calling this method does not prevent future write calls - but + /// if a later write ends up writing to a stream which has been disposed, that is likely to + /// fail. It is recommend that you not call any other methods after this. + /// </para> + /// </remarks> + public void Dispose() + { + Flush(); + if (!leaveOpen) + { + output.Dispose(); + } + } + + /// <summary> + /// Flushes any buffered data to the underlying stream (if there is one). + /// </summary> + public void Flush() + { + var span = new Span<byte>(buffer); + WriteBufferHelper.Flush(ref span, ref state); + } + + /// <summary> + /// Verifies that SpaceLeft returns zero. It's common to create a byte array + /// that is exactly big enough to hold a message, then write to it with + /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that + /// the message was actually as big as expected, which can help finding bugs. + /// </summary> + public void CheckNoSpaceLeft() + { + WriteBufferHelper.CheckNoSpaceLeft(ref state); + } + + /// <summary> + /// If writing to a flat array, returns the space left in the array. Otherwise, + /// throws an InvalidOperationException. + /// </summary> + public int SpaceLeft => WriteBufferHelper.GetSpaceLeft(ref state); + + internal byte[] InternalBuffer => buffer; + + internal Stream InternalOutputStream => output; + + internal ref WriterInternalState InternalState => ref state; + } +}
diff --git a/csharp/src/Google.Protobuf/Collections/MapField.cs b/csharp/src/Google.Protobuf/Collections/MapField.cs index 6b7d0f1..e5217f4 100644 --- a/csharp/src/Google.Protobuf/Collections/MapField.cs +++ b/csharp/src/Google.Protobuf/Collections/MapField.cs
@@ -1,762 +1,762 @@ -#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 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 -{ - /// <summary> - /// Representation of a map field in a Protocol Buffer message. - /// </summary> - /// <typeparam name="TKey">Key type in the map. Must be a type supported by Protocol Buffer map keys.</typeparam> - /// <typeparam name="TValue">Value type in the map. Must be a type supported by Protocol Buffers.</typeparam> - /// <remarks> - /// <para> - /// For string keys, the equality comparison is provided by <see cref="StringComparer.Ordinal" />. - /// </para> - /// <para> - /// Null values are not permitted in the map, either for wrapper types or regular messages. - /// If a map is deserialized from a data stream and the value is missing from an entry, a default value - /// is created instead. For primitive types, that is the regular default value (0, the empty string and so - /// on); for message types, an empty instance of the message is created, as if the map entry contained a 0-length - /// encoded value for the field. - /// </para> - /// <para> - /// This implementation does not generally prohibit the use of key/value types which are not - /// supported by Protocol Buffers (e.g. using a key type of <code>byte</code>) but nor does it guarantee - /// that all operations will work in such cases. - /// </para> - /// <para> - /// The order in which entries are returned when iterating over this object is undefined, and may change - /// in future versions. - /// </para> - /// </remarks> - public sealed class MapField<TKey, TValue> : IDeepCloneable<MapField<TKey, TValue>>, IDictionary<TKey, TValue>, IEquatable<MapField<TKey, TValue>>, IDictionary -#if !NET35 - , IReadOnlyDictionary<TKey, TValue> -#endif - { - private static readonly EqualityComparer<TValue> ValueEqualityComparer = ProtobufEqualityComparers.GetEqualityComparer<TValue>(); - private static readonly EqualityComparer<TKey> KeyEqualityComparer = ProtobufEqualityComparers.GetEqualityComparer<TKey>(); - - // TODO: Don't create the map/list until we have an entry. (Assume many maps will be empty.) - private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> map = - new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(KeyEqualityComparer); - private readonly LinkedList<KeyValuePair<TKey, TValue>> list = new LinkedList<KeyValuePair<TKey, TValue>>(); - - /// <summary> - /// Creates a deep clone of this object. - /// </summary> - /// <returns> - /// A deep clone of this object. - /// </returns> - public MapField<TKey, TValue> Clone() - { - var clone = new MapField<TKey, TValue>(); - // Keys are never cloneable. Values might be. - if (typeof(IDeepCloneable<TValue>).IsAssignableFrom(typeof(TValue))) - { - foreach (var pair in list) - { - clone.Add(pair.Key, ((IDeepCloneable<TValue>)pair.Value).Clone()); - } - } - else - { - // Nothing is cloneable, so we don't need to worry. - clone.Add(this); - } - return clone; - } - - /// <summary> - /// Adds the specified key/value pair to the map. - /// </summary> - /// <remarks> - /// This operation fails if the key already exists in the map. To replace an existing entry, use the indexer. - /// </remarks> - /// <param name="key">The key to add</param> - /// <param name="value">The value to add.</param> - /// <exception cref="System.ArgumentException">The given key already exists in map.</exception> - public void Add(TKey key, TValue value) - { - // Validation of arguments happens in ContainsKey and the indexer - if (ContainsKey(key)) - { - throw new ArgumentException("Key already exists in map", nameof(key)); - } - this[key] = value; - } - - /// <summary> - /// Determines whether the specified key is present in the map. - /// </summary> - /// <param name="key">The key to check.</param> - /// <returns><c>true</c> if the map contains the given key; <c>false</c> otherwise.</returns> - public bool ContainsKey(TKey key) - { - ProtoPreconditions.CheckNotNullUnconstrained(key, nameof(key)); - return map.ContainsKey(key); - } - - private bool ContainsValue(TValue value) => - list.Any(pair => ValueEqualityComparer.Equals(pair.Value, value)); - - /// <summary> - /// Removes the entry identified by the given key from the map. - /// </summary> - /// <param name="key">The key indicating the entry to remove from the map.</param> - /// <returns><c>true</c> if the map contained the given key before the entry was removed; <c>false</c> otherwise.</returns> - public bool Remove(TKey key) - { - ProtoPreconditions.CheckNotNullUnconstrained(key, nameof(key)); - LinkedListNode<KeyValuePair<TKey, TValue>> node; - if (map.TryGetValue(key, out node)) - { - map.Remove(key); - node.List.Remove(node); - return true; - } - else - { - return false; - } - } - - /// <summary> - /// Gets the value associated with the specified key. - /// </summary> - /// <param name="key">The key whose value to get.</param> - /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; - /// otherwise, the default value for the type of the <paramref name="value"/> parameter. - /// This parameter is passed uninitialized.</param> - /// <returns><c>true</c> if the map contains an element with the specified key; otherwise, <c>false</c>.</returns> - public bool TryGetValue(TKey key, out TValue value) - { - LinkedListNode<KeyValuePair<TKey, TValue>> node; - if (map.TryGetValue(key, out node)) - { - value = node.Value.Value; - return true; - } - else - { - value = default(TValue); - return false; - } - } - - /// <summary> - /// Gets or sets the value associated with the specified key. - /// </summary> - /// <param name="key">The key of the value to get or set.</param> - /// <exception cref="KeyNotFoundException">The property is retrieved and key does not exist in the collection.</exception> - /// <returns>The value associated with the specified key. If the specified key is not found, - /// a get operation throws a <see cref="KeyNotFoundException"/>, and a set operation creates a new element with the specified key.</returns> - public TValue this[TKey key] - { - get - { - ProtoPreconditions.CheckNotNullUnconstrained(key, nameof(key)); - TValue value; - if (TryGetValue(key, out value)) - { - return value; - } - throw new KeyNotFoundException(); - } - set - { - ProtoPreconditions.CheckNotNullUnconstrained(key, nameof(key)); - // value == null check here is redundant, but avoids boxing. - if (value == null) - { - ProtoPreconditions.CheckNotNullUnconstrained(value, nameof(value)); - } - LinkedListNode<KeyValuePair<TKey, TValue>> node; - var pair = new KeyValuePair<TKey, TValue>(key, value); - if (map.TryGetValue(key, out node)) - { - node.Value = pair; - } - else - { - node = list.AddLast(pair); - map[key] = node; - } - } - } - - /// <summary> - /// Gets a collection containing the keys in the map. - /// </summary> - public ICollection<TKey> Keys { get { return new MapView<TKey>(this, pair => pair.Key, ContainsKey); } } - - /// <summary> - /// Gets a collection containing the values in the map. - /// </summary> - public ICollection<TValue> Values { get { return new MapView<TValue>(this, pair => pair.Value, ContainsValue); } } - - /// <summary> - /// Adds the specified entries to the map. The keys and values are not automatically cloned. - /// </summary> - /// <param name="entries">The entries to add to the map.</param> - public void Add(IDictionary<TKey, TValue> entries) - { - ProtoPreconditions.CheckNotNull(entries, nameof(entries)); - foreach (var pair in entries) - { - Add(pair.Key, pair.Value); - } - } - - /// <summary> - /// Returns an enumerator that iterates through the collection. - /// </summary> - /// <returns> - /// An enumerator that can be used to iterate through the collection. - /// </returns> - public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() - { - return list.GetEnumerator(); - } - - /// <summary> - /// Returns an enumerator that iterates through a collection. - /// </summary> - /// <returns> - /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. - /// </returns> - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - /// <summary> - /// Adds the specified item to the map. - /// </summary> - /// <param name="item">The item to add to the map.</param> - void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) - { - Add(item.Key, item.Value); - } - - /// <summary> - /// Removes all items from the map. - /// </summary> - public void Clear() - { - list.Clear(); - map.Clear(); - } - - /// <summary> - /// Determines whether map contains an entry equivalent to the given key/value pair. - /// </summary> - /// <param name="item">The key/value pair to find.</param> - /// <returns></returns> - bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) - { - TValue value; - return TryGetValue(item.Key, out value) && ValueEqualityComparer.Equals(item.Value, value); - } - - /// <summary> - /// Copies the key/value pairs in this map to an array. - /// </summary> - /// <param name="array">The array to copy the entries into.</param> - /// <param name="arrayIndex">The index of the array at which to start copying values.</param> - void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) - { - list.CopyTo(array, arrayIndex); - } - - /// <summary> - /// Removes the specified key/value pair from the map. - /// </summary> - /// <remarks>Both the key and the value must be found for the entry to be removed.</remarks> - /// <param name="item">The key/value pair to remove.</param> - /// <returns><c>true</c> if the key/value pair was found and removed; <c>false</c> otherwise.</returns> - bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) - { - if (item.Key == null) - { - throw new ArgumentException("Key is null", nameof(item)); - } - LinkedListNode<KeyValuePair<TKey, TValue>> node; - if (map.TryGetValue(item.Key, out node) && - EqualityComparer<TValue>.Default.Equals(item.Value, node.Value.Value)) - { - map.Remove(item.Key); - node.List.Remove(node); - return true; - } - else - { - return false; - } - } - - /// <summary> - /// Gets the number of elements contained in the map. - /// </summary> - public int Count { get { return list.Count; } } - - /// <summary> - /// Gets a value indicating whether the map is read-only. - /// </summary> - public bool IsReadOnly { get { return false; } } - - /// <summary> - /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. - /// </summary> - /// <param name="other">The <see cref="System.Object" /> to compare with this instance.</param> - /// <returns> - /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. - /// </returns> - public override bool Equals(object other) - { - return Equals(other as MapField<TKey, TValue>); - } - - /// <summary> - /// Returns a hash code for this instance. - /// </summary> - /// <returns> - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - /// </returns> - public override int GetHashCode() - { - var keyComparer = KeyEqualityComparer; - var valueComparer = ValueEqualityComparer; - int hash = 0; - foreach (var pair in list) - { - hash ^= keyComparer.GetHashCode(pair.Key) * 31 + valueComparer.GetHashCode(pair.Value); - } - return hash; - } - - /// <summary> - /// Compares this map with another for equality. - /// </summary> - /// <remarks> - /// The order of the key/value pairs in the maps is not deemed significant in this comparison. - /// </remarks> - /// <param name="other">The map to compare this with.</param> - /// <returns><c>true</c> if <paramref name="other"/> refers to an equal map; <c>false</c> otherwise.</returns> - public bool Equals(MapField<TKey, TValue> other) - { - if (other == null) - { - return false; - } - if (other == this) - { - return true; - } - if (other.Count != this.Count) - { - return false; - } - var valueComparer = ValueEqualityComparer; - foreach (var pair in this) - { - TValue value; - if (!other.TryGetValue(pair.Key, out value)) - { - return false; - } - if (!valueComparer.Equals(value, pair.Value)) - { - return false; - } - } - return true; - } - - /// <summary> - /// Adds entries to the map from the given stream. - /// </summary> - /// <remarks> - /// It is assumed that the stream is initially positioned after the tag specified by the codec. - /// This method will continue reading entries from the stream until the end is reached, or - /// a different tag is encountered. - /// </remarks> - /// <param name="input">Stream to read from</param> - /// <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) - { - do - { - KeyValuePair<TKey, TValue> entry = ParsingPrimitivesMessages.ReadMapEntry(ref ctx, codec); - this[entry.Key] = entry.Value; - } while (ParsingPrimitives.MaybeConsumeTag(ref ctx.buffer, ref ctx.state, codec.MapTag)); - } - - /// <summary> - /// Writes the contents of this map to the given coded output stream, using the specified codec - /// to encode each entry. - /// </summary> - /// <param name="output">The output stream to write to.</param> - /// <param name="codec">The codec to use for each entry.</param> - public void WriteTo(CodedOutputStream output, Codec codec) - { - WriteContext.Initialize(output, out WriteContext ctx); - try - { - WriteTo(ref ctx, codec); - } - finally - { - ctx.CopyStateTo(output); - } - } - - /// <summary> - /// Writes the contents of this map to the given write context, using the specified codec - /// to encode each entry. - /// </summary> - /// <param name="ctx">The write context to write to.</param> - /// <param name="codec">The codec to use for each entry.</param> - [SecuritySafeCritical] - public void WriteTo(ref WriteContext ctx, Codec codec) - { - foreach (var entry in list) - { - ctx.WriteTag(codec.MapTag); - - WritingPrimitives.WriteLength(ref ctx.buffer, ref ctx.state, CalculateEntrySize(codec, entry)); - codec.KeyCodec.WriteTagAndValue(ref ctx, entry.Key); - codec.ValueCodec.WriteTagAndValue(ref ctx, entry.Value); - } - } - - /// <summary> - /// Calculates the size of this map based on the given entry codec. - /// </summary> - /// <param name="codec">The codec to use to encode each entry.</param> - /// <returns></returns> - public int CalculateSize(Codec codec) - { - if (Count == 0) - { - return 0; - } - int size = 0; - foreach (var entry in list) - { - int entrySize = CalculateEntrySize(codec, entry); - - size += CodedOutputStream.ComputeRawVarint32Size(codec.MapTag); - size += CodedOutputStream.ComputeLengthSize(entrySize) + entrySize; - } - return size; - } - - private static int CalculateEntrySize(Codec codec, KeyValuePair<TKey, TValue> entry) - { - return codec.KeyCodec.CalculateSizeWithTag(entry.Key) + codec.ValueCodec.CalculateSizeWithTag(entry.Value); - } - - /// <summary> - /// Returns a string representation of this repeated field, in the same - /// way as it would be represented by the default JSON formatter. - /// </summary> - public override string ToString() - { - var writer = new StringWriter(); - JsonFormatter.Default.WriteDictionary(writer, this); - return writer.ToString(); - } - - #region IDictionary explicit interface implementation - void IDictionary.Add(object key, object value) - { - Add((TKey)key, (TValue)value); - } - - bool IDictionary.Contains(object key) - { - if (!(key is TKey)) - { - return false; - } - return ContainsKey((TKey)key); - } - - IDictionaryEnumerator IDictionary.GetEnumerator() - { - return new DictionaryEnumerator(GetEnumerator()); - } - - void IDictionary.Remove(object key) - { - ProtoPreconditions.CheckNotNull(key, nameof(key)); - if (!(key is TKey)) - { - return; - } - Remove((TKey)key); - } - - void ICollection.CopyTo(Array array, int index) - { - // This is ugly and slow as heck, but with any luck it will never be used anyway. - ICollection temp = this.Select(pair => new DictionaryEntry(pair.Key, pair.Value)).ToList(); - temp.CopyTo(array, index); - } - - bool IDictionary.IsFixedSize { get { return false; } } - - ICollection IDictionary.Keys { get { return (ICollection)Keys; } } - - ICollection IDictionary.Values { get { return (ICollection)Values; } } - - bool ICollection.IsSynchronized { get { return false; } } - - object ICollection.SyncRoot { get { return this; } } - - object IDictionary.this[object key] - { - get - { - ProtoPreconditions.CheckNotNull(key, nameof(key)); - if (!(key is TKey)) - { - return null; - } - TValue value; - TryGetValue((TKey)key, out value); - return value; - } - - set - { - this[(TKey)key] = (TValue)value; - } - } - #endregion - - #region IReadOnlyDictionary explicit interface implementation -#if !NET35 - IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys; - - IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values; -#endif - #endregion - - private class DictionaryEnumerator : IDictionaryEnumerator - { - private readonly IEnumerator<KeyValuePair<TKey, TValue>> enumerator; - - internal DictionaryEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> enumerator) - { - this.enumerator = enumerator; - } - - public bool MoveNext() - { - return enumerator.MoveNext(); - } - - public void Reset() - { - enumerator.Reset(); - } - - public object Current { get { return Entry; } } - public DictionaryEntry Entry { get { return new DictionaryEntry(Key, Value); } } - public object Key { get { return enumerator.Current.Key; } } - public object Value { get { return enumerator.Current.Value; } } - } - - /// <summary> - /// A codec for a specific map field. This contains all the information required to encode and - /// decode the nested messages. - /// </summary> - public sealed class Codec - { - private readonly FieldCodec<TKey> keyCodec; - private readonly FieldCodec<TValue> valueCodec; - private readonly uint mapTag; - - /// <summary> - /// Creates a new entry codec based on a separate key codec and value codec, - /// and the tag to use for each map entry. - /// </summary> - /// <param name="keyCodec">The key codec.</param> - /// <param name="valueCodec">The value codec.</param> - /// <param name="mapTag">The map tag to use to introduce each map entry.</param> - public Codec(FieldCodec<TKey> keyCodec, FieldCodec<TValue> valueCodec, uint mapTag) - { - this.keyCodec = keyCodec; - this.valueCodec = valueCodec; - this.mapTag = mapTag; - } - - /// <summary> - /// The key codec. - /// </summary> - internal FieldCodec<TKey> KeyCodec => keyCodec; - - /// <summary> - /// The value codec. - /// </summary> - internal FieldCodec<TValue> ValueCodec => valueCodec; - - /// <summary> - /// The tag used in the enclosing message to indicate map entries. - /// </summary> - internal uint MapTag => mapTag; - } - - private class MapView<T> : ICollection<T>, ICollection - { - private readonly MapField<TKey, TValue> parent; - private readonly Func<KeyValuePair<TKey, TValue>, T> projection; - private readonly Func<T, bool> containsCheck; - - internal MapView( - MapField<TKey, TValue> parent, - Func<KeyValuePair<TKey, TValue>, T> projection, - Func<T, bool> containsCheck) - { - this.parent = parent; - this.projection = projection; - this.containsCheck = containsCheck; - } - - public int Count { get { return parent.Count; } } - - public bool IsReadOnly { get { return true; } } - - public bool IsSynchronized { get { return false; } } - - public object SyncRoot { get { return parent; } } - - public void Add(T item) - { - throw new NotSupportedException(); - } - - public void Clear() - { - throw new NotSupportedException(); - } - - public bool Contains(T item) - { - return containsCheck(item); - } - - public void CopyTo(T[] array, int arrayIndex) - { - if (arrayIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - } - if (arrayIndex + Count > array.Length) - { - throw new ArgumentException("Not enough space in the array", nameof(array)); - } - foreach (var item in this) - { - array[arrayIndex++] = item; - } - } - - public IEnumerator<T> GetEnumerator() - { - return parent.list.Select(projection).GetEnumerator(); - } - - public bool Remove(T item) - { - throw new NotSupportedException(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public void CopyTo(Array array, int index) - { - if (index < 0) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - if (index + Count > array.Length) - { - throw new ArgumentException("Not enough space in the array", nameof(array)); - } - foreach (var item in this) - { - array.SetValue(item, index++); - } - } - } - } -} +#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 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 +{ + /// <summary> + /// Representation of a map field in a Protocol Buffer message. + /// </summary> + /// <typeparam name="TKey">Key type in the map. Must be a type supported by Protocol Buffer map keys.</typeparam> + /// <typeparam name="TValue">Value type in the map. Must be a type supported by Protocol Buffers.</typeparam> + /// <remarks> + /// <para> + /// For string keys, the equality comparison is provided by <see cref="StringComparer.Ordinal" />. + /// </para> + /// <para> + /// Null values are not permitted in the map, either for wrapper types or regular messages. + /// If a map is deserialized from a data stream and the value is missing from an entry, a default value + /// is created instead. For primitive types, that is the regular default value (0, the empty string and so + /// on); for message types, an empty instance of the message is created, as if the map entry contained a 0-length + /// encoded value for the field. + /// </para> + /// <para> + /// This implementation does not generally prohibit the use of key/value types which are not + /// supported by Protocol Buffers (e.g. using a key type of <code>byte</code>) but nor does it guarantee + /// that all operations will work in such cases. + /// </para> + /// <para> + /// The order in which entries are returned when iterating over this object is undefined, and may change + /// in future versions. + /// </para> + /// </remarks> + public sealed class MapField<TKey, TValue> : IDeepCloneable<MapField<TKey, TValue>>, IDictionary<TKey, TValue>, IEquatable<MapField<TKey, TValue>>, IDictionary +#if !NET35 + , IReadOnlyDictionary<TKey, TValue> +#endif + { + private static readonly EqualityComparer<TValue> ValueEqualityComparer = ProtobufEqualityComparers.GetEqualityComparer<TValue>(); + private static readonly EqualityComparer<TKey> KeyEqualityComparer = ProtobufEqualityComparers.GetEqualityComparer<TKey>(); + + // TODO: Don't create the map/list until we have an entry. (Assume many maps will be empty.) + private readonly Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>> map = + new Dictionary<TKey, LinkedListNode<KeyValuePair<TKey, TValue>>>(KeyEqualityComparer); + private readonly LinkedList<KeyValuePair<TKey, TValue>> list = new LinkedList<KeyValuePair<TKey, TValue>>(); + + /// <summary> + /// Creates a deep clone of this object. + /// </summary> + /// <returns> + /// A deep clone of this object. + /// </returns> + public MapField<TKey, TValue> Clone() + { + var clone = new MapField<TKey, TValue>(); + // Keys are never cloneable. Values might be. + if (typeof(IDeepCloneable<TValue>).IsAssignableFrom(typeof(TValue))) + { + foreach (var pair in list) + { + clone.Add(pair.Key, ((IDeepCloneable<TValue>)pair.Value).Clone()); + } + } + else + { + // Nothing is cloneable, so we don't need to worry. + clone.Add(this); + } + return clone; + } + + /// <summary> + /// Adds the specified key/value pair to the map. + /// </summary> + /// <remarks> + /// This operation fails if the key already exists in the map. To replace an existing entry, use the indexer. + /// </remarks> + /// <param name="key">The key to add</param> + /// <param name="value">The value to add.</param> + /// <exception cref="System.ArgumentException">The given key already exists in map.</exception> + public void Add(TKey key, TValue value) + { + // Validation of arguments happens in ContainsKey and the indexer + if (ContainsKey(key)) + { + throw new ArgumentException("Key already exists in map", nameof(key)); + } + this[key] = value; + } + + /// <summary> + /// Determines whether the specified key is present in the map. + /// </summary> + /// <param name="key">The key to check.</param> + /// <returns><c>true</c> if the map contains the given key; <c>false</c> otherwise.</returns> + public bool ContainsKey(TKey key) + { + ProtoPreconditions.CheckNotNullUnconstrained(key, nameof(key)); + return map.ContainsKey(key); + } + + private bool ContainsValue(TValue value) => + list.Any(pair => ValueEqualityComparer.Equals(pair.Value, value)); + + /// <summary> + /// Removes the entry identified by the given key from the map. + /// </summary> + /// <param name="key">The key indicating the entry to remove from the map.</param> + /// <returns><c>true</c> if the map contained the given key before the entry was removed; <c>false</c> otherwise.</returns> + public bool Remove(TKey key) + { + ProtoPreconditions.CheckNotNullUnconstrained(key, nameof(key)); + LinkedListNode<KeyValuePair<TKey, TValue>> node; + if (map.TryGetValue(key, out node)) + { + map.Remove(key); + node.List.Remove(node); + return true; + } + else + { + return false; + } + } + + /// <summary> + /// Gets the value associated with the specified key. + /// </summary> + /// <param name="key">The key whose value to get.</param> + /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; + /// otherwise, the default value for the type of the <paramref name="value"/> parameter. + /// This parameter is passed uninitialized.</param> + /// <returns><c>true</c> if the map contains an element with the specified key; otherwise, <c>false</c>.</returns> + public bool TryGetValue(TKey key, out TValue value) + { + LinkedListNode<KeyValuePair<TKey, TValue>> node; + if (map.TryGetValue(key, out node)) + { + value = node.Value.Value; + return true; + } + else + { + value = default(TValue); + return false; + } + } + + /// <summary> + /// Gets or sets the value associated with the specified key. + /// </summary> + /// <param name="key">The key of the value to get or set.</param> + /// <exception cref="KeyNotFoundException">The property is retrieved and key does not exist in the collection.</exception> + /// <returns>The value associated with the specified key. If the specified key is not found, + /// a get operation throws a <see cref="KeyNotFoundException"/>, and a set operation creates a new element with the specified key.</returns> + public TValue this[TKey key] + { + get + { + ProtoPreconditions.CheckNotNullUnconstrained(key, nameof(key)); + TValue value; + if (TryGetValue(key, out value)) + { + return value; + } + throw new KeyNotFoundException(); + } + set + { + ProtoPreconditions.CheckNotNullUnconstrained(key, nameof(key)); + // value == null check here is redundant, but avoids boxing. + if (value == null) + { + ProtoPreconditions.CheckNotNullUnconstrained(value, nameof(value)); + } + LinkedListNode<KeyValuePair<TKey, TValue>> node; + var pair = new KeyValuePair<TKey, TValue>(key, value); + if (map.TryGetValue(key, out node)) + { + node.Value = pair; + } + else + { + node = list.AddLast(pair); + map[key] = node; + } + } + } + + /// <summary> + /// Gets a collection containing the keys in the map. + /// </summary> + public ICollection<TKey> Keys { get { return new MapView<TKey>(this, pair => pair.Key, ContainsKey); } } + + /// <summary> + /// Gets a collection containing the values in the map. + /// </summary> + public ICollection<TValue> Values { get { return new MapView<TValue>(this, pair => pair.Value, ContainsValue); } } + + /// <summary> + /// Adds the specified entries to the map. The keys and values are not automatically cloned. + /// </summary> + /// <param name="entries">The entries to add to the map.</param> + public void Add(IDictionary<TKey, TValue> entries) + { + ProtoPreconditions.CheckNotNull(entries, nameof(entries)); + foreach (var pair in entries) + { + Add(pair.Key, pair.Value); + } + } + + /// <summary> + /// Returns an enumerator that iterates through the collection. + /// </summary> + /// <returns> + /// An enumerator that can be used to iterate through the collection. + /// </returns> + public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() + { + return list.GetEnumerator(); + } + + /// <summary> + /// Returns an enumerator that iterates through a collection. + /// </summary> + /// <returns> + /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. + /// </returns> + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// <summary> + /// Adds the specified item to the map. + /// </summary> + /// <param name="item">The item to add to the map.</param> + void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) + { + Add(item.Key, item.Value); + } + + /// <summary> + /// Removes all items from the map. + /// </summary> + public void Clear() + { + list.Clear(); + map.Clear(); + } + + /// <summary> + /// Determines whether map contains an entry equivalent to the given key/value pair. + /// </summary> + /// <param name="item">The key/value pair to find.</param> + /// <returns></returns> + bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) + { + TValue value; + return TryGetValue(item.Key, out value) && ValueEqualityComparer.Equals(item.Value, value); + } + + /// <summary> + /// Copies the key/value pairs in this map to an array. + /// </summary> + /// <param name="array">The array to copy the entries into.</param> + /// <param name="arrayIndex">The index of the array at which to start copying values.</param> + void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) + { + list.CopyTo(array, arrayIndex); + } + + /// <summary> + /// Removes the specified key/value pair from the map. + /// </summary> + /// <remarks>Both the key and the value must be found for the entry to be removed.</remarks> + /// <param name="item">The key/value pair to remove.</param> + /// <returns><c>true</c> if the key/value pair was found and removed; <c>false</c> otherwise.</returns> + bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) + { + if (item.Key == null) + { + throw new ArgumentException("Key is null", nameof(item)); + } + LinkedListNode<KeyValuePair<TKey, TValue>> node; + if (map.TryGetValue(item.Key, out node) && + EqualityComparer<TValue>.Default.Equals(item.Value, node.Value.Value)) + { + map.Remove(item.Key); + node.List.Remove(node); + return true; + } + else + { + return false; + } + } + + /// <summary> + /// Gets the number of elements contained in the map. + /// </summary> + public int Count { get { return list.Count; } } + + /// <summary> + /// Gets a value indicating whether the map is read-only. + /// </summary> + public bool IsReadOnly { get { return false; } } + + /// <summary> + /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. + /// </summary> + /// <param name="other">The <see cref="System.Object" /> to compare with this instance.</param> + /// <returns> + /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. + /// </returns> + public override bool Equals(object other) + { + return Equals(other as MapField<TKey, TValue>); + } + + /// <summary> + /// Returns a hash code for this instance. + /// </summary> + /// <returns> + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// </returns> + public override int GetHashCode() + { + var keyComparer = KeyEqualityComparer; + var valueComparer = ValueEqualityComparer; + int hash = 0; + foreach (var pair in list) + { + hash ^= keyComparer.GetHashCode(pair.Key) * 31 + valueComparer.GetHashCode(pair.Value); + } + return hash; + } + + /// <summary> + /// Compares this map with another for equality. + /// </summary> + /// <remarks> + /// The order of the key/value pairs in the maps is not deemed significant in this comparison. + /// </remarks> + /// <param name="other">The map to compare this with.</param> + /// <returns><c>true</c> if <paramref name="other"/> refers to an equal map; <c>false</c> otherwise.</returns> + public bool Equals(MapField<TKey, TValue> other) + { + if (other == null) + { + return false; + } + if (other == this) + { + return true; + } + if (other.Count != this.Count) + { + return false; + } + var valueComparer = ValueEqualityComparer; + foreach (var pair in this) + { + TValue value; + if (!other.TryGetValue(pair.Key, out value)) + { + return false; + } + if (!valueComparer.Equals(value, pair.Value)) + { + return false; + } + } + return true; + } + + /// <summary> + /// Adds entries to the map from the given stream. + /// </summary> + /// <remarks> + /// It is assumed that the stream is initially positioned after the tag specified by the codec. + /// This method will continue reading entries from the stream until the end is reached, or + /// a different tag is encountered. + /// </remarks> + /// <param name="input">Stream to read from</param> + /// <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) + { + do + { + KeyValuePair<TKey, TValue> entry = ParsingPrimitivesMessages.ReadMapEntry(ref ctx, codec); + this[entry.Key] = entry.Value; + } while (ParsingPrimitives.MaybeConsumeTag(ref ctx.buffer, ref ctx.state, codec.MapTag)); + } + + /// <summary> + /// Writes the contents of this map to the given coded output stream, using the specified codec + /// to encode each entry. + /// </summary> + /// <param name="output">The output stream to write to.</param> + /// <param name="codec">The codec to use for each entry.</param> + public void WriteTo(CodedOutputStream output, Codec codec) + { + WriteContext.Initialize(output, out WriteContext ctx); + try + { + WriteTo(ref ctx, codec); + } + finally + { + ctx.CopyStateTo(output); + } + } + + /// <summary> + /// Writes the contents of this map to the given write context, using the specified codec + /// to encode each entry. + /// </summary> + /// <param name="ctx">The write context to write to.</param> + /// <param name="codec">The codec to use for each entry.</param> + [SecuritySafeCritical] + public void WriteTo(ref WriteContext ctx, Codec codec) + { + foreach (var entry in list) + { + ctx.WriteTag(codec.MapTag); + + WritingPrimitives.WriteLength(ref ctx.buffer, ref ctx.state, CalculateEntrySize(codec, entry)); + codec.KeyCodec.WriteTagAndValue(ref ctx, entry.Key); + codec.ValueCodec.WriteTagAndValue(ref ctx, entry.Value); + } + } + + /// <summary> + /// Calculates the size of this map based on the given entry codec. + /// </summary> + /// <param name="codec">The codec to use to encode each entry.</param> + /// <returns></returns> + public int CalculateSize(Codec codec) + { + if (Count == 0) + { + return 0; + } + int size = 0; + foreach (var entry in list) + { + int entrySize = CalculateEntrySize(codec, entry); + + size += CodedOutputStream.ComputeRawVarint32Size(codec.MapTag); + size += CodedOutputStream.ComputeLengthSize(entrySize) + entrySize; + } + return size; + } + + private static int CalculateEntrySize(Codec codec, KeyValuePair<TKey, TValue> entry) + { + return codec.KeyCodec.CalculateSizeWithTag(entry.Key) + codec.ValueCodec.CalculateSizeWithTag(entry.Value); + } + + /// <summary> + /// Returns a string representation of this repeated field, in the same + /// way as it would be represented by the default JSON formatter. + /// </summary> + public override string ToString() + { + var writer = new StringWriter(); + JsonFormatter.Default.WriteDictionary(writer, this); + return writer.ToString(); + } + + #region IDictionary explicit interface implementation + void IDictionary.Add(object key, object value) + { + Add((TKey)key, (TValue)value); + } + + bool IDictionary.Contains(object key) + { + if (!(key is TKey)) + { + return false; + } + return ContainsKey((TKey)key); + } + + IDictionaryEnumerator IDictionary.GetEnumerator() + { + return new DictionaryEnumerator(GetEnumerator()); + } + + void IDictionary.Remove(object key) + { + ProtoPreconditions.CheckNotNull(key, nameof(key)); + if (!(key is TKey)) + { + return; + } + Remove((TKey)key); + } + + void ICollection.CopyTo(Array array, int index) + { + // This is ugly and slow as heck, but with any luck it will never be used anyway. + ICollection temp = this.Select(pair => new DictionaryEntry(pair.Key, pair.Value)).ToList(); + temp.CopyTo(array, index); + } + + bool IDictionary.IsFixedSize { get { return false; } } + + ICollection IDictionary.Keys { get { return (ICollection)Keys; } } + + ICollection IDictionary.Values { get { return (ICollection)Values; } } + + bool ICollection.IsSynchronized { get { return false; } } + + object ICollection.SyncRoot { get { return this; } } + + object IDictionary.this[object key] + { + get + { + ProtoPreconditions.CheckNotNull(key, nameof(key)); + if (!(key is TKey)) + { + return null; + } + TValue value; + TryGetValue((TKey)key, out value); + return value; + } + + set + { + this[(TKey)key] = (TValue)value; + } + } + #endregion + + #region IReadOnlyDictionary explicit interface implementation +#if !NET35 + IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys; + + IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values; +#endif + #endregion + + private class DictionaryEnumerator : IDictionaryEnumerator + { + private readonly IEnumerator<KeyValuePair<TKey, TValue>> enumerator; + + internal DictionaryEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> enumerator) + { + this.enumerator = enumerator; + } + + public bool MoveNext() + { + return enumerator.MoveNext(); + } + + public void Reset() + { + enumerator.Reset(); + } + + public object Current { get { return Entry; } } + public DictionaryEntry Entry { get { return new DictionaryEntry(Key, Value); } } + public object Key { get { return enumerator.Current.Key; } } + public object Value { get { return enumerator.Current.Value; } } + } + + /// <summary> + /// A codec for a specific map field. This contains all the information required to encode and + /// decode the nested messages. + /// </summary> + public sealed class Codec + { + private readonly FieldCodec<TKey> keyCodec; + private readonly FieldCodec<TValue> valueCodec; + private readonly uint mapTag; + + /// <summary> + /// Creates a new entry codec based on a separate key codec and value codec, + /// and the tag to use for each map entry. + /// </summary> + /// <param name="keyCodec">The key codec.</param> + /// <param name="valueCodec">The value codec.</param> + /// <param name="mapTag">The map tag to use to introduce each map entry.</param> + public Codec(FieldCodec<TKey> keyCodec, FieldCodec<TValue> valueCodec, uint mapTag) + { + this.keyCodec = keyCodec; + this.valueCodec = valueCodec; + this.mapTag = mapTag; + } + + /// <summary> + /// The key codec. + /// </summary> + internal FieldCodec<TKey> KeyCodec => keyCodec; + + /// <summary> + /// The value codec. + /// </summary> + internal FieldCodec<TValue> ValueCodec => valueCodec; + + /// <summary> + /// The tag used in the enclosing message to indicate map entries. + /// </summary> + internal uint MapTag => mapTag; + } + + private class MapView<T> : ICollection<T>, ICollection + { + private readonly MapField<TKey, TValue> parent; + private readonly Func<KeyValuePair<TKey, TValue>, T> projection; + private readonly Func<T, bool> containsCheck; + + internal MapView( + MapField<TKey, TValue> parent, + Func<KeyValuePair<TKey, TValue>, T> projection, + Func<T, bool> containsCheck) + { + this.parent = parent; + this.projection = projection; + this.containsCheck = containsCheck; + } + + public int Count { get { return parent.Count; } } + + public bool IsReadOnly { get { return true; } } + + public bool IsSynchronized { get { return false; } } + + public object SyncRoot { get { return parent; } } + + public void Add(T item) + { + throw new NotSupportedException(); + } + + public void Clear() + { + throw new NotSupportedException(); + } + + public bool Contains(T item) + { + return containsCheck(item); + } + + public void CopyTo(T[] array, int arrayIndex) + { + if (arrayIndex < 0) + { + throw new ArgumentOutOfRangeException(nameof(arrayIndex)); + } + if (arrayIndex + Count > array.Length) + { + throw new ArgumentException("Not enough space in the array", nameof(array)); + } + foreach (var item in this) + { + array[arrayIndex++] = item; + } + } + + public IEnumerator<T> GetEnumerator() + { + return parent.list.Select(projection).GetEnumerator(); + } + + public bool Remove(T item) + { + throw new NotSupportedException(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public void CopyTo(Array array, int index) + { + if (index < 0) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + if (index + Count > array.Length) + { + throw new ArgumentException("Not enough space in the array", nameof(array)); + } + foreach (var item in this) + { + array.SetValue(item, index++); + } + } + } + } +}
diff --git a/csharp/src/Google.Protobuf/Collections/ReadOnlyDictionary.cs b/csharp/src/Google.Protobuf/Collections/ReadOnlyDictionary.cs index 8436066..28530a2 100644 --- a/csharp/src/Google.Protobuf/Collections/ReadOnlyDictionary.cs +++ b/csharp/src/Google.Protobuf/Collections/ReadOnlyDictionary.cs
@@ -1,147 +1,147 @@ -#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.Collections; -using System.Collections.Generic; - -namespace Google.Protobuf.Collections -{ - /// <summary> - /// Read-only wrapper around another dictionary. - /// </summary> - internal sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue> - { - private readonly IDictionary<TKey, TValue> wrapped; - - public ReadOnlyDictionary(IDictionary<TKey, TValue> wrapped) - { - this.wrapped = wrapped; - } - - public void Add(TKey key, TValue value) - { - throw new InvalidOperationException(); - } - - public bool ContainsKey(TKey key) - { - return wrapped.ContainsKey(key); - } - - public ICollection<TKey> Keys - { - get { return wrapped.Keys; } - } - - public bool Remove(TKey key) - { - throw new InvalidOperationException(); - } - - public bool TryGetValue(TKey key, out TValue value) - { - return wrapped.TryGetValue(key, out value); - } - - public ICollection<TValue> Values - { - get { return wrapped.Values; } - } - - public TValue this[TKey key] - { - get { return wrapped[key]; } - set { throw new InvalidOperationException(); } - } - - public void Add(KeyValuePair<TKey, TValue> item) - { - throw new InvalidOperationException(); - } - - public void Clear() - { - throw new InvalidOperationException(); - } - - public bool Contains(KeyValuePair<TKey, TValue> item) - { - return wrapped.Contains(item); - } - - public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) - { - wrapped.CopyTo(array, arrayIndex); - } - - public int Count - { - get { return wrapped.Count; } - } - - public bool IsReadOnly - { - get { return true; } - } - - public bool Remove(KeyValuePair<TKey, TValue> item) - { - throw new InvalidOperationException(); - } - - public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() - { - return wrapped.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return ((IEnumerable) wrapped).GetEnumerator(); - } - - public override bool Equals(object obj) - { - return wrapped.Equals(obj); - } - - public override int GetHashCode() - { - return wrapped.GetHashCode(); - } - - public override string ToString() - { - return wrapped.ToString(); - } - } +#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.Collections; +using System.Collections.Generic; + +namespace Google.Protobuf.Collections +{ + /// <summary> + /// Read-only wrapper around another dictionary. + /// </summary> + internal sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue> + { + private readonly IDictionary<TKey, TValue> wrapped; + + public ReadOnlyDictionary(IDictionary<TKey, TValue> wrapped) + { + this.wrapped = wrapped; + } + + public void Add(TKey key, TValue value) + { + throw new InvalidOperationException(); + } + + public bool ContainsKey(TKey key) + { + return wrapped.ContainsKey(key); + } + + public ICollection<TKey> Keys + { + get { return wrapped.Keys; } + } + + public bool Remove(TKey key) + { + throw new InvalidOperationException(); + } + + public bool TryGetValue(TKey key, out TValue value) + { + return wrapped.TryGetValue(key, out value); + } + + public ICollection<TValue> Values + { + get { return wrapped.Values; } + } + + public TValue this[TKey key] + { + get { return wrapped[key]; } + set { throw new InvalidOperationException(); } + } + + public void Add(KeyValuePair<TKey, TValue> item) + { + throw new InvalidOperationException(); + } + + public void Clear() + { + throw new InvalidOperationException(); + } + + public bool Contains(KeyValuePair<TKey, TValue> item) + { + return wrapped.Contains(item); + } + + public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) + { + wrapped.CopyTo(array, arrayIndex); + } + + public int Count + { + get { return wrapped.Count; } + } + + public bool IsReadOnly + { + get { return true; } + } + + public bool Remove(KeyValuePair<TKey, TValue> item) + { + throw new InvalidOperationException(); + } + + public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() + { + return wrapped.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable) wrapped).GetEnumerator(); + } + + public override bool Equals(object obj) + { + return wrapped.Equals(obj); + } + + public override int GetHashCode() + { + return wrapped.GetHashCode(); + } + + public override string ToString() + { + return wrapped.ToString(); + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs index 19114ca..9269c74 100644 --- a/csharp/src/Google.Protobuf/Collections/RepeatedField.cs +++ b/csharp/src/Google.Protobuf/Collections/RepeatedField.cs
@@ -1,698 +1,698 @@ -#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 System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Security; -using System.Threading; - -namespace Google.Protobuf.Collections -{ - /// <summary> - /// The contents of a repeated field: essentially, a collection with some extra - /// restrictions (no null values) and capabilities (deep cloning). - /// </summary> - /// <remarks> - /// This implementation does not generally prohibit the use of types which are not - /// supported by Protocol Buffers but nor does it guarantee that all operations will work in such cases. - /// </remarks> - /// <typeparam name="T">The element type of the repeated field.</typeparam> - public sealed class RepeatedField<T> : IList<T>, IList, IDeepCloneable<RepeatedField<T>>, IEquatable<RepeatedField<T>> -#if !NET35 - , IReadOnlyList<T> -#endif - { - private static readonly EqualityComparer<T> EqualityComparer = ProtobufEqualityComparers.GetEqualityComparer<T>(); - private static readonly T[] EmptyArray = new T[0]; - private const int MinArraySize = 8; - - private T[] array = EmptyArray; - private int count = 0; - - /// <summary> - /// Creates a deep clone of this repeated field. - /// </summary> - /// <remarks> - /// If the field type is - /// a message type, each element is also cloned; otherwise, it is - /// assumed that the field type is primitive (including string and - /// bytes, both of which are immutable) and so a simple copy is - /// equivalent to a deep clone. - /// </remarks> - /// <returns>A deep clone of this repeated field.</returns> - public RepeatedField<T> Clone() - { - RepeatedField<T> clone = new RepeatedField<T>(); - if (array != EmptyArray) - { - clone.array = (T[])array.Clone(); - IDeepCloneable<T>[] cloneableArray = clone.array as IDeepCloneable<T>[]; - if (cloneableArray != null) - { - for (int i = 0; i < count; i++) - { - clone.array[i] = cloneableArray[i].Clone(); - } - } - } - clone.count = count; - return clone; - } - - /// <summary> - /// Adds the entries from the given input stream, decoding them with the specified codec. - /// </summary> - /// <param name="input">The input stream to read from.</param> - /// <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 = ctx.state.lastTag; - var reader = codec.ValueReader; - // Non-nullable value types can be packed or not. - if (FieldCodec<T>.IsPackedRepeatedField(tag)) - { - int length = ctx.ReadLength(); - if (length > 0) - { - int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length); - - // If the content is fixed size then we can calculate the length - // of the repeated field and pre-initialize the underlying collection. - // - // Check that the supplied length doesn't exceed the underlying buffer. - // That prevents a malicious length from initializing a very large collection. - if (codec.FixedSize > 0 && length % codec.FixedSize == 0 && ParsingPrimitives.IsDataAvailable(ref ctx.state, length)) - { - EnsureSize(count + (length / codec.FixedSize)); - - while (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state)) - { - // Only FieldCodecs with a fixed size can reach here, and they are all known - // types that don't allow the user to specify a custom reader action. - // reader action will never return null. - array[count++] = reader(ref ctx); - } - } - else - { - // Content is variable size so add until we reach the limit. - while (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state)) - { - Add(reader(ref ctx)); - } - } - SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit); - } - // Empty packed field. Odd, but valid - just ignore. - } - else - { - // Not packed... (possibly not packable) - do - { - Add(reader(ref ctx)); - } while (ParsingPrimitives.MaybeConsumeTag(ref ctx.buffer, ref ctx.state, tag)); - } - } - - /// <summary> - /// Calculates the size of this collection based on the given codec. - /// </summary> - /// <param name="codec">The codec to use when encoding each field.</param> - /// <returns>The number of bytes that would be written to an output by one of the <c>WriteTo</c> methods, - /// using the same codec.</returns> - public int CalculateSize(FieldCodec<T> codec) - { - if (count == 0) - { - return 0; - } - uint tag = codec.Tag; - if (codec.PackedRepeatedField) - { - int dataSize = CalculatePackedDataSize(codec); - return CodedOutputStream.ComputeRawVarint32Size(tag) + - CodedOutputStream.ComputeLengthSize(dataSize) + - dataSize; - } - else - { - var sizeCalculator = codec.ValueSizeCalculator; - int size = count * CodedOutputStream.ComputeRawVarint32Size(tag); - if (codec.EndTag != 0) - { - size += count * CodedOutputStream.ComputeRawVarint32Size(codec.EndTag); - } - for (int i = 0; i < count; i++) - { - size += sizeCalculator(array[i]); - } - return size; - } - } - - private int CalculatePackedDataSize(FieldCodec<T> codec) - { - int fixedSize = codec.FixedSize; - if (fixedSize == 0) - { - var calculator = codec.ValueSizeCalculator; - int tmp = 0; - for (int i = 0; i < count; i++) - { - tmp += calculator(array[i]); - } - return tmp; - } - else - { - return fixedSize * Count; - } - } - - /// <summary> - /// Writes the contents of this collection to the given <see cref="CodedOutputStream"/>, - /// encoding each value using the specified codec. - /// </summary> - /// <param name="output">The output stream to write to.</param> - /// <param name="codec">The codec to use when encoding each value.</param> - public void WriteTo(CodedOutputStream output, FieldCodec<T> codec) - { - WriteContext.Initialize(output, out WriteContext ctx); - try - { - WriteTo(ref ctx, codec); - } - finally - { - ctx.CopyStateTo(output); - } - } - - /// <summary> - /// Writes the contents of this collection to the given write context, - /// encoding each value using the specified codec. - /// </summary> - /// <param name="ctx">The write context to write to.</param> - /// <param name="codec">The codec to use when encoding each value.</param> - [SecuritySafeCritical] - public void WriteTo(ref WriteContext ctx, FieldCodec<T> codec) - { - if (count == 0) - { - return; - } - var writer = codec.ValueWriter; - var tag = codec.Tag; - if (codec.PackedRepeatedField) - { - // Packed primitive type - int size = CalculatePackedDataSize(codec); - ctx.WriteTag(tag); - ctx.WriteLength(size); - for (int i = 0; i < count; i++) - { - writer(ref ctx, array[i]); - } - } - else - { - // Not packed: a simple tag/value pair for each value. - // Can't use codec.WriteTagAndValue, as that omits default values. - for (int i = 0; i < count; i++) - { - ctx.WriteTag(tag); - writer(ref ctx, array[i]); - if (codec.EndTag != 0) - { - ctx.WriteTag(codec.EndTag); - } - } - } - } - - /// <summary> - /// Gets and sets the capacity of the RepeatedField's internal array. WHen set, the internal array is reallocated to the given capacity. - /// <exception cref="ArgumentOutOfRangeException">The new value is less than Count -or- when Count is less than 0.</exception> - /// </summary> - public int Capacity - { - get { return array.Length; } - set - { - if (value < count) - { - throw new ArgumentOutOfRangeException("Capacity", value, - $"Cannot set Capacity to a value smaller than the current item count, {count}"); - } - - if (value >= 0 && value != array.Length) - { - SetSize(value); - } - } - } - - // May increase the size of the internal array, but will never shrink it. - private void EnsureSize(int size) - { - if (array.Length < size) - { - size = Math.Max(size, MinArraySize); - int newSize = Math.Max(array.Length * 2, size); - SetSize(newSize); - } - } - - // Sets the internal array to an exact size. - private void SetSize(int size) - { - if (size != array.Length) - { - var tmp = new T[size]; - Array.Copy(array, 0, tmp, 0, count); - array = tmp; - } - } - - /// <summary> - /// Adds the specified item to the collection. - /// </summary> - /// <param name="item">The item to add.</param> - public void Add(T item) - { - ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); - EnsureSize(count + 1); - array[count++] = item; - } - - /// <summary> - /// Removes all items from the collection. - /// </summary> - public void Clear() - { - array = EmptyArray; - count = 0; - } - - /// <summary> - /// Determines whether this collection contains the given item. - /// </summary> - /// <param name="item">The item to find.</param> - /// <returns><c>true</c> if this collection contains the given item; <c>false</c> otherwise.</returns> - public bool Contains(T item) - { - return IndexOf(item) != -1; - } - - /// <summary> - /// Copies this collection to the given array. - /// </summary> - /// <param name="array">The array to copy to.</param> - /// <param name="arrayIndex">The first index of the array to copy to.</param> - public void CopyTo(T[] array, int arrayIndex) - { - Array.Copy(this.array, 0, array, arrayIndex, count); - } - - /// <summary> - /// Removes the specified item from the collection - /// </summary> - /// <param name="item">The item to remove.</param> - /// <returns><c>true</c> if the item was found and removed; <c>false</c> otherwise.</returns> - public bool Remove(T item) - { - int index = IndexOf(item); - if (index == -1) - { - return false; - } - Array.Copy(array, index + 1, array, index, count - index - 1); - count--; - array[count] = default(T); - return true; - } - - /// <summary> - /// Gets the number of elements contained in the collection. - /// </summary> - public int Count => count; - - /// <summary> - /// Gets a value indicating whether the collection is read-only. - /// </summary> - public bool IsReadOnly => false; - - /// <summary> - /// Adds all of the specified values into this collection. - /// </summary> - /// <param name="values">The values to add to this collection.</param> - public void AddRange(IEnumerable<T> values) - { - ProtoPreconditions.CheckNotNull(values, nameof(values)); - - // Optimization 1: If the collection we're adding is already a RepeatedField<T>, - // we know the values are valid. - var otherRepeatedField = values as RepeatedField<T>; - if (otherRepeatedField != null) - { - EnsureSize(count + otherRepeatedField.count); - Array.Copy(otherRepeatedField.array, 0, array, count, otherRepeatedField.count); - count += otherRepeatedField.count; - return; - } - - // Optimization 2: The collection is an ICollection, so we can expand - // just once and ask the collection to copy itself into the array. - var collection = values as ICollection; - if (collection != null) - { - var extraCount = collection.Count; - // For reference types and nullable value types, we need to check that there are no nulls - // present. (This isn't a thread-safe approach, but we don't advertise this is thread-safe.) - // We expect the JITter to optimize this test to true/false, so it's effectively conditional - // specialization. - if (default(T) == null) - { - // TODO: Measure whether iterating once to check and then letting the collection copy - // itself is faster or slower than iterating and adding as we go. For large - // collections this will not be great in terms of cache usage... but the optimized - // copy may be significantly faster than doing it one at a time. - foreach (var item in collection) - { - if (item == null) - { - throw new ArgumentException("Sequence contained null element", nameof(values)); - } - } - } - EnsureSize(count + extraCount); - collection.CopyTo(array, count); - count += extraCount; - return; - } - - // We *could* check for ICollection<T> as well, but very very few collections implement - // ICollection<T> but not ICollection. (HashSet<T> does, for one...) - - // Fall back to a slower path of adding items one at a time. - foreach (T item in values) - { - Add(item); - } - } - - /// <summary> - /// Adds all of the specified values into this collection. This method is present to - /// allow repeated fields to be constructed from queries within collection initializers. - /// Within non-collection-initializer code, consider using the equivalent <see cref="AddRange"/> - /// method instead for clarity. - /// </summary> - /// <param name="values">The values to add to this collection.</param> - public void Add(IEnumerable<T> values) - { - AddRange(values); - } - - /// <summary> - /// Returns an enumerator that iterates through the collection. - /// </summary> - /// <returns> - /// An enumerator that can be used to iterate through the collection. - /// </returns> - public IEnumerator<T> GetEnumerator() - { - for (int i = 0; i < count; i++) - { - yield return array[i]; - } - } - - /// <summary> - /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. - /// </summary> - /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> - /// <returns> - /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. - /// </returns> - public override bool Equals(object obj) - { - return Equals(obj as RepeatedField<T>); - } - - /// <summary> - /// Returns an enumerator that iterates through a collection. - /// </summary> - /// <returns> - /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. - /// </returns> - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - /// <summary> - /// Returns a hash code for this instance. - /// </summary> - /// <returns> - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - /// </returns> - public override int GetHashCode() - { - int hash = 0; - for (int i = 0; i < count; i++) - { - hash = hash * 31 + array[i].GetHashCode(); - } - return hash; - } - - /// <summary> - /// Compares this repeated field with another for equality. - /// </summary> - /// <param name="other">The repeated field to compare this with.</param> - /// <returns><c>true</c> if <paramref name="other"/> refers to an equal repeated field; <c>false</c> otherwise.</returns> - public bool Equals(RepeatedField<T> other) - { - if (ReferenceEquals(other, null)) - { - return false; - } - if (ReferenceEquals(other, this)) - { - return true; - } - if (other.Count != this.Count) - { - return false; - } - EqualityComparer<T> comparer = EqualityComparer; - for (int i = 0; i < count; i++) - { - if (!comparer.Equals(array[i], other.array[i])) - { - return false; - } - } - return true; - } - - /// <summary> - /// Returns the index of the given item within the collection, or -1 if the item is not - /// present. - /// </summary> - /// <param name="item">The item to find in the collection.</param> - /// <returns>The zero-based index of the item, or -1 if it is not found.</returns> - public int IndexOf(T item) - { - ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); - EqualityComparer<T> comparer = EqualityComparer; - for (int i = 0; i < count; i++) - { - if (comparer.Equals(array[i], item)) - { - return i; - } - } - return -1; - } - - /// <summary> - /// Inserts the given item at the specified index. - /// </summary> - /// <param name="index">The index at which to insert the item.</param> - /// <param name="item">The item to insert.</param> - public void Insert(int index, T item) - { - ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); - if (index < 0 || index > count) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - EnsureSize(count + 1); - Array.Copy(array, index, array, index + 1, count - index); - array[index] = item; - count++; - } - - /// <summary> - /// Removes the item at the given index. - /// </summary> - /// <param name="index">The zero-based index of the item to remove.</param> - public void RemoveAt(int index) - { - if (index < 0 || index >= count) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - Array.Copy(array, index + 1, array, index, count - index - 1); - count--; - array[count] = default(T); - } - - /// <summary> - /// Returns a string representation of this repeated field, in the same - /// way as it would be represented by the default JSON formatter. - /// </summary> - public override string ToString() - { - var writer = new StringWriter(); - JsonFormatter.Default.WriteList(writer, this); - return writer.ToString(); - } - - /// <summary> - /// Gets or sets the item at the specified index. - /// </summary> - /// <value> - /// The element at the specified index. - /// </value> - /// <param name="index">The zero-based index of the element to get or set.</param> - /// <returns>The item at the specified index.</returns> - public T this[int index] - { - get - { - if (index < 0 || index >= count) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - return array[index]; - } - set - { - if (index < 0 || index >= count) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - ProtoPreconditions.CheckNotNullUnconstrained(value, nameof(value)); - array[index] = value; - } - } - - #region Explicit interface implementation for IList and ICollection. - bool IList.IsFixedSize => false; - - void ICollection.CopyTo(Array array, int index) - { - Array.Copy(this.array, 0, array, index, count); - } - - bool ICollection.IsSynchronized => false; - - object ICollection.SyncRoot => this; - - object IList.this[int index] - { - get { return this[index]; } - set { this[index] = (T)value; } - } - - int IList.Add(object value) - { - Add((T) value); - return count - 1; - } - - bool IList.Contains(object value) - { - return (value is T && Contains((T)value)); - } - - int IList.IndexOf(object value) - { - if (!(value is T)) - { - return -1; - } - return IndexOf((T)value); - } - - void IList.Insert(int index, object value) - { - Insert(index, (T) value); - } - - void IList.Remove(object value) - { - if (!(value is T)) - { - return; - } - Remove((T)value); - } - #endregion - } -} +#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 System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Security; +using System.Threading; + +namespace Google.Protobuf.Collections +{ + /// <summary> + /// The contents of a repeated field: essentially, a collection with some extra + /// restrictions (no null values) and capabilities (deep cloning). + /// </summary> + /// <remarks> + /// This implementation does not generally prohibit the use of types which are not + /// supported by Protocol Buffers but nor does it guarantee that all operations will work in such cases. + /// </remarks> + /// <typeparam name="T">The element type of the repeated field.</typeparam> + public sealed class RepeatedField<T> : IList<T>, IList, IDeepCloneable<RepeatedField<T>>, IEquatable<RepeatedField<T>> +#if !NET35 + , IReadOnlyList<T> +#endif + { + private static readonly EqualityComparer<T> EqualityComparer = ProtobufEqualityComparers.GetEqualityComparer<T>(); + private static readonly T[] EmptyArray = new T[0]; + private const int MinArraySize = 8; + + private T[] array = EmptyArray; + private int count = 0; + + /// <summary> + /// Creates a deep clone of this repeated field. + /// </summary> + /// <remarks> + /// If the field type is + /// a message type, each element is also cloned; otherwise, it is + /// assumed that the field type is primitive (including string and + /// bytes, both of which are immutable) and so a simple copy is + /// equivalent to a deep clone. + /// </remarks> + /// <returns>A deep clone of this repeated field.</returns> + public RepeatedField<T> Clone() + { + RepeatedField<T> clone = new RepeatedField<T>(); + if (array != EmptyArray) + { + clone.array = (T[])array.Clone(); + IDeepCloneable<T>[] cloneableArray = clone.array as IDeepCloneable<T>[]; + if (cloneableArray != null) + { + for (int i = 0; i < count; i++) + { + clone.array[i] = cloneableArray[i].Clone(); + } + } + } + clone.count = count; + return clone; + } + + /// <summary> + /// Adds the entries from the given input stream, decoding them with the specified codec. + /// </summary> + /// <param name="input">The input stream to read from.</param> + /// <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 = ctx.state.lastTag; + var reader = codec.ValueReader; + // Non-nullable value types can be packed or not. + if (FieldCodec<T>.IsPackedRepeatedField(tag)) + { + int length = ctx.ReadLength(); + if (length > 0) + { + int oldLimit = SegmentedBufferHelper.PushLimit(ref ctx.state, length); + + // If the content is fixed size then we can calculate the length + // of the repeated field and pre-initialize the underlying collection. + // + // Check that the supplied length doesn't exceed the underlying buffer. + // That prevents a malicious length from initializing a very large collection. + if (codec.FixedSize > 0 && length % codec.FixedSize == 0 && ParsingPrimitives.IsDataAvailable(ref ctx.state, length)) + { + EnsureSize(count + (length / codec.FixedSize)); + + while (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state)) + { + // Only FieldCodecs with a fixed size can reach here, and they are all known + // types that don't allow the user to specify a custom reader action. + // reader action will never return null. + array[count++] = reader(ref ctx); + } + } + else + { + // Content is variable size so add until we reach the limit. + while (!SegmentedBufferHelper.IsReachedLimit(ref ctx.state)) + { + Add(reader(ref ctx)); + } + } + SegmentedBufferHelper.PopLimit(ref ctx.state, oldLimit); + } + // Empty packed field. Odd, but valid - just ignore. + } + else + { + // Not packed... (possibly not packable) + do + { + Add(reader(ref ctx)); + } while (ParsingPrimitives.MaybeConsumeTag(ref ctx.buffer, ref ctx.state, tag)); + } + } + + /// <summary> + /// Calculates the size of this collection based on the given codec. + /// </summary> + /// <param name="codec">The codec to use when encoding each field.</param> + /// <returns>The number of bytes that would be written to an output by one of the <c>WriteTo</c> methods, + /// using the same codec.</returns> + public int CalculateSize(FieldCodec<T> codec) + { + if (count == 0) + { + return 0; + } + uint tag = codec.Tag; + if (codec.PackedRepeatedField) + { + int dataSize = CalculatePackedDataSize(codec); + return CodedOutputStream.ComputeRawVarint32Size(tag) + + CodedOutputStream.ComputeLengthSize(dataSize) + + dataSize; + } + else + { + var sizeCalculator = codec.ValueSizeCalculator; + int size = count * CodedOutputStream.ComputeRawVarint32Size(tag); + if (codec.EndTag != 0) + { + size += count * CodedOutputStream.ComputeRawVarint32Size(codec.EndTag); + } + for (int i = 0; i < count; i++) + { + size += sizeCalculator(array[i]); + } + return size; + } + } + + private int CalculatePackedDataSize(FieldCodec<T> codec) + { + int fixedSize = codec.FixedSize; + if (fixedSize == 0) + { + var calculator = codec.ValueSizeCalculator; + int tmp = 0; + for (int i = 0; i < count; i++) + { + tmp += calculator(array[i]); + } + return tmp; + } + else + { + return fixedSize * Count; + } + } + + /// <summary> + /// Writes the contents of this collection to the given <see cref="CodedOutputStream"/>, + /// encoding each value using the specified codec. + /// </summary> + /// <param name="output">The output stream to write to.</param> + /// <param name="codec">The codec to use when encoding each value.</param> + public void WriteTo(CodedOutputStream output, FieldCodec<T> codec) + { + WriteContext.Initialize(output, out WriteContext ctx); + try + { + WriteTo(ref ctx, codec); + } + finally + { + ctx.CopyStateTo(output); + } + } + + /// <summary> + /// Writes the contents of this collection to the given write context, + /// encoding each value using the specified codec. + /// </summary> + /// <param name="ctx">The write context to write to.</param> + /// <param name="codec">The codec to use when encoding each value.</param> + [SecuritySafeCritical] + public void WriteTo(ref WriteContext ctx, FieldCodec<T> codec) + { + if (count == 0) + { + return; + } + var writer = codec.ValueWriter; + var tag = codec.Tag; + if (codec.PackedRepeatedField) + { + // Packed primitive type + int size = CalculatePackedDataSize(codec); + ctx.WriteTag(tag); + ctx.WriteLength(size); + for (int i = 0; i < count; i++) + { + writer(ref ctx, array[i]); + } + } + else + { + // Not packed: a simple tag/value pair for each value. + // Can't use codec.WriteTagAndValue, as that omits default values. + for (int i = 0; i < count; i++) + { + ctx.WriteTag(tag); + writer(ref ctx, array[i]); + if (codec.EndTag != 0) + { + ctx.WriteTag(codec.EndTag); + } + } + } + } + + /// <summary> + /// Gets and sets the capacity of the RepeatedField's internal array. WHen set, the internal array is reallocated to the given capacity. + /// <exception cref="ArgumentOutOfRangeException">The new value is less than Count -or- when Count is less than 0.</exception> + /// </summary> + public int Capacity + { + get { return array.Length; } + set + { + if (value < count) + { + throw new ArgumentOutOfRangeException("Capacity", value, + $"Cannot set Capacity to a value smaller than the current item count, {count}"); + } + + if (value >= 0 && value != array.Length) + { + SetSize(value); + } + } + } + + // May increase the size of the internal array, but will never shrink it. + private void EnsureSize(int size) + { + if (array.Length < size) + { + size = Math.Max(size, MinArraySize); + int newSize = Math.Max(array.Length * 2, size); + SetSize(newSize); + } + } + + // Sets the internal array to an exact size. + private void SetSize(int size) + { + if (size != array.Length) + { + var tmp = new T[size]; + Array.Copy(array, 0, tmp, 0, count); + array = tmp; + } + } + + /// <summary> + /// Adds the specified item to the collection. + /// </summary> + /// <param name="item">The item to add.</param> + public void Add(T item) + { + ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); + EnsureSize(count + 1); + array[count++] = item; + } + + /// <summary> + /// Removes all items from the collection. + /// </summary> + public void Clear() + { + array = EmptyArray; + count = 0; + } + + /// <summary> + /// Determines whether this collection contains the given item. + /// </summary> + /// <param name="item">The item to find.</param> + /// <returns><c>true</c> if this collection contains the given item; <c>false</c> otherwise.</returns> + public bool Contains(T item) + { + return IndexOf(item) != -1; + } + + /// <summary> + /// Copies this collection to the given array. + /// </summary> + /// <param name="array">The array to copy to.</param> + /// <param name="arrayIndex">The first index of the array to copy to.</param> + public void CopyTo(T[] array, int arrayIndex) + { + Array.Copy(this.array, 0, array, arrayIndex, count); + } + + /// <summary> + /// Removes the specified item from the collection + /// </summary> + /// <param name="item">The item to remove.</param> + /// <returns><c>true</c> if the item was found and removed; <c>false</c> otherwise.</returns> + public bool Remove(T item) + { + int index = IndexOf(item); + if (index == -1) + { + return false; + } + Array.Copy(array, index + 1, array, index, count - index - 1); + count--; + array[count] = default(T); + return true; + } + + /// <summary> + /// Gets the number of elements contained in the collection. + /// </summary> + public int Count => count; + + /// <summary> + /// Gets a value indicating whether the collection is read-only. + /// </summary> + public bool IsReadOnly => false; + + /// <summary> + /// Adds all of the specified values into this collection. + /// </summary> + /// <param name="values">The values to add to this collection.</param> + public void AddRange(IEnumerable<T> values) + { + ProtoPreconditions.CheckNotNull(values, nameof(values)); + + // Optimization 1: If the collection we're adding is already a RepeatedField<T>, + // we know the values are valid. + var otherRepeatedField = values as RepeatedField<T>; + if (otherRepeatedField != null) + { + EnsureSize(count + otherRepeatedField.count); + Array.Copy(otherRepeatedField.array, 0, array, count, otherRepeatedField.count); + count += otherRepeatedField.count; + return; + } + + // Optimization 2: The collection is an ICollection, so we can expand + // just once and ask the collection to copy itself into the array. + var collection = values as ICollection; + if (collection != null) + { + var extraCount = collection.Count; + // For reference types and nullable value types, we need to check that there are no nulls + // present. (This isn't a thread-safe approach, but we don't advertise this is thread-safe.) + // We expect the JITter to optimize this test to true/false, so it's effectively conditional + // specialization. + if (default(T) == null) + { + // TODO: Measure whether iterating once to check and then letting the collection copy + // itself is faster or slower than iterating and adding as we go. For large + // collections this will not be great in terms of cache usage... but the optimized + // copy may be significantly faster than doing it one at a time. + foreach (var item in collection) + { + if (item == null) + { + throw new ArgumentException("Sequence contained null element", nameof(values)); + } + } + } + EnsureSize(count + extraCount); + collection.CopyTo(array, count); + count += extraCount; + return; + } + + // We *could* check for ICollection<T> as well, but very very few collections implement + // ICollection<T> but not ICollection. (HashSet<T> does, for one...) + + // Fall back to a slower path of adding items one at a time. + foreach (T item in values) + { + Add(item); + } + } + + /// <summary> + /// Adds all of the specified values into this collection. This method is present to + /// allow repeated fields to be constructed from queries within collection initializers. + /// Within non-collection-initializer code, consider using the equivalent <see cref="AddRange"/> + /// method instead for clarity. + /// </summary> + /// <param name="values">The values to add to this collection.</param> + public void Add(IEnumerable<T> values) + { + AddRange(values); + } + + /// <summary> + /// Returns an enumerator that iterates through the collection. + /// </summary> + /// <returns> + /// An enumerator that can be used to iterate through the collection. + /// </returns> + public IEnumerator<T> GetEnumerator() + { + for (int i = 0; i < count; i++) + { + yield return array[i]; + } + } + + /// <summary> + /// Determines whether the specified <see cref="System.Object" />, is equal to this instance. + /// </summary> + /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> + /// <returns> + /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>. + /// </returns> + public override bool Equals(object obj) + { + return Equals(obj as RepeatedField<T>); + } + + /// <summary> + /// Returns an enumerator that iterates through a collection. + /// </summary> + /// <returns> + /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. + /// </returns> + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// <summary> + /// Returns a hash code for this instance. + /// </summary> + /// <returns> + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// </returns> + public override int GetHashCode() + { + int hash = 0; + for (int i = 0; i < count; i++) + { + hash = hash * 31 + array[i].GetHashCode(); + } + return hash; + } + + /// <summary> + /// Compares this repeated field with another for equality. + /// </summary> + /// <param name="other">The repeated field to compare this with.</param> + /// <returns><c>true</c> if <paramref name="other"/> refers to an equal repeated field; <c>false</c> otherwise.</returns> + public bool Equals(RepeatedField<T> other) + { + if (ReferenceEquals(other, null)) + { + return false; + } + if (ReferenceEquals(other, this)) + { + return true; + } + if (other.Count != this.Count) + { + return false; + } + EqualityComparer<T> comparer = EqualityComparer; + for (int i = 0; i < count; i++) + { + if (!comparer.Equals(array[i], other.array[i])) + { + return false; + } + } + return true; + } + + /// <summary> + /// Returns the index of the given item within the collection, or -1 if the item is not + /// present. + /// </summary> + /// <param name="item">The item to find in the collection.</param> + /// <returns>The zero-based index of the item, or -1 if it is not found.</returns> + public int IndexOf(T item) + { + ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); + EqualityComparer<T> comparer = EqualityComparer; + for (int i = 0; i < count; i++) + { + if (comparer.Equals(array[i], item)) + { + return i; + } + } + return -1; + } + + /// <summary> + /// Inserts the given item at the specified index. + /// </summary> + /// <param name="index">The index at which to insert the item.</param> + /// <param name="item">The item to insert.</param> + public void Insert(int index, T item) + { + ProtoPreconditions.CheckNotNullUnconstrained(item, nameof(item)); + if (index < 0 || index > count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + EnsureSize(count + 1); + Array.Copy(array, index, array, index + 1, count - index); + array[index] = item; + count++; + } + + /// <summary> + /// Removes the item at the given index. + /// </summary> + /// <param name="index">The zero-based index of the item to remove.</param> + public void RemoveAt(int index) + { + if (index < 0 || index >= count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + Array.Copy(array, index + 1, array, index, count - index - 1); + count--; + array[count] = default(T); + } + + /// <summary> + /// Returns a string representation of this repeated field, in the same + /// way as it would be represented by the default JSON formatter. + /// </summary> + public override string ToString() + { + var writer = new StringWriter(); + JsonFormatter.Default.WriteList(writer, this); + return writer.ToString(); + } + + /// <summary> + /// Gets or sets the item at the specified index. + /// </summary> + /// <value> + /// The element at the specified index. + /// </value> + /// <param name="index">The zero-based index of the element to get or set.</param> + /// <returns>The item at the specified index.</returns> + public T this[int index] + { + get + { + if (index < 0 || index >= count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + return array[index]; + } + set + { + if (index < 0 || index >= count) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + ProtoPreconditions.CheckNotNullUnconstrained(value, nameof(value)); + array[index] = value; + } + } + + #region Explicit interface implementation for IList and ICollection. + bool IList.IsFixedSize => false; + + void ICollection.CopyTo(Array array, int index) + { + Array.Copy(this.array, 0, array, index, count); + } + + bool ICollection.IsSynchronized => false; + + object ICollection.SyncRoot => this; + + object IList.this[int index] + { + get { return this[index]; } + set { this[index] = (T)value; } + } + + int IList.Add(object value) + { + Add((T) value); + return count - 1; + } + + bool IList.Contains(object value) + { + return (value is T && Contains((T)value)); + } + + int IList.IndexOf(object value) + { + if (!(value is T)) + { + return -1; + } + return IndexOf((T)value); + } + + void IList.Insert(int index, object value) + { + Insert(index, (T) value); + } + + void IList.Remove(object value) + { + if (!(value is T)) + { + return; + } + Remove((T)value); + } + #endregion + } +}
diff --git a/csharp/src/Google.Protobuf/Extension.cs b/csharp/src/Google.Protobuf/Extension.cs index 6dd1cea..d10a668 100644 --- a/csharp/src/Google.Protobuf/Extension.cs +++ b/csharp/src/Google.Protobuf/Extension.cs
@@ -77,7 +77,7 @@ this.codec = codec; } - internal TValue DefaultValue => codec.DefaultValue; + internal TValue DefaultValue => codec != null ? codec.DefaultValue : default(TValue); internal override Type TargetType => typeof(TTarget);
diff --git a/csharp/src/Google.Protobuf/ExtensionSet.cs b/csharp/src/Google.Protobuf/ExtensionSet.cs index 895b9ae..306e45e 100644 --- a/csharp/src/Google.Protobuf/ExtensionSet.cs +++ b/csharp/src/Google.Protobuf/ExtensionSet.cs
@@ -1,377 +1,428 @@ -#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.Collections; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security; - -namespace Google.Protobuf -{ - /// <summary> - /// Methods for managing <see cref="ExtensionSet{TTarget}"/>s with null checking. - /// - /// Most users will not use this class directly and its API is experimental and subject to change. - /// </summary> - public static class ExtensionSet - { - private static bool TryGetValue<TTarget>(ref ExtensionSet<TTarget> set, Extension extension, out IExtensionValue value) where TTarget : IExtendableMessage<TTarget> - { - if (set == null) - { - value = null; - return false; - } - return set.ValuesByNumber.TryGetValue(extension.FieldNumber, out value); - } - - /// <summary> - /// Gets the value of the specified extension - /// </summary> - public static TValue Get<TTarget, TValue>(ref ExtensionSet<TTarget> set, Extension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> - { - IExtensionValue value; - if (TryGetValue(ref set, extension, out value)) - { - return ((ExtensionValue<TValue>)value).GetValue(); - } - else - { - return extension.DefaultValue; - } - } - - /// <summary> - /// Gets the value of the specified repeated extension or null if it doesn't exist in this set - /// </summary> - public static RepeatedField<TValue> Get<TTarget, TValue>(ref ExtensionSet<TTarget> set, RepeatedExtension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> - { - IExtensionValue value; - if (TryGetValue(ref set, extension, out value)) - { - return ((RepeatedExtensionValue<TValue>)value).GetValue(); - } - else - { - return null; - } - } - - /// <summary> - /// Gets the value of the specified repeated extension, registering it if it doesn't exist - /// </summary> - public static RepeatedField<TValue> GetOrInitialize<TTarget, TValue>(ref ExtensionSet<TTarget> set, RepeatedExtension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> - { - IExtensionValue value; - if (set == null) - { - value = extension.CreateValue(); - set = new ExtensionSet<TTarget>(); - set.ValuesByNumber.Add(extension.FieldNumber, value); - } - else - { - if (!set.ValuesByNumber.TryGetValue(extension.FieldNumber, out value)) - { - value = extension.CreateValue(); - set.ValuesByNumber.Add(extension.FieldNumber, value); - } - } - - return ((RepeatedExtensionValue<TValue>)value).GetValue(); - } - - /// <summary> - /// Sets the value of the specified extension. This will make a new instance of ExtensionSet if the set is null. - /// </summary> - public static void Set<TTarget, TValue>(ref ExtensionSet<TTarget> set, Extension<TTarget, TValue> extension, TValue value) where TTarget : IExtendableMessage<TTarget> - { - ProtoPreconditions.CheckNotNullUnconstrained(value, nameof(value)); - - IExtensionValue extensionValue; - if (set == null) - { - extensionValue = extension.CreateValue(); - set = new ExtensionSet<TTarget>(); - set.ValuesByNumber.Add(extension.FieldNumber, extensionValue); - } - else - { - if (!set.ValuesByNumber.TryGetValue(extension.FieldNumber, out extensionValue)) - { - extensionValue = extension.CreateValue(); - set.ValuesByNumber.Add(extension.FieldNumber, extensionValue); - } - } - - ((ExtensionValue<TValue>)extensionValue).SetValue(value); - } - - /// <summary> - /// Gets whether the value of the specified extension is set - /// </summary> - public static bool Has<TTarget, TValue>(ref ExtensionSet<TTarget> set, Extension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> - { - IExtensionValue value; - return TryGetValue(ref set, extension, out value); - } - - /// <summary> - /// Clears the value of the specified extension - /// </summary> - public static void Clear<TTarget, TValue>(ref ExtensionSet<TTarget> set, Extension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> - { - if (set == null) - { - return; - } - set.ValuesByNumber.Remove(extension.FieldNumber); - if (set.ValuesByNumber.Count == 0) - { - set = null; - } - } - - /// <summary> - /// Clears the value of the specified extension - /// </summary> - public static void Clear<TTarget, TValue>(ref ExtensionSet<TTarget> set, RepeatedExtension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> - { - if (set == null) - { - return; - } - set.ValuesByNumber.Remove(extension.FieldNumber); - if (set.ValuesByNumber.Count == 0) - { - set = null; - } - } - - /// <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, 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(ctx.LastTag); - - IExtensionValue extensionValue; - if (set != null && set.ValuesByNumber.TryGetValue(lastFieldNumber, out extensionValue)) - { - extensionValue.MergeFrom(ref ctx); - return true; - } - else if (ctx.ExtensionRegistry != null && ctx.ExtensionRegistry.ContainsInputField(ctx.LastTag, typeof(TTarget), out extension)) - { - IExtensionValue value = extension.CreateValue(); - value.MergeFrom(ref ctx); - set = (set ?? new ExtensionSet<TTarget>()); - set.ValuesByNumber.Add(extension.FieldNumber, value); - return true; - } - else - { - return false; - } - } - - /// <summary> - /// Merges the second set into the first set, creating a new instance if first is null - /// </summary> - public static void MergeFrom<TTarget>(ref ExtensionSet<TTarget> first, ExtensionSet<TTarget> second) where TTarget : IExtendableMessage<TTarget> - { - if (second == null) - { - return; - } - if (first == null) - { - first = new ExtensionSet<TTarget>(); - } - foreach (var pair in second.ValuesByNumber) - { - IExtensionValue value; - if (first.ValuesByNumber.TryGetValue(pair.Key, out value)) - { - value.MergeFrom(pair.Value); - } - else - { - var cloned = pair.Value.Clone(); - first.ValuesByNumber[pair.Key] = cloned; - } - } - } - - /// <summary> - /// Clones the set into a new set. If the set is null, this returns null - /// </summary> - public static ExtensionSet<TTarget> Clone<TTarget>(ExtensionSet<TTarget> set) where TTarget : IExtendableMessage<TTarget> - { - if (set == null) - { - return null; - } - - var newSet = new ExtensionSet<TTarget>(); - foreach (var pair in set.ValuesByNumber) - { - var cloned = pair.Value.Clone(); - newSet.ValuesByNumber[pair.Key] = cloned; - } - return newSet; - } - } - - /// <summary> - /// Used for keeping track of extensions in messages. - /// <see cref="IExtendableMessage{T}"/> methods route to this set. - /// - /// Most users will not need to use this class directly - /// </summary> - /// <typeparam name="TTarget">The message type that extensions in this set target</typeparam> - public sealed class ExtensionSet<TTarget> where TTarget : IExtendableMessage<TTarget> - { - internal Dictionary<int, IExtensionValue> ValuesByNumber { get; } = new Dictionary<int, IExtensionValue>(); - - /// <summary> - /// Gets a hash code of the set - /// </summary> - public override int GetHashCode() - { - int ret = typeof(TTarget).GetHashCode(); - foreach (KeyValuePair<int, IExtensionValue> field in ValuesByNumber) - { - // Use ^ here to make the field order irrelevant. - int hash = field.Key.GetHashCode() ^ field.Value.GetHashCode(); - ret ^= hash; - } - return ret; - } - - /// <summary> - /// Returns whether this set is equal to the other object - /// </summary> - public override bool Equals(object other) - { - if (ReferenceEquals(this, other)) - { - return true; - } - ExtensionSet<TTarget> otherSet = other as ExtensionSet<TTarget>; - if (ValuesByNumber.Count != otherSet.ValuesByNumber.Count) - { - return false; - } - foreach (var pair in ValuesByNumber) - { - IExtensionValue secondValue; - if (!otherSet.ValuesByNumber.TryGetValue(pair.Key, out secondValue)) - { - return false; - } - if (!pair.Value.Equals(secondValue)) - { - return false; - } - } - return true; - } - - /// <summary> - /// Calculates the size of this extension set - /// </summary> - public int CalculateSize() - { - int size = 0; - foreach (var value in ValuesByNumber.Values) - { - size += value.CalculateSize(); - } - return size; - } - - /// <summary> - /// Writes the extension values in this set to the output stream - /// </summary> - public void WriteTo(CodedOutputStream stream) - { - - WriteContext.Initialize(stream, out WriteContext ctx); - try - { - WriteTo(ref ctx); - } - finally - { - ctx.CopyStateTo(stream); - } - } - - /// <summary> - /// Writes the extension values in this set to the write context - /// </summary> - [SecuritySafeCritical] - public void WriteTo(ref WriteContext ctx) - { - foreach (var value in ValuesByNumber.Values) - { - value.WriteTo(ref ctx); - } - } - - internal bool IsInitialized() - { - return ValuesByNumber.Values.All(v => v.IsInitialized()); - } - } -} +#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.Collections; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Security; + +namespace Google.Protobuf +{ + /// <summary> + /// Methods for managing <see cref="ExtensionSet{TTarget}"/>s with null checking. + /// + /// Most users will not use this class directly and its API is experimental and subject to change. + /// </summary> + public static class ExtensionSet + { + private static bool TryGetValue<TTarget>(ref ExtensionSet<TTarget> set, Extension extension, out IExtensionValue value) where TTarget : IExtendableMessage<TTarget> + { + if (set == null) + { + value = null; + return false; + } + return set.ValuesByNumber.TryGetValue(extension.FieldNumber, out value); + } + + /// <summary> + /// Gets the value of the specified extension + /// </summary> + public static TValue Get<TTarget, TValue>(ref ExtensionSet<TTarget> set, Extension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> + { + IExtensionValue value; + if (TryGetValue(ref set, extension, out value)) + { + // The stored ExtensionValue can be a different type to what is being requested. + // This happens when the same extension proto is compiled in different assemblies. + // To allow consuming assemblies to still get the value when the TValue type is + // different, this get method: + // 1. Attempts to cast the value to the expected ExtensionValue<TValue>. + // This is the usual case. It is used first because it avoids possibly boxing the value. + // 2. Fallback to get the value as object from IExtensionValue then casting. + // This allows for someone to specify a TValue of object. They can then convert + // the values to bytes and reparse using expected value. + // 3. If neither of these work, throw a user friendly error that the types aren't compatible. + if (value is ExtensionValue<TValue> extensionValue) + { + return extensionValue.GetValue(); + } + else if (value.GetValue() is TValue underlyingValue) + { + return underlyingValue; + } + else + { + var valueType = value.GetType().GetTypeInfo(); + if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(ExtensionValue<>)) + { + var storedType = valueType.GenericTypeArguments[0]; + throw new InvalidOperationException( + "The stored extension value has a type of '" + storedType.AssemblyQualifiedName + "'. " + + "This a different from the requested type of '" + typeof(TValue).AssemblyQualifiedName + "'."); + } + else + { + throw new InvalidOperationException("Unexpected extension value type: " + valueType.AssemblyQualifiedName); + } + } + } + else + { + return extension.DefaultValue; + } + } + + /// <summary> + /// Gets the value of the specified repeated extension or null if it doesn't exist in this set + /// </summary> + public static RepeatedField<TValue> Get<TTarget, TValue>(ref ExtensionSet<TTarget> set, RepeatedExtension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> + { + IExtensionValue value; + if (TryGetValue(ref set, extension, out value)) + { + if (value is RepeatedExtensionValue<TValue> extensionValue) + { + return extensionValue.GetValue(); + } + else + { + var valueType = value.GetType().GetTypeInfo(); + if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(RepeatedExtensionValue<>)) + { + var storedType = valueType.GenericTypeArguments[0]; + throw new InvalidOperationException( + "The stored extension value has a type of '" + storedType.AssemblyQualifiedName + "'. " + + "This a different from the requested type of '" + typeof(TValue).AssemblyQualifiedName + "'."); + } + else + { + throw new InvalidOperationException("Unexpected extension value type: " + valueType.AssemblyQualifiedName); + } + } + } + else + { + return null; + } + } + + /// <summary> + /// Gets the value of the specified repeated extension, registering it if it doesn't exist + /// </summary> + public static RepeatedField<TValue> GetOrInitialize<TTarget, TValue>(ref ExtensionSet<TTarget> set, RepeatedExtension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> + { + IExtensionValue value; + if (set == null) + { + value = extension.CreateValue(); + set = new ExtensionSet<TTarget>(); + set.ValuesByNumber.Add(extension.FieldNumber, value); + } + else + { + if (!set.ValuesByNumber.TryGetValue(extension.FieldNumber, out value)) + { + value = extension.CreateValue(); + set.ValuesByNumber.Add(extension.FieldNumber, value); + } + } + + return ((RepeatedExtensionValue<TValue>)value).GetValue(); + } + + /// <summary> + /// Sets the value of the specified extension. This will make a new instance of ExtensionSet if the set is null. + /// </summary> + public static void Set<TTarget, TValue>(ref ExtensionSet<TTarget> set, Extension<TTarget, TValue> extension, TValue value) where TTarget : IExtendableMessage<TTarget> + { + ProtoPreconditions.CheckNotNullUnconstrained(value, nameof(value)); + + IExtensionValue extensionValue; + if (set == null) + { + extensionValue = extension.CreateValue(); + set = new ExtensionSet<TTarget>(); + set.ValuesByNumber.Add(extension.FieldNumber, extensionValue); + } + else + { + if (!set.ValuesByNumber.TryGetValue(extension.FieldNumber, out extensionValue)) + { + extensionValue = extension.CreateValue(); + set.ValuesByNumber.Add(extension.FieldNumber, extensionValue); + } + } + + ((ExtensionValue<TValue>)extensionValue).SetValue(value); + } + + /// <summary> + /// Gets whether the value of the specified extension is set + /// </summary> + public static bool Has<TTarget, TValue>(ref ExtensionSet<TTarget> set, Extension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> + { + IExtensionValue value; + return TryGetValue(ref set, extension, out value); + } + + /// <summary> + /// Clears the value of the specified extension + /// </summary> + public static void Clear<TTarget, TValue>(ref ExtensionSet<TTarget> set, Extension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> + { + if (set == null) + { + return; + } + set.ValuesByNumber.Remove(extension.FieldNumber); + if (set.ValuesByNumber.Count == 0) + { + set = null; + } + } + + /// <summary> + /// Clears the value of the specified extension + /// </summary> + public static void Clear<TTarget, TValue>(ref ExtensionSet<TTarget> set, RepeatedExtension<TTarget, TValue> extension) where TTarget : IExtendableMessage<TTarget> + { + if (set == null) + { + return; + } + set.ValuesByNumber.Remove(extension.FieldNumber); + if (set.ValuesByNumber.Count == 0) + { + set = null; + } + } + + /// <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, 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(ctx.LastTag); + + IExtensionValue extensionValue; + if (set != null && set.ValuesByNumber.TryGetValue(lastFieldNumber, out extensionValue)) + { + extensionValue.MergeFrom(ref ctx); + return true; + } + else if (ctx.ExtensionRegistry != null && ctx.ExtensionRegistry.ContainsInputField(ctx.LastTag, typeof(TTarget), out extension)) + { + IExtensionValue value = extension.CreateValue(); + value.MergeFrom(ref ctx); + set = (set ?? new ExtensionSet<TTarget>()); + set.ValuesByNumber.Add(extension.FieldNumber, value); + return true; + } + else + { + return false; + } + } + + /// <summary> + /// Merges the second set into the first set, creating a new instance if first is null + /// </summary> + public static void MergeFrom<TTarget>(ref ExtensionSet<TTarget> first, ExtensionSet<TTarget> second) where TTarget : IExtendableMessage<TTarget> + { + if (second == null) + { + return; + } + if (first == null) + { + first = new ExtensionSet<TTarget>(); + } + foreach (var pair in second.ValuesByNumber) + { + IExtensionValue value; + if (first.ValuesByNumber.TryGetValue(pair.Key, out value)) + { + value.MergeFrom(pair.Value); + } + else + { + var cloned = pair.Value.Clone(); + first.ValuesByNumber[pair.Key] = cloned; + } + } + } + + /// <summary> + /// Clones the set into a new set. If the set is null, this returns null + /// </summary> + public static ExtensionSet<TTarget> Clone<TTarget>(ExtensionSet<TTarget> set) where TTarget : IExtendableMessage<TTarget> + { + if (set == null) + { + return null; + } + + var newSet = new ExtensionSet<TTarget>(); + foreach (var pair in set.ValuesByNumber) + { + var cloned = pair.Value.Clone(); + newSet.ValuesByNumber[pair.Key] = cloned; + } + return newSet; + } + } + + /// <summary> + /// Used for keeping track of extensions in messages. + /// <see cref="IExtendableMessage{T}"/> methods route to this set. + /// + /// Most users will not need to use this class directly + /// </summary> + /// <typeparam name="TTarget">The message type that extensions in this set target</typeparam> + public sealed class ExtensionSet<TTarget> where TTarget : IExtendableMessage<TTarget> + { + internal Dictionary<int, IExtensionValue> ValuesByNumber { get; } = new Dictionary<int, IExtensionValue>(); + + /// <summary> + /// Gets a hash code of the set + /// </summary> + public override int GetHashCode() + { + int ret = typeof(TTarget).GetHashCode(); + foreach (KeyValuePair<int, IExtensionValue> field in ValuesByNumber) + { + // Use ^ here to make the field order irrelevant. + int hash = field.Key.GetHashCode() ^ field.Value.GetHashCode(); + ret ^= hash; + } + return ret; + } + + /// <summary> + /// Returns whether this set is equal to the other object + /// </summary> + public override bool Equals(object other) + { + if (ReferenceEquals(this, other)) + { + return true; + } + ExtensionSet<TTarget> otherSet = other as ExtensionSet<TTarget>; + if (ValuesByNumber.Count != otherSet.ValuesByNumber.Count) + { + return false; + } + foreach (var pair in ValuesByNumber) + { + IExtensionValue secondValue; + if (!otherSet.ValuesByNumber.TryGetValue(pair.Key, out secondValue)) + { + return false; + } + if (!pair.Value.Equals(secondValue)) + { + return false; + } + } + return true; + } + + /// <summary> + /// Calculates the size of this extension set + /// </summary> + public int CalculateSize() + { + int size = 0; + foreach (var value in ValuesByNumber.Values) + { + size += value.CalculateSize(); + } + return size; + } + + /// <summary> + /// Writes the extension values in this set to the output stream + /// </summary> + public void WriteTo(CodedOutputStream stream) + { + + WriteContext.Initialize(stream, out WriteContext ctx); + try + { + WriteTo(ref ctx); + } + finally + { + ctx.CopyStateTo(stream); + } + } + + /// <summary> + /// Writes the extension values in this set to the write context + /// </summary> + [SecuritySafeCritical] + public void WriteTo(ref WriteContext ctx) + { + foreach (var value in ValuesByNumber.Values) + { + value.WriteTo(ref ctx); + } + } + + internal bool IsInitialized() + { + return ValuesByNumber.Values.All(v => v.IsInitialized()); + } + } +}
diff --git a/csharp/src/Google.Protobuf/ExtensionValue.cs b/csharp/src/Google.Protobuf/ExtensionValue.cs index 5257c4c..1329b2f 100644 --- a/csharp/src/Google.Protobuf/ExtensionValue.cs +++ b/csharp/src/Google.Protobuf/ExtensionValue.cs
@@ -44,6 +44,7 @@ void WriteTo(ref WriteContext ctx); int CalculateSize(); bool IsInitialized(); + object GetValue(); } internal sealed class ExtensionValue<T> : IExtensionValue @@ -118,6 +119,8 @@ public T GetValue() => field; + object IExtensionValue.GetValue() => field; + public void SetValue(T value) { field = value; @@ -201,6 +204,8 @@ public RepeatedField<T> GetValue() => field; + object IExtensionValue.GetValue() => field; + public bool IsInitialized() { for (int i = 0; i < field.Count; i++)
diff --git a/csharp/src/Google.Protobuf/FrameworkPortability.cs b/csharp/src/Google.Protobuf/FrameworkPortability.cs index 9498dbe..1606411 100644 --- a/csharp/src/Google.Protobuf/FrameworkPortability.cs +++ b/csharp/src/Google.Protobuf/FrameworkPortability.cs
@@ -1,49 +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 - -using System; -using System.Text.RegularExpressions; - -namespace Google.Protobuf -{ - /// <summary> - /// Class containing helpful workarounds for various platform compatibility - /// </summary> - internal static class FrameworkPortability - { - // The value of RegexOptions.Compiled is 8. We can test for the presence at - // execution time using Enum.IsDefined, so a single build will do the right thing - // on each platform. (RegexOptions.Compiled isn't supported by PCLs.) - internal static readonly RegexOptions CompiledRegexWhereAvailable = - Enum.IsDefined(typeof(RegexOptions), 8) ? (RegexOptions)8 : RegexOptions.None; - } +#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.Text.RegularExpressions; + +namespace Google.Protobuf +{ + /// <summary> + /// Class containing helpful workarounds for various platform compatibility + /// </summary> + internal static class FrameworkPortability + { + // The value of RegexOptions.Compiled is 8. We can test for the presence at + // execution time using Enum.IsDefined, so a single build will do the right thing + // on each platform. (RegexOptions.Compiled isn't supported by PCLs.) + internal static readonly RegexOptions CompiledRegexWhereAvailable = + Enum.IsDefined(typeof(RegexOptions), 8) ? (RegexOptions)8 : RegexOptions.None; + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/IMessage.cs b/csharp/src/Google.Protobuf/IMessage.cs index d089f94..3e644c1 100644 --- a/csharp/src/Google.Protobuf/IMessage.cs +++ b/csharp/src/Google.Protobuf/IMessage.cs
@@ -1,87 +1,87 @@ -#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 Google.Protobuf.Reflection; - -namespace Google.Protobuf -{ - /// <summary> - /// Interface for a Protocol Buffers message, supporting - /// basic operations required for serialization. - /// </summary> - public interface IMessage - { - /// <summary> - /// Merges the data from the specified coded input stream with the current message. - /// </summary> - /// <remarks>See the user guide for precise merge semantics.</remarks> - /// <param name="input"></param> - void MergeFrom(CodedInputStream input); - - /// <summary> - /// Writes the data to the given coded output stream. - /// </summary> - /// <param name="output">Coded output stream to write the data to. Must not be null.</param> - void WriteTo(CodedOutputStream output); - - /// <summary> - /// Calculates the size of this message in Protocol Buffer wire format, in bytes. - /// </summary> - /// <returns>The number of bytes required to write this message - /// to a coded output stream.</returns> - int CalculateSize(); - - /// <summary> - /// Descriptor for this message. All instances are expected to return the same descriptor, - /// and for generated types this will be an explicitly-implemented member, returning the - /// same value as the static property declared on the type. - /// </summary> - MessageDescriptor Descriptor { get; } - } - - /// <summary> - /// Generic interface for a Protocol Buffers message, - /// where the type parameter is expected to be the same type as - /// the implementation class. - /// </summary> - /// <typeparam name="T">The message type.</typeparam> - public interface IMessage<T> : IMessage, IEquatable<T>, IDeepCloneable<T> where T : IMessage<T> - { - /// <summary> - /// Merges the given message into this one. - /// </summary> - /// <remarks>See the user guide for precise merge semantics.</remarks> - /// <param name="message">The message to merge with this one. Must not be null.</param> - void MergeFrom(T message); - } -} +#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 Google.Protobuf.Reflection; + +namespace Google.Protobuf +{ + /// <summary> + /// Interface for a Protocol Buffers message, supporting + /// basic operations required for serialization. + /// </summary> + public interface IMessage + { + /// <summary> + /// Merges the data from the specified coded input stream with the current message. + /// </summary> + /// <remarks>See the user guide for precise merge semantics.</remarks> + /// <param name="input"></param> + void MergeFrom(CodedInputStream input); + + /// <summary> + /// Writes the data to the given coded output stream. + /// </summary> + /// <param name="output">Coded output stream to write the data to. Must not be null.</param> + void WriteTo(CodedOutputStream output); + + /// <summary> + /// Calculates the size of this message in Protocol Buffer wire format, in bytes. + /// </summary> + /// <returns>The number of bytes required to write this message + /// to a coded output stream.</returns> + int CalculateSize(); + + /// <summary> + /// Descriptor for this message. All instances are expected to return the same descriptor, + /// and for generated types this will be an explicitly-implemented member, returning the + /// same value as the static property declared on the type. + /// </summary> + MessageDescriptor Descriptor { get; } + } + + /// <summary> + /// Generic interface for a Protocol Buffers message, + /// where the type parameter is expected to be the same type as + /// the implementation class. + /// </summary> + /// <typeparam name="T">The message type.</typeparam> + public interface IMessage<T> : IMessage, IEquatable<T>, IDeepCloneable<T> where T : IMessage<T> + { + /// <summary> + /// Merges the given message into this one. + /// </summary> + /// <remarks>See the user guide for precise merge semantics.</remarks> + /// <param name="message">The message to merge with this one. Must not be null.</param> + void MergeFrom(T message); + } +}
diff --git a/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs b/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs index c5ffe9b..6a3dbd6 100644 --- a/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs +++ b/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs
@@ -1,140 +1,140 @@ -#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.IO; - -namespace Google.Protobuf -{ - /// <summary> - /// Thrown when a protocol message being parsed is invalid in some way, - /// e.g. it contains a malformed varint or a negative byte length. - /// </summary> - public sealed class InvalidProtocolBufferException : IOException - { - internal InvalidProtocolBufferException(string message) - : base(message) - { - } - - internal InvalidProtocolBufferException(string message, Exception innerException) - : base(message, innerException) - { - } - - internal static InvalidProtocolBufferException MoreDataAvailable() - { - return new InvalidProtocolBufferException( - "Completed reading a message while more data was available in the stream."); - } - - internal static InvalidProtocolBufferException TruncatedMessage() - { - return new InvalidProtocolBufferException( - "While parsing a protocol message, the input ended unexpectedly " + - "in the middle of a field. This could mean either that the " + - "input has been truncated or that an embedded message " + - "misreported its own length."); - } - - internal static InvalidProtocolBufferException NegativeSize() - { - return new InvalidProtocolBufferException( - "CodedInputStream encountered an embedded string or message " + - "which claimed to have negative size."); - } - - internal static InvalidProtocolBufferException MalformedVarint() - { - return new InvalidProtocolBufferException( - "CodedInputStream encountered a malformed varint."); - } - - /// <summary> - /// Creates an exception for an error condition of an invalid tag being encountered. - /// </summary> - internal static InvalidProtocolBufferException InvalidTag() - { - return new InvalidProtocolBufferException( - "Protocol message contained an invalid tag (zero)."); - } - - internal static InvalidProtocolBufferException InvalidWireType() - { - return new InvalidProtocolBufferException( - "Protocol message contained a tag with an invalid wire type."); - } - - internal static InvalidProtocolBufferException InvalidBase64(Exception innerException) - { - return new InvalidProtocolBufferException("Invalid base64 data", innerException); - } - - internal static InvalidProtocolBufferException InvalidEndTag() - { - return new InvalidProtocolBufferException( - "Protocol message end-group tag did not match expected tag."); - } - - internal static InvalidProtocolBufferException RecursionLimitExceeded() - { - return new InvalidProtocolBufferException( - "Protocol message had too many levels of nesting. May be malicious. " + - "Use CodedInputStream.SetRecursionLimit() to increase the depth limit."); - } - - internal static InvalidProtocolBufferException JsonRecursionLimitExceeded() - { - return new InvalidProtocolBufferException( - "Protocol message had too many levels of nesting. May be malicious. " + - "Use JsonParser.Settings to increase the depth limit."); - } - - internal static InvalidProtocolBufferException SizeLimitExceeded() - { - return new InvalidProtocolBufferException( - "Protocol message was too large. May be malicious. " + - "Use CodedInputStream.SetSizeLimit() to increase the size limit."); - } - - internal static InvalidProtocolBufferException InvalidMessageStreamTag() - { - return new InvalidProtocolBufferException( - "Stream of protocol messages had invalid tag. Expected tag is length-delimited field 1."); - } - - internal static InvalidProtocolBufferException MissingFields() - { - return new InvalidProtocolBufferException("Message was missing required fields"); - } -} +#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.IO; + +namespace Google.Protobuf +{ + /// <summary> + /// Thrown when a protocol message being parsed is invalid in some way, + /// e.g. it contains a malformed varint or a negative byte length. + /// </summary> + public sealed class InvalidProtocolBufferException : IOException + { + internal InvalidProtocolBufferException(string message) + : base(message) + { + } + + internal InvalidProtocolBufferException(string message, Exception innerException) + : base(message, innerException) + { + } + + internal static InvalidProtocolBufferException MoreDataAvailable() + { + return new InvalidProtocolBufferException( + "Completed reading a message while more data was available in the stream."); + } + + internal static InvalidProtocolBufferException TruncatedMessage() + { + return new InvalidProtocolBufferException( + "While parsing a protocol message, the input ended unexpectedly " + + "in the middle of a field. This could mean either that the " + + "input has been truncated or that an embedded message " + + "misreported its own length."); + } + + internal static InvalidProtocolBufferException NegativeSize() + { + return new InvalidProtocolBufferException( + "CodedInputStream encountered an embedded string or message " + + "which claimed to have negative size."); + } + + internal static InvalidProtocolBufferException MalformedVarint() + { + return new InvalidProtocolBufferException( + "CodedInputStream encountered a malformed varint."); + } + + /// <summary> + /// Creates an exception for an error condition of an invalid tag being encountered. + /// </summary> + internal static InvalidProtocolBufferException InvalidTag() + { + return new InvalidProtocolBufferException( + "Protocol message contained an invalid tag (zero)."); + } + + internal static InvalidProtocolBufferException InvalidWireType() + { + return new InvalidProtocolBufferException( + "Protocol message contained a tag with an invalid wire type."); + } + + internal static InvalidProtocolBufferException InvalidBase64(Exception innerException) + { + return new InvalidProtocolBufferException("Invalid base64 data", innerException); + } + + internal static InvalidProtocolBufferException InvalidEndTag() + { + return new InvalidProtocolBufferException( + "Protocol message end-group tag did not match expected tag."); + } + + internal static InvalidProtocolBufferException RecursionLimitExceeded() + { + return new InvalidProtocolBufferException( + "Protocol message had too many levels of nesting. May be malicious. " + + "Use CodedInputStream.SetRecursionLimit() to increase the depth limit."); + } + + internal static InvalidProtocolBufferException JsonRecursionLimitExceeded() + { + return new InvalidProtocolBufferException( + "Protocol message had too many levels of nesting. May be malicious. " + + "Use JsonParser.Settings to increase the depth limit."); + } + + internal static InvalidProtocolBufferException SizeLimitExceeded() + { + return new InvalidProtocolBufferException( + "Protocol message was too large. May be malicious. " + + "Use CodedInputStream.SetSizeLimit() to increase the size limit."); + } + + internal static InvalidProtocolBufferException InvalidMessageStreamTag() + { + return new InvalidProtocolBufferException( + "Stream of protocol messages had invalid tag. Expected tag is length-delimited field 1."); + } + + internal static InvalidProtocolBufferException MissingFields() + { + return new InvalidProtocolBufferException("Message was missing required fields"); + } +} } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs index db7dc5c..16f7c5a 100644 --- a/csharp/src/Google.Protobuf/JsonFormatter.cs +++ b/csharp/src/Google.Protobuf/JsonFormatter.cs
@@ -1,4 +1,4 @@ -#region Copyright notice and license +#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/ @@ -233,13 +233,13 @@ writer.Write(PropertySeparator); } - if (settings.PreserveProtoFieldNames) - { - WriteString(writer, accessor.Descriptor.Name); + if (settings.PreserveProtoFieldNames) + { + WriteString(writer, accessor.Descriptor.Name); } - else - { - WriteString(writer, accessor.Descriptor.JsonName); + else + { + WriteString(writer, accessor.Descriptor.JsonName); } writer.Write(NameValueSeparator); WriteValue(writer, value); @@ -823,8 +823,8 @@ /// </summary> public bool FormatEnumsAsIntegers { get; } - /// <summary> - /// Whether to use the original proto field names as defined in the .proto file. Defaults to false. + /// <summary> + /// Whether to use the original proto field names as defined in the .proto file. Defaults to false. /// </summary> public bool PreserveProtoFieldNames { get; } @@ -884,9 +884,9 @@ /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param> public Settings WithFormatEnumsAsIntegers(bool formatEnumsAsIntegers) => new Settings(FormatDefaultValues, TypeRegistry, formatEnumsAsIntegers, PreserveProtoFieldNames); - /// <summary> - /// Creates a new <see cref="Settings"/> object with the specified field name formatting option and the current settings. - /// </summary> + /// <summary> + /// Creates a new <see cref="Settings"/> object with the specified field name formatting option and the current settings. + /// </summary> /// <param name="preserveProtoFieldNames"><c>true</c> to preserve proto field names; <c>false</c> to convert them to lowerCamelCase.</param> public Settings WithPreserveProtoFieldNames(bool preserveProtoFieldNames) => new Settings(FormatDefaultValues, TypeRegistry, FormatEnumsAsIntegers, preserveProtoFieldNames); }
diff --git a/csharp/src/Google.Protobuf/ObjectIntPair.cs b/csharp/src/Google.Protobuf/ObjectIntPair.cs index b98d93a..b61fc68 100644 --- a/csharp/src/Google.Protobuf/ObjectIntPair.cs +++ b/csharp/src/Google.Protobuf/ObjectIntPair.cs
@@ -1,40 +1,40 @@ -using System; - -namespace Google.Protobuf -{ +using System; + +namespace Google.Protobuf +{ /// <summary> /// Struct used to hold the keys for the fieldByNumber table in DescriptorPool and the keys for the /// extensionByNumber table in ExtensionRegistry. - /// </summary> - internal struct ObjectIntPair<T> : IEquatable<ObjectIntPair<T>> where T : class - { - private readonly int number; - private readonly T obj; - - internal ObjectIntPair(T obj, int number) - { - this.number = number; - this.obj = obj; - } - - public bool Equals(ObjectIntPair<T> other) - { - return obj == other.obj - && number == other.number; - } - - public override bool Equals(object obj) - { - if (obj is ObjectIntPair<T>) - { - return Equals((ObjectIntPair<T>)obj); - } - return false; - } - - public override int GetHashCode() - { - return obj.GetHashCode() * ((1 << 16) - 1) + number; - } - } -} + /// </summary> + internal struct ObjectIntPair<T> : IEquatable<ObjectIntPair<T>> where T : class + { + private readonly int number; + private readonly T obj; + + internal ObjectIntPair(T obj, int number) + { + this.number = number; + this.obj = obj; + } + + public bool Equals(ObjectIntPair<T> other) + { + return obj == other.obj + && number == other.number; + } + + public override bool Equals(object obj) + { + if (obj is ObjectIntPair<T>) + { + return Equals((ObjectIntPair<T>)obj); + } + return false; + } + + public override int GetHashCode() + { + return obj.GetHashCode() * ((1 << 16) - 1) + number; + } + } +}
diff --git a/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs b/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs index 130bcf0..4328e2e 100644 --- a/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs +++ b/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs
@@ -1,56 +1,56 @@ -#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.Runtime.CompilerServices; -using System.Security; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -#if !NCRUNCH -[assembly: AllowPartiallyTrustedCallers] -#endif - -[assembly: InternalsVisibleTo("Google.Protobuf.Test, PublicKey=" + - "002400000480000094000000060200000024000052534131000400000100010025800fbcfc63a1" + - "7c66b303aae80b03a6beaa176bb6bef883be436f2a1579edd80ce23edf151a1f4ced97af83abcd" + - "981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" + - "b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" + - "c5ae9cb6")] - -[assembly: InternalsVisibleTo("Google.Protobuf.Benchmarks, PublicKey=" + - "002400000480000094000000060200000024000052534131000400000100010025800fbcfc63a1" + - "7c66b303aae80b03a6beaa176bb6bef883be436f2a1579edd80ce23edf151a1f4ced97af83abcd" + - "981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" + - "b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" + - "c5ae9cb6")] +#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.Runtime.CompilerServices; +using System.Security; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +#if !NCRUNCH +[assembly: AllowPartiallyTrustedCallers] +#endif + +[assembly: InternalsVisibleTo("Google.Protobuf.Test, PublicKey=" + + "002400000480000094000000060200000024000052534131000400000100010025800fbcfc63a1" + + "7c66b303aae80b03a6beaa176bb6bef883be436f2a1579edd80ce23edf151a1f4ced97af83abcd" + + "981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" + + "b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" + + "c5ae9cb6")] + +[assembly: InternalsVisibleTo("Google.Protobuf.Benchmarks, PublicKey=" + + "002400000480000094000000060200000024000052534131000400000100010025800fbcfc63a1" + + "7c66b303aae80b03a6beaa176bb6bef883be436f2a1579edd80ce23edf151a1f4ced97af83abcd" + + "981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" + + "b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" + + "c5ae9cb6")]
diff --git a/csharp/src/Google.Protobuf/ProtoPreconditions.cs b/csharp/src/Google.Protobuf/ProtoPreconditions.cs index 590a3bb..1814b8b 100644 --- a/csharp/src/Google.Protobuf/ProtoPreconditions.cs +++ b/csharp/src/Google.Protobuf/ProtoPreconditions.cs
@@ -1,79 +1,79 @@ -#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; - -namespace Google.Protobuf -{ - /// <summary> - /// Helper methods for throwing exceptions when preconditions are not met. - /// </summary> - /// <remarks> - /// This class is used internally and by generated code; it is not particularly - /// expected to be used from application code, although nothing prevents it - /// from being used that way. - /// </remarks> - public static class ProtoPreconditions - { - /// <summary> - /// Throws an ArgumentNullException if the given value is null, otherwise - /// return the value to the caller. - /// </summary> - public static T CheckNotNull<T>(T value, string name) where T : class - { - if (value == null) - { - throw new ArgumentNullException(name); - } - return value; - } - - /// <summary> - /// Throws an ArgumentNullException if the given value is null, otherwise - /// return the value to the caller. - /// </summary> - /// <remarks> - /// This is equivalent to <see cref="CheckNotNull{T}(T, string)"/> but without the type parameter - /// constraint. In most cases, the constraint is useful to prevent you from calling CheckNotNull - /// with a value type - but it gets in the way if either you want to use it with a nullable - /// value type, or you want to use it with an unconstrained type parameter. - /// </remarks> - internal static T CheckNotNullUnconstrained<T>(T value, string name) - { - if (value == null) - { - throw new ArgumentNullException(name); - } - return value; - } - } +#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; + +namespace Google.Protobuf +{ + /// <summary> + /// Helper methods for throwing exceptions when preconditions are not met. + /// </summary> + /// <remarks> + /// This class is used internally and by generated code; it is not particularly + /// expected to be used from application code, although nothing prevents it + /// from being used that way. + /// </remarks> + public static class ProtoPreconditions + { + /// <summary> + /// Throws an ArgumentNullException if the given value is null, otherwise + /// return the value to the caller. + /// </summary> + public static T CheckNotNull<T>(T value, string name) where T : class + { + if (value == null) + { + throw new ArgumentNullException(name); + } + return value; + } + + /// <summary> + /// Throws an ArgumentNullException if the given value is null, otherwise + /// return the value to the caller. + /// </summary> + /// <remarks> + /// This is equivalent to <see cref="CheckNotNull{T}(T, string)"/> but without the type parameter + /// constraint. In most cases, the constraint is useful to prevent you from calling CheckNotNull + /// with a value type - but it gets in the way if either you want to use it with a nullable + /// value type, or you want to use it with an unconstrained type parameter. + /// </remarks> + internal static T CheckNotNullUnconstrained<T>(T value, string name) + { + if (value == null) + { + throw new ArgumentNullException(name); + } + return value; + } + } } \ No newline at end of file
diff --git a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs index cd4d095..5967a4f 100644 --- a/csharp/src/Google.Protobuf/Reflection/Descriptor.cs +++ b/csharp/src/Google.Protobuf/Reflection/Descriptor.cs
@@ -9611,8 +9611,8 @@ /// The name of the uninterpreted option. Each string represents a segment in /// a dot-separated name. is_extension is true iff a segment represents an /// extension (denoted with parentheses in options specs in .proto files). - /// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - /// "foo.(bar.baz).qux". + /// E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + /// "foo.(bar.baz).moo". /// </summary> public sealed partial class NamePart : pb::IMessage<NamePart> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE @@ -10241,13 +10241,13 @@ /// // Comment attached to baz. /// // Another line attached to baz. /// - /// // Comment attached to qux. + /// // Comment attached to moo. /// // - /// // Another line attached to qux. - /// optional double qux = 4; + /// // Another line attached to moo. + /// optional double moo = 4; /// /// // Detached comment for corge. This is not leading or trailing comments - /// // to qux or corge because there are blank lines separating it from + /// // to moo or corge because there are blank lines separating it from /// // both. /// /// // Detached comment for corge paragraph 2.
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs index 49f2599..5e7b6d5 100644 --- a/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs +++ b/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs
@@ -1,4 +1,4 @@ -#region Copyright notice and license +#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/ @@ -67,15 +67,15 @@ return lastSlash == -1 ? "" : typeUrl.Substring(lastSlash + 1); } - /// <summary> - /// Returns a bool indictating whether this Any message is of the target message type - /// </summary> - /// <param name="descriptor">The descriptor of the message type</param> + /// <summary> + /// Returns a bool indictating whether this Any message is of the target message type + /// </summary> + /// <param name="descriptor">The descriptor of the message type</param> /// <returns><c>true</c> if the type name matches the descriptor's full name or <c>false</c> otherwise</returns> - public bool Is(MessageDescriptor descriptor) - { - ProtoPreconditions.CheckNotNull(descriptor, nameof(descriptor)); - return GetTypeName(TypeUrl) == descriptor.FullName; + public bool Is(MessageDescriptor descriptor) + { + ProtoPreconditions.CheckNotNull(descriptor, nameof(descriptor)); + return GetTypeName(TypeUrl) == descriptor.FullName; } /// <summary>
diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs index 073b59e..08f4a84 100644 --- a/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs
@@ -47,8 +47,6 @@ /// service Foo { /// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); /// } - /// - /// The JSON representation for `Empty` is empty JSON object `{}`. /// </summary> public sealed partial class Empty : pb::IMessage<Empty> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
diff --git a/csharp/src/Google.Protobuf/WireFormat.cs b/csharp/src/Google.Protobuf/WireFormat.cs index 201fd16..7cd2ada 100644 --- a/csharp/src/Google.Protobuf/WireFormat.cs +++ b/csharp/src/Google.Protobuf/WireFormat.cs
@@ -1,104 +1,104 @@ -#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 -{ - /// <summary> - /// This class is used internally by the Protocol Buffer Library and generated - /// message implementations. It is public only for the sake of those generated - /// messages. Others should not use this class directly. - /// <para> - /// This class contains constants and helper functions useful for dealing with - /// the Protocol Buffer wire format. - /// </para> - /// </summary> - public static class WireFormat - { - /// <summary> - /// Wire types within protobuf encoding. - /// </summary> - public enum WireType : uint - { - /// <summary> - /// Variable-length integer. - /// </summary> - Varint = 0, - /// <summary> - /// A fixed-length 64-bit value. - /// </summary> - Fixed64 = 1, - /// <summary> - /// A length-delimited value, i.e. a length followed by that many bytes of data. - /// </summary> - LengthDelimited = 2, - /// <summary> - /// A "start group" value - /// </summary> - StartGroup = 3, - /// <summary> - /// An "end group" value - /// </summary> - EndGroup = 4, - /// <summary> - /// A fixed-length 32-bit value. - /// </summary> - Fixed32 = 5 - } - - private const int TagTypeBits = 3; - private const uint TagTypeMask = (1 << TagTypeBits) - 1; - - /// <summary> - /// Given a tag value, determines the wire type (lower 3 bits). - /// </summary> - public static WireType GetTagWireType(uint tag) - { - return (WireType) (tag & TagTypeMask); - } - - /// <summary> - /// Given a tag value, determines the field number (the upper 29 bits). - /// </summary> - public static int GetTagFieldNumber(uint tag) - { - return (int) (tag >> TagTypeBits); - } - - /// <summary> - /// Makes a tag value given a field number and wire type. - /// </summary> - public static uint MakeTag(int fieldNumber, WireType wireType) - { - return (uint) (fieldNumber << TagTypeBits) | (uint) wireType; - } - } +#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 +{ + /// <summary> + /// This class is used internally by the Protocol Buffer Library and generated + /// message implementations. It is public only for the sake of those generated + /// messages. Others should not use this class directly. + /// <para> + /// This class contains constants and helper functions useful for dealing with + /// the Protocol Buffer wire format. + /// </para> + /// </summary> + public static class WireFormat + { + /// <summary> + /// Wire types within protobuf encoding. + /// </summary> + public enum WireType : uint + { + /// <summary> + /// Variable-length integer. + /// </summary> + Varint = 0, + /// <summary> + /// A fixed-length 64-bit value. + /// </summary> + Fixed64 = 1, + /// <summary> + /// A length-delimited value, i.e. a length followed by that many bytes of data. + /// </summary> + LengthDelimited = 2, + /// <summary> + /// A "start group" value + /// </summary> + StartGroup = 3, + /// <summary> + /// An "end group" value + /// </summary> + EndGroup = 4, + /// <summary> + /// A fixed-length 32-bit value. + /// </summary> + Fixed32 = 5 + } + + private const int TagTypeBits = 3; + private const uint TagTypeMask = (1 << TagTypeBits) - 1; + + /// <summary> + /// Given a tag value, determines the wire type (lower 3 bits). + /// </summary> + public static WireType GetTagWireType(uint tag) + { + return (WireType) (tag & TagTypeMask); + } + + /// <summary> + /// Given a tag value, determines the field number (the upper 29 bits). + /// </summary> + public static int GetTagFieldNumber(uint tag) + { + return (int) (tag >> TagTypeBits); + } + + /// <summary> + /// Makes a tag value given a field number and wire type. + /// </summary> + public static uint MakeTag(int fieldNumber, WireType wireType) + { + return (uint) (fieldNumber << TagTypeBits) | (uint) wireType; + } + } } \ No newline at end of file
diff --git a/docs/implementing_proto3_presence.md b/docs/implementing_proto3_presence.md index ae8b369..7c3e213 100644 --- a/docs/implementing_proto3_presence.md +++ b/docs/implementing_proto3_presence.md
@@ -30,7 +30,7 @@ inside Google and [from open-source users](https://github.com/protocolbuffers/protobuf/issues/1606). The [proto3 wrapper -types](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/wrappers.proto) +types](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/wrappers.proto) were previously the only supported presence mechanism for proto3. Users have pointed to both efficiency and usability issues with the wrapper types.
diff --git a/docs/jvm_aot.md b/docs/jvm_aot.md index 4eb682f..304c829 100644 --- a/docs/jvm_aot.md +++ b/docs/jvm_aot.md
@@ -4,7 +4,7 @@ Protobuf for the JVM uses reflection and some of its target classes are not possible to determine in advance. Historically, there were good reasons to use reflection based on APIs that were published effectively requiring them, and this situation is unlikely to change. -[The Lite version of protobuf for the JVM](https://github.com/protocolbuffers/protobuf/blob/master/java/lite.md) +[The Lite version of protobuf for the JVM](https://github.com/protocolbuffers/protobuf/blob/main/java/lite.md) avoids reflection and may be better suited for use with AOT compilation tooling. This Lite version was originally targeted for use on Android which has similar AOT compilation goals as GraalVM's native-image tool.
diff --git a/docs/options.md b/docs/options.md index dbb3563..b489288 100644 --- a/docs/options.md +++ b/docs/options.md
@@ -304,3 +304,19 @@ 1. Embedded Proto * Website: https://EmbeddedProto.com * Extension: 1141 + +1. Protoc-gen-fieldmask + * Website: https://github.com/yeqown/protoc-gen-fieldmask + * Extension: 1142 + +1. Google Gnostic + * Website: https://github.com/google/gnostic + * Extension: 1143 + +1. Protoc-gen-go-micro + * Website: https://github.com/unistack-org/protoc-gen-go-micro + * Extension: 1144 + +1. Protoc-gen-authz + * Website: https://github.com/Neakxs/protoc-gen-authz + * Extension: 1145
diff --git a/docs/performance.md b/docs/performance.md index 8734c70..245fdf1 100644 --- a/docs/performance.md +++ b/docs/performance.md
@@ -301,4 +301,4 @@ </tr> </tbody></table> -\* The cpp performance can be improved by using [tcmalloc](https://gperftools.github.io/gperftools/tcmalloc.html), please follow the (instruction)[https://github.com/protocolbuffers/protobuf/blob/master/benchmarks/README.md] to link with tcmalloc to get the faster result. +\* The cpp performance can be improved by using [tcmalloc](https://gperftools.github.io/gperftools/tcmalloc.html), please follow the (instruction)[https://github.com/protocolbuffers/protobuf/blob/main/benchmarks/README.md] to link with tcmalloc to get the faster result.
diff --git a/docs/third_party.md b/docs/third_party.md index f09cff2..d8478e9 100644 --- a/docs/third_party.md +++ b/docs/third_party.md
@@ -71,6 +71,7 @@ * Kotlin: https://github.com/Kotlin/kotlinx.serialization * Kotlin: https://github.com/ButterCam/sisyphus * Kotlin: https://github.com/open-toast/protokt +* Kotlin Multiplatform: https://github.com/streem/pbandk * Lua: https://code.google.com/p/protoc-gen-lua/ * Lua: http://github.com/indygreg/lua-protobuf * Lua: https://github.com/Neopallium/lua-pb @@ -180,7 +181,7 @@ * [Protobuf for nginx module](https://github.com/dbcode/protobuf-nginx/) * [RSpec matchers and Cucumber step defs for testing Protocol Buffers](https://github.com/connamara/protobuf_spec) * [Sbt plugin for Protocol Buffers](https://github.com/Atry/sbt-cppp) -* [Gradle Protobuf Plugin](https://github.com/aantono/gradle-plugin-protobuf) +* [Protobuf Plugin for Gradle](https://github.com/google/protobuf-gradle-plugin) * [Multi-platform executable JAR and Java API for protoc](https://github.com/os72/protoc-jar) * [Python scripts to convert between Protocol Buffers and JSON](https://github.com/NextTuesday/py-pb-converters) * [Visual Studio Language Service support for Protocol Buffers](http://visualstudiogallery.msdn.microsoft.com/4bc0f38c-b058-4e05-ae38-155e053c19c5)
diff --git a/examples/WORKSPACE b/examples/WORKSPACE index fb36639..3897572 100644 --- a/examples/WORKSPACE +++ b/examples/WORKSPACE
@@ -10,8 +10,8 @@ # # http_archive( # name = "com_google_protobuf", -# strip_prefix = "protobuf-master", -# urls = ["https://github.com/protocolbuffers/protobuf/archive/master.zip"], +# strip_prefix = "protobuf-main", +# urls = ["https://github.com/protocolbuffers/protobuf/archive/main.zip"], # ) local_repository( name = "com_google_protobuf",
diff --git a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java index b36c94f..0a87859 100644 --- a/java/core/src/main/java/com/google/protobuf/AbstractMessage.java +++ b/java/core/src/main/java/com/google/protobuf/AbstractMessage.java
@@ -94,13 +94,13 @@ return MessageReflection.delimitWithCommas(findInitializationErrors()); } - /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ + // TODO(jieluo): Clear it when all subclasses have implemented this method. @Override public boolean hasOneof(OneofDescriptor oneof) { throw new UnsupportedOperationException("hasOneof() is not implemented."); } - /** TODO(jieluo): Clear it when all subclasses have implemented this method. */ + // TODO(jieluo): Clear it when all subclasses have implemented this method. @Override public FieldDescriptor getOneofFieldDescriptor(OneofDescriptor oneof) { throw new UnsupportedOperationException("getOneofFieldDescriptor() is not implemented.");
diff --git a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java index a05c504..4ad8309 100644 --- a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java +++ b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java
@@ -996,8 +996,6 @@ writeLazy(bytes, 0, bytes.length); } catch (IndexOutOfBoundsException e) { throw new OutOfSpaceException(e); - } catch (OutOfSpaceException e) { - throw e; } } @@ -1345,49 +1343,19 @@ @Override public final void writeUInt32NoTag(int value) throws IOException { - if (HAS_UNSAFE_ARRAY_OPERATIONS - && !Android.isOnAndroidDevice() - && spaceLeft() >= MAX_VARINT32_SIZE) { - if ((value & ~0x7F) == 0) { - UnsafeUtil.putByte(buffer, position++, (byte) value); - return; - } - UnsafeUtil.putByte(buffer, position++, (byte) (value | 0x80)); - value >>>= 7; - if ((value & ~0x7F) == 0) { - UnsafeUtil.putByte(buffer, position++, (byte) value); - return; - } - UnsafeUtil.putByte(buffer, position++, (byte) (value | 0x80)); - value >>>= 7; - if ((value & ~0x7F) == 0) { - UnsafeUtil.putByte(buffer, position++, (byte) value); - return; - } - UnsafeUtil.putByte(buffer, position++, (byte) (value | 0x80)); - value >>>= 7; - if ((value & ~0x7F) == 0) { - UnsafeUtil.putByte(buffer, position++, (byte) value); - return; - } - UnsafeUtil.putByte(buffer, position++, (byte) (value | 0x80)); - value >>>= 7; - UnsafeUtil.putByte(buffer, position++, (byte) value); - } else { - try { - while (true) { - if ((value & ~0x7F) == 0) { - buffer[position++] = (byte) value; - return; - } else { - buffer[position++] = (byte) ((value & 0x7F) | 0x80); - value >>>= 7; - } + try { + while (true) { + if ((value & ~0x7F) == 0) { + buffer[position++] = (byte) value; + return; + } else { + buffer[position++] = (byte) ((value & 0x7F) | 0x80); + value >>>= 7; } - } catch (IndexOutOfBoundsException e) { - throw new OutOfSpaceException( - String.format("Pos: %d, limit: %d, len: %d", position, limit, 1), e); } + } catch (IndexOutOfBoundsException e) { + throw new OutOfSpaceException( + String.format("Pos: %d, limit: %d, len: %d", position, limit, 1), e); } }
diff --git a/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java b/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java index 6090985..b856952 100644 --- a/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java +++ b/java/core/src/main/java/com/google/protobuf/DescriptorMessageInfoFactory.java
@@ -150,7 +150,7 @@ * <p>This class is thread-safe. */ // <p>The code is adapted from the C++ implementation: - // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/compiler/java/java_helpers.h + // https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/compiler/java/java_helpers.h static class IsInitializedCheckAnalyzer { private final Map<Descriptor, Boolean> resultCache =
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 99d088a..a36195b 100644 --- a/java/core/src/main/java/com/google/protobuf/Descriptors.java +++ b/java/core/src/main/java/com/google/protobuf/Descriptors.java
@@ -814,7 +814,7 @@ /** * Finds a nested message type by name. * - * @param name The unqualified name of the nested type (e.g. "Foo"). + * @param name The unqualified name of the nested type such as "Foo" * @return The types's descriptor, or {@code null} if not found. */ public Descriptor findNestedTypeByName(final String name) { @@ -829,7 +829,7 @@ /** * Finds a nested enum type by name. * - * @param name The unqualified name of the nested type (e.g. "Foo"). + * @param name The unqualified name of the nested type such as "Foo" * @return The types's descriptor, or {@code null} if not found. */ public EnumDescriptor findEnumTypeByName(final String name) { @@ -1202,7 +1202,7 @@ } } - /** Can this field be packed? i.e. is it a repeated primitive field? */ + /** Can this field be packed? That is, is it a repeated primitive field? */ public boolean isPackable() { return isRepeated() && getLiteType().isPackable(); } @@ -1295,13 +1295,13 @@ * } * message Bar { * extend Foo { - * optional int32 qux = 4321; + * optional int32 moo = 4321; * } * } * </pre> * - * Both {@code baz}'s and {@code qux}'s containing type is {@code Foo}. However, {@code baz}'s - * extension scope is {@code null} while {@code qux}'s extension scope is {@code Bar}. + * Both {@code baz}'s and {@code moo}'s containing type is {@code Foo}. However, {@code baz}'s + * extension scope is {@code null} while {@code moo}'s extension scope is {@code Bar}. */ public Descriptor getExtensionScope() { if (!isExtension()) { @@ -1332,11 +1332,11 @@ /** * Compare with another {@code FieldDescriptor}. This orders fields in "canonical" order, which - * simply means ascending order by field number. {@code other} must be a field of the same type - * -- i.e. {@code getContainingType()} must return the same {@code Descriptor} for both fields. + * simply means ascending order by field number. {@code other} must be a field of the same type. + * That is, {@code getContainingType()} must return the same {@code Descriptor} for both fields. * * @return negative, zero, or positive if {@code this} is less than, equal to, or greater than - * {@code other}, respectively. + * {@code other}, respectively */ @Override public int compareTo(final FieldDescriptor other) { @@ -1791,8 +1791,8 @@ /** * Find an enum value by name. * - * @param name The unqualified name of the value (e.g. "FOO"). - * @return the value's descriptor, or {@code null} if not found. + * @param name the unqualified name of the value such as "FOO" + * @return the value's descriptor, or {@code null} if not found */ public EnumValueDescriptor findValueByName(final String name) { final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); @@ -2102,8 +2102,8 @@ /** * Find a method by name. * - * @param name The unqualified name of the method (e.g. "Foo"). - * @return the method's descriptor, or {@code null} if not found. + * @param name the unqualified name of the method such as "Foo" + * @return the method's descriptor, or {@code null} if not found */ public MethodDescriptor findMethodByName(final String name) { final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name); @@ -2676,8 +2676,8 @@ } /** - * Verifies that the descriptor's name is valid (i.e. it contains only letters, digits, and - * underscores, and does not start with a digit). + * Verifies that the descriptor's name is valid. That is, it contains only letters, digits, and + * underscores, and does not start with a digit. */ static void validateSymbolName(final GenericDescriptor descriptor) throws DescriptorValidationException { @@ -2705,7 +2705,7 @@ } } - /** Describes an oneof of a message type. */ + /** Describes a oneof of a message type. */ public static final class OneofDescriptor extends GenericDescriptor { /** Get the index of this descriptor within its parent. */ public int getIndex() {
diff --git a/java/core/src/main/java/com/google/protobuf/MapEntry.java b/java/core/src/main/java/com/google/protobuf/MapEntry.java index d528e1a..8890f22 100644 --- a/java/core/src/main/java/com/google/protobuf/MapEntry.java +++ b/java/core/src/main/java/com/google/protobuf/MapEntry.java
@@ -336,13 +336,17 @@ @Override public Builder<K, V> setField(FieldDescriptor field, Object value) { checkFieldDescriptor(field); + if (value == null) { + throw new NullPointerException(field.getFullName() + " is null"); + } + if (field.getNumber() == 1) { setKey((K) value); } else { if (field.getType() == FieldDescriptor.Type.ENUM) { value = ((EnumValueDescriptor) value).getNumber(); } else if (field.getType() == FieldDescriptor.Type.MESSAGE) { - if (value != null && !metadata.defaultValue.getClass().isInstance(value)) { + if (!metadata.defaultValue.getClass().isInstance(value)) { // The value is not the exact right message type. However, if it // is an alternative implementation of the same type -- e.g. a // DynamicMessage -- we should accept it. In this case we can make
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 b32a8b5..7317f49 100644 --- a/java/core/src/main/java/com/google/protobuf/TextFormat.java +++ b/java/core/src/main/java/com/google/protobuf/TextFormat.java
@@ -471,7 +471,7 @@ private final FieldDescriptor.JavaType fieldType; - public MapEntryAdapter(Object entry, FieldDescriptor fieldDescriptor) { + MapEntryAdapter(Object entry, FieldDescriptor fieldDescriptor) { if (entry instanceof MapEntry) { this.mapEntry = (MapEntry) entry; } else { @@ -484,14 +484,14 @@ return fieldDescriptor.getMessageType().getFields().get(0).getJavaType(); } - public Object getKey() { + Object getKey() { if (mapEntry != null) { return mapEntry.getKey(); } return null; } - public Object getEntry() { + Object getEntry() { if (mapEntry != null) { return mapEntry; } @@ -988,12 +988,12 @@ } /** Are we at the end of the input? */ - public boolean atEnd() { + boolean atEnd() { return currentToken.length() == 0; } /** Advance to the next token. */ - public void nextToken() { + void nextToken() { previousLine = line; previousColumn = column; @@ -1039,7 +1039,7 @@ * If the next token exactly matches {@code token}, consume it and return {@code true}. * Otherwise, return {@code false} without doing anything. */ - public boolean tryConsume(final String token) { + boolean tryConsume(final String token) { if (currentToken.equals(token)) { nextToken(); return true; @@ -1052,14 +1052,14 @@ * If the next token exactly matches {@code token}, consume it. Otherwise, throw a {@link * ParseException}. */ - public void consume(final String token) throws ParseException { + void consume(final String token) throws ParseException { if (!tryConsume(token)) { throw parseException("Expected \"" + token + "\"."); } } /** Returns {@code true} if the next token is an integer, but does not consume it. */ - public boolean lookingAtInteger() { + boolean lookingAtInteger() { if (currentToken.length() == 0) { return false; } @@ -1069,7 +1069,7 @@ } /** Returns {@code true} if the current token's text is equal to that specified. */ - public boolean lookingAt(String text) { + boolean lookingAt(String text) { return currentToken.equals(text); } @@ -1077,7 +1077,7 @@ * If the next token is an identifier, consume it and return its value. Otherwise, throw a * {@link ParseException}. */ - public String consumeIdentifier() throws ParseException { + String consumeIdentifier() throws ParseException { for (int i = 0; i < currentToken.length(); i++) { final char c = currentToken.charAt(i); if (('a' <= c && c <= 'z') @@ -1100,7 +1100,7 @@ * If the next token is an identifier, consume it and return {@code true}. Otherwise, return * {@code false} without doing anything. */ - public boolean tryConsumeIdentifier() { + boolean tryConsumeIdentifier() { try { consumeIdentifier(); return true; @@ -1113,7 +1113,7 @@ * If the next token is a 32-bit signed integer, consume it and return its value. Otherwise, * throw a {@link ParseException}. */ - public int consumeInt32() throws ParseException { + int consumeInt32() throws ParseException { try { final int result = parseInt32(currentToken); nextToken(); @@ -1127,7 +1127,7 @@ * If the next token is a 32-bit unsigned integer, consume it and return its value. Otherwise, * throw a {@link ParseException}. */ - public int consumeUInt32() throws ParseException { + int consumeUInt32() throws ParseException { try { final int result = parseUInt32(currentToken); nextToken(); @@ -1141,7 +1141,7 @@ * If the next token is a 64-bit signed integer, consume it and return its value. Otherwise, * throw a {@link ParseException}. */ - public long consumeInt64() throws ParseException { + long consumeInt64() throws ParseException { try { final long result = parseInt64(currentToken); nextToken(); @@ -1155,7 +1155,7 @@ * If the next token is a 64-bit signed integer, consume it and return {@code true}. Otherwise, * return {@code false} without doing anything. */ - public boolean tryConsumeInt64() { + boolean tryConsumeInt64() { try { consumeInt64(); return true; @@ -1168,7 +1168,7 @@ * If the next token is a 64-bit unsigned integer, consume it and return its value. Otherwise, * throw a {@link ParseException}. */ - public long consumeUInt64() throws ParseException { + long consumeUInt64() throws ParseException { try { final long result = parseUInt64(currentToken); nextToken(); @@ -1298,7 +1298,7 @@ } /** If the next token is a string, consume it and return true. Otherwise, return false. */ - public boolean tryConsumeString() { + boolean tryConsumeString() { try { consumeString(); return true; @@ -1311,7 +1311,7 @@ * If the next token is a string, consume it, unescape it as a {@link ByteString}, and return * it. Otherwise, throw a {@link ParseException}. */ - public ByteString consumeByteString() throws ParseException { + ByteString consumeByteString() throws ParseException { List<ByteString> list = new ArrayList<ByteString>(); consumeByteString(list); while (currentToken.startsWith("'") || currentToken.startsWith("\"")) { @@ -1349,7 +1349,7 @@ * Returns a {@link ParseException} with the current line and column numbers in the description, * suitable for throwing. */ - public ParseException parseException(final String description) { + ParseException parseException(final String description) { // Note: People generally prefer one-based line and column numbers. return new ParseException(line + 1, column + 1, description); } @@ -1358,7 +1358,7 @@ * Returns a {@link ParseException} with the line and column numbers of the previous token in * the description, suitable for throwing. */ - public ParseException parseExceptionPreviousToken(final String description) { + ParseException parseExceptionPreviousToken(final String description) { // Note: People generally prefer one-based line and column numbers. return new ParseException(previousLine + 1, previousColumn + 1, description); } @@ -1379,16 +1379,6 @@ return parseException("Couldn't parse number: " + e.getMessage()); } - /** - * Returns a {@link UnknownFieldParseException} with the line and column numbers of the previous - * token in the description, and the unknown field name, suitable for throwing. - */ - public UnknownFieldParseException unknownFieldParseExceptionPreviousToken( - final String unknownField, final String description) { - // Note: People generally prefer one-based line and column numbers. - return new UnknownFieldParseException( - previousLine + 1, previousColumn + 1, unknownField, description); - } } /** Thrown when parsing an invalid text format message. */ @@ -1552,7 +1542,6 @@ * control the parser behavior. */ public static class Parser { - private int debugStringSilentMarker; /** * A valid silent marker appears between a field name and its value. If there is a ":" in @@ -1567,13 +1556,13 @@ /** * Determines if repeated values for non-repeated fields and oneofs are permitted. For example, - * given required/optional field "foo" and a oneof containing "baz" and "qux": + * given required/optional field "foo" and a oneof containing "baz" and "moo": * * <ul> * <li>"foo: 1 foo: 2" - * <li>"baz: 1 qux: 2" + * <li>"baz: 1 moo: 2" * <li>merging "foo: 2" into a proto in which foo is already set, or - * <li>merging "qux: 2" into a proto in which baz is already set. + * <li>merging "moo: 2" into a proto in which baz is already set. * </ul> */ public enum SingularOverwritePolicy { @@ -1803,7 +1792,6 @@ while (!tokenizer.atEnd()) { mergeField(tokenizer, extensionRegistry, target, unknownFields); } - checkUnknownFields(unknownFields); }
diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java index 5c482d6..45b5a6b 100644 --- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java
@@ -62,7 +62,7 @@ /** * Construct an {@code UnknownFieldSet} around the given map. */ - UnknownFieldSet(TreeMap<Integer, Field> fields) { + private UnknownFieldSet(TreeMap<Integer, Field> fields) { this.fields = fields; }
diff --git a/java/core/src/main/java/com/google/protobuf/Utf8.java b/java/core/src/main/java/com/google/protobuf/Utf8.java index 3130a31..c74497c 100644 --- a/java/core/src/main/java/com/google/protobuf/Utf8.java +++ b/java/core/src/main/java/com/google/protobuf/Utf8.java
@@ -42,6 +42,7 @@ import static java.lang.Character.toCodePoint; import java.nio.ByteBuffer; +import java.util.Arrays; /** * A set of low-level, high-performance static utility methods related to the UTF-8 character @@ -1366,87 +1367,25 @@ @Override String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { - if ((index | size | bytes.length - index - size) < 0) { - throw new ArrayIndexOutOfBoundsException( - String.format("buffer length=%d, index=%d, size=%d", bytes.length, index, size)); + String s = new String(bytes, index, size, Internal.UTF_8); + + // "\uFFFD" is UTF-8 default replacement string, which illegal byte sequences get replaced + // with. + if (!s.contains("\uFFFD")) { + return s; } - int offset = index + unsafeEstimateConsecutiveAscii(bytes, index, size); - final int limit = index + size; - - // get an "exact" consecutive ASCII - while (offset < limit) { - byte b = UnsafeUtil.getByte(bytes, offset); - if (b < 0) { - break; - } - offset++; + // Since s contains "\uFFFD" there are 2 options: + // 1) The byte array slice is invalid UTF-8. + // 2) The byte array slice is valid UTF-8 and contains encodings for "\uFFFD". + // To rule out (1), we encode s and compare it to the byte array slice. + // If the byte array slice was invalid UTF-8, then we would get a different sequence of bytes. + if (Arrays.equals( + s.getBytes(Internal.UTF_8), Arrays.copyOfRange(bytes, index, index + size))) { + return s; } - if (offset == limit) { - // The entire byte sequence is ASCII. Don't bother copying to a char[], JVMs using - // compact strings will just turn it back into the same byte[]. - return new String(bytes, index, size, Internal.US_ASCII); - } - - // It's not all ASCII, at this point. This may over-allocate, but we will truncate in the - // end. - char[] resultArr = new char[size]; - int resultPos = 0; - - // Copy over the initial run of ASCII. - for (int i = index; i < offset; i++) { - DecodeUtil.handleOneByte(UnsafeUtil.getByte(bytes, i), resultArr, resultPos++); - } - - while (offset < limit) { - byte byte1 = UnsafeUtil.getByte(bytes, offset++); - if (DecodeUtil.isOneByte(byte1)) { - DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); - - // It's common for there to be multiple ASCII characters in a run mixed in, so add an - // extra optimized loop to take care of these runs. - while (offset < limit) { - byte b = UnsafeUtil.getByte(bytes, offset); - if (!DecodeUtil.isOneByte(b)) { - break; - } - offset++; - DecodeUtil.handleOneByte(b, resultArr, resultPos++); - } - } else if (DecodeUtil.isTwoBytes(byte1)) { - if (offset >= limit) { - throw InvalidProtocolBufferException.invalidUtf8(); - } - DecodeUtil.handleTwoBytes( - byte1, /* byte2 */ UnsafeUtil.getByte(bytes, offset++), resultArr, resultPos++); - } else if (DecodeUtil.isThreeBytes(byte1)) { - if (offset >= limit - 1) { - throw InvalidProtocolBufferException.invalidUtf8(); - } - DecodeUtil.handleThreeBytes( - byte1, - /* byte2 */ UnsafeUtil.getByte(bytes, offset++), - /* byte3 */ UnsafeUtil.getByte(bytes, offset++), - resultArr, - resultPos++); - } else { - if (offset >= limit - 2) { - throw InvalidProtocolBufferException.invalidUtf8(); - } - DecodeUtil.handleFourBytes( - byte1, - /* byte2 */ UnsafeUtil.getByte(bytes, offset++), - /* byte3 */ UnsafeUtil.getByte(bytes, offset++), - /* byte4 */ UnsafeUtil.getByte(bytes, offset++), - resultArr, - resultPos++); - // 4-byte case requires two chars. - resultPos++; - } - } - - return new String(resultArr, 0, resultPos); + throw InvalidProtocolBufferException.invalidUtf8(); } @Override @@ -1666,8 +1605,20 @@ return 0; } + // Read bytes until 8-byte aligned so that we can read longs in the loop below. + // Byte arrays are already either 8 or 16-byte aligned, so we just need to make sure that + // the index (relative to the start of the array) is also 8-byte aligned. We do this by + // ANDing the index with 7 to determine the number of bytes that need to be read before + // we're 8-byte aligned. + final int unaligned = 8 - ((int) offset & 7); int i; - for (i = 0; i + 8 <= maxChars; i += 8) { + for (i = 0; i < unaligned; i++) { + if (UnsafeUtil.getByte(bytes, offset++) < 0) { + return i; + } + } + + for (; i + 8 <= maxChars; i += 8) { if ((UnsafeUtil.getLong(bytes, UnsafeUtil.BYTE_ARRAY_BASE_OFFSET + offset) & ASCII_MASK_LONG) != 0L) {
diff --git a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java index 800623a..6518372 100644 --- a/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java +++ b/java/core/src/test/java/com/google/protobuf/CheckUtf8Test.java
@@ -64,8 +64,7 @@ public void testParseRequiredStringWithGoodUtf8() throws Exception { ByteString serialized = BytesWrapper.newBuilder().setReq(UTF8_BYTE_STRING).build().toByteString(); - assertThat(StringWrapper.parser().parseFrom(serialized).getReq()) - .isEqualTo(UTF8_BYTE_STRING_TEXT); + assertThat(StringWrapper.parseFrom(serialized).getReq()).isEqualTo(UTF8_BYTE_STRING_TEXT); } @Test
diff --git a/java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java b/java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java index 5a345aa..4cffd4c 100644 --- a/java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java +++ b/java/core/src/test/java/com/google/protobuf/DecodeUtf8Test.java
@@ -253,13 +253,13 @@ try { UNSAFE_PROCESSOR.decodeUtf8(bytes, index, size); fail(); - } catch (ArrayIndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { // Expected. } try { SAFE_PROCESSOR.decodeUtf8(bytes, index, size); fail(); - } catch (ArrayIndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { // Expected. } @@ -269,13 +269,13 @@ try { UNSAFE_PROCESSOR.decodeUtf8(direct, index, size); fail(); - } catch (ArrayIndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { // Expected. } try { SAFE_PROCESSOR.decodeUtf8(direct, index, size); fail(); - } catch (ArrayIndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { // Expected. } @@ -285,13 +285,13 @@ try { UNSAFE_PROCESSOR.decodeUtf8(heap, index, size); fail(); - } catch (ArrayIndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { // Expected. } try { SAFE_PROCESSOR.decodeUtf8(heap, index, size); fail(); - } catch (ArrayIndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { // Expected. } }
diff --git a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java index eb5b739..55864af 100644 --- a/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/GeneratedMessageTest.java
@@ -359,7 +359,7 @@ @Test public void testParsedMessagesAreImmutable() throws Exception { - TestAllTypes value = TestAllTypes.parser().parseFrom(TestUtil.getAllSet().toByteString()); + TestAllTypes value = TestAllTypes.parseFrom(TestUtil.getAllSet().toByteString()); assertIsUnmodifiable(value.getRepeatedInt32List()); assertIsUnmodifiable(value.getRepeatedInt64List()); assertIsUnmodifiable(value.getRepeatedUint32List()); @@ -1498,7 +1498,7 @@ assertThat(message.hasFooStringPiece()).isTrue(); TestUtil.assertAtMostOneFieldSetOneof(message); - message = builder.setFooBytes(TestUtil.toBytes("qux")).buildPartial(); + message = builder.setFooBytes(TestUtil.toBytes("moo")).buildPartial(); assertThat(message.hasFooBytes()).isTrue(); TestUtil.assertAtMostOneFieldSetOneof(message); @@ -1508,7 +1508,7 @@ message = builder - .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()) + .setFooMessage(TestOneof2.NestedMessage.newBuilder().setMooInt(234).build()) .buildPartial(); assertThat(message.hasFooMessage()).isTrue(); TestUtil.assertAtMostOneFieldSetOneof(message); @@ -1625,31 +1625,31 @@ { // set TestOneof2.Builder builder = TestOneof2.newBuilder(); - assertThat(builder.getFooMessage().getQuxInt()).isEqualTo(0); - builder.setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()); + assertThat(builder.getFooMessage().getMooInt()).isEqualTo(0); + builder.setFooMessage(TestOneof2.NestedMessage.newBuilder().setMooInt(234).build()); assertThat(builder.hasFooMessage()).isTrue(); - assertThat(builder.getFooMessage().getQuxInt()).isEqualTo(234); + assertThat(builder.getFooMessage().getMooInt()).isEqualTo(234); TestOneof2 message = builder.buildPartial(); assertThat(message.hasFooMessage()).isTrue(); - assertThat(message.getFooMessage().getQuxInt()).isEqualTo(234); + assertThat(message.getFooMessage().getMooInt()).isEqualTo(234); // clear assertThat(builder.clearFooMessage().hasFooString()).isFalse(); message = builder.build(); assertThat(message.hasFooMessage()).isFalse(); - assertThat(message.getFooMessage().getQuxInt()).isEqualTo(0); + assertThat(message.getFooMessage().getMooInt()).isEqualTo(0); // nested builder builder = TestOneof2.newBuilder(); assertThat(builder.getFooMessageOrBuilder()) .isSameInstanceAs(TestOneof2.NestedMessage.getDefaultInstance()); assertThat(builder.hasFooMessage()).isFalse(); - builder.getFooMessageBuilder().setQuxInt(123); + builder.getFooMessageBuilder().setMooInt(123); assertThat(builder.hasFooMessage()).isTrue(); - assertThat(builder.getFooMessage().getQuxInt()).isEqualTo(123); + assertThat(builder.getFooMessage().getMooInt()).isEqualTo(123); message = builder.build(); assertThat(message.hasFooMessage()).isTrue(); - assertThat(message.getFooMessage().getQuxInt()).isEqualTo(123); + assertThat(message.getFooMessage().getMooInt()).isEqualTo(123); } // LazyMessage is tested in LazyMessageLiteTest.java @@ -1689,10 +1689,10 @@ public void testOneofMergeMessage_mergeIntoNewBuilder() { TestOneof2.Builder builder = TestOneof2.newBuilder(); TestOneof2 message = - builder.setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()).build(); + builder.setFooMessage(TestOneof2.NestedMessage.newBuilder().setMooInt(234).build()).build(); TestOneof2 message2 = TestOneof2.newBuilder().mergeFrom(message).build(); assertThat(message2.hasFooMessage()).isTrue(); - assertThat(message2.getFooMessage().getQuxInt()).isEqualTo(234); + assertThat(message2.getFooMessage().getMooInt()).isEqualTo(234); } @Test @@ -1755,12 +1755,12 @@ TestOneof2.Builder builder = TestOneof2.newBuilder(); TestOneof2 message = builder - .setFooMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(234).build()) + .setFooMessage(TestOneof2.NestedMessage.newBuilder().setMooInt(234).build()) .build(); ByteString serialized = message.toByteString(); TestOneof2 message2 = TestOneof2.parseFrom(serialized); assertThat(message2.hasFooMessage()).isTrue(); - assertThat(message2.getFooMessage().getQuxInt()).isEqualTo(234); + assertThat(message2.getFooMessage().getMooInt()).isEqualTo(234); } }
diff --git a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java index 006ba38..2ff60da 100644 --- a/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java +++ b/java/core/src/test/java/com/google/protobuf/LazyStringEndToEndTest.java
@@ -76,7 +76,7 @@ ByteString bytes = tV2.toByteString(); assertThat(bytes).isEqualTo(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8); - tV2.getOptionalString(); + String unused = tV2.getOptionalString(); bytes = tV2.toByteString(); assertThat(bytes).isEqualTo(TEST_ALL_TYPES_SERIALIZED_WITH_ILLEGAL_UTF8); }
diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java index 1a767c0..e8b1503 100644 --- a/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapForProto2LiteTest.java
@@ -392,21 +392,21 @@ setMapValues(builder); TestMap message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesSet(message); builder = message.toBuilder(); updateMapValues(builder); message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesUpdated(message); builder = message.toBuilder(); builder.clear(); message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesCleared(message); } @@ -415,7 +415,7 @@ CodedOutputStream output = CodedOutputStream.newInstance(byteArrayOutputStream); bizarroMap.writeTo(output); output.flush(); - return TestMap.parser().parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); + return TestMap.parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); } @Test
diff --git a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java index 6681724..2f74f96 100644 --- a/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java +++ b/java/core/src/test/java/com/google/protobuf/MapForProto2Test.java
@@ -534,21 +534,21 @@ setMapValuesUsingAccessors(builder); TestMap message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesSet(message); builder = message.toBuilder(); updateMapValuesUsingAccessors(builder); message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesUpdated(message); builder = message.toBuilder(); builder.clear(); message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesCleared(message); } @@ -557,7 +557,7 @@ CodedOutputStream output = CodedOutputStream.newInstance(byteArrayOutputStream); bizarroMap.writeTo(output); output.flush(); - return TestMap.parser().parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); + return TestMap.parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); } @Test
diff --git a/java/core/src/test/java/com/google/protobuf/MapLiteTest.java b/java/core/src/test/java/com/google/protobuf/MapLiteTest.java index 349d576..d763f9d 100644 --- a/java/core/src/test/java/com/google/protobuf/MapLiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapLiteTest.java
@@ -425,21 +425,21 @@ setMapValues(builder); TestMap message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesSet(message); builder = message.toBuilder(); updateMapValues(builder); message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesUpdated(message); builder = message.toBuilder(); builder.clear(); message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesCleared(message); } @@ -448,7 +448,7 @@ CodedOutputStream output = CodedOutputStream.newInstance(byteArrayOutputStream); bizarroMap.writeTo(output); output.flush(); - return TestMap.parser().parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); + return TestMap.parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); } @Test
diff --git a/java/core/src/test/java/com/google/protobuf/MapTest.java b/java/core/src/test/java/com/google/protobuf/MapTest.java index 587ebbb..1bb7166 100644 --- a/java/core/src/test/java/com/google/protobuf/MapTest.java +++ b/java/core/src/test/java/com/google/protobuf/MapTest.java
@@ -40,6 +40,7 @@ import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import map_test.MapTestProto.BizarroTestMap; +import map_test.MapTestProto.MapContainer; import map_test.MapTestProto.ReservedAsMapField; import map_test.MapTestProto.ReservedAsMapFieldWithEnumValue; import map_test.MapTestProto.TestMap; @@ -580,21 +581,21 @@ setMapValuesUsingAccessors(builder); TestMap message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesSet(message); builder = message.toBuilder(); updateMapValuesUsingAccessors(builder); message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesUpdated(message); builder = message.toBuilder(); builder.clear(); message = builder.build(); assertThat(message.toByteString().size()).isEqualTo(message.getSerializedSize()); - message = TestMap.parser().parseFrom(message.toByteString()); + message = TestMap.parseFrom(message.toByteString()); assertMapValuesCleared(message); } @@ -603,7 +604,7 @@ CodedOutputStream output = CodedOutputStream.newInstance(byteArrayOutputStream); bizarroMap.writeTo(output); output.flush(); - return TestMap.parser().parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); + return TestMap.parseFrom(ByteString.copyFrom(byteArrayOutputStream.toByteArray())); } @Test @@ -1586,4 +1587,19 @@ assertThat(builder.build().toByteArray()).isEqualTo(new byte[0]); } + + @Test + // https://github.com/protocolbuffers/protobuf/issues/9785 + public void testContainer() { + FieldDescriptor field = MapContainer.getDescriptor().findFieldByName("my_map"); + Descriptor entryDescriptor = field.getMessageType(); + FieldDescriptor valueDescriptor = entryDescriptor.findFieldByName("value"); + Message.Builder builder = MapContainer.newBuilder().newBuilderForField(field); + try { + builder.setField(valueDescriptor, null); + fail("Allowed null field value"); + } catch (NullPointerException expected) { + assertThat(expected).hasMessageThat().isNotNull(); + } + } }
diff --git a/java/core/src/test/java/com/google/protobuf/MessageTest.java b/java/core/src/test/java/com/google/protobuf/MessageTest.java index fa36433..86e077e 100644 --- a/java/core/src/test/java/com/google/protobuf/MessageTest.java +++ b/java/core/src/test/java/com/google/protobuf/MessageTest.java
@@ -337,7 +337,7 @@ /** Test reading unset repeated message from DynamicMessage. */ @Test public void testDynamicRepeatedMessageNull() throws Exception { - TestRequired.getDescriptor(); + Descriptors.Descriptor unused = TestRequired.getDescriptor(); DynamicMessage result = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()) .mergeFrom(DynamicMessage.newBuilder(MERGE_SOURCE).build()) @@ -365,7 +365,7 @@ .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance()) .addRepeatedForeignMessage(ForeignMessage.getDefaultInstance()) .build(); - TestRequired.getDescriptor(); + Descriptors.Descriptor unused = TestRequired.getDescriptor(); DynamicMessage result = DynamicMessage.newBuilder(TestAllTypes.getDescriptor()) .mergeFrom(DynamicMessage.newBuilder(repeatedNested).build())
diff --git a/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java b/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java index 6f6d26b..dc31b38 100644 --- a/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java +++ b/java/core/src/test/java/com/google/protobuf/ParserLiteTest.java
@@ -192,7 +192,7 @@ // Parse TestParsingMergeLite. ExtensionRegistryLite registry = ExtensionRegistryLite.newInstance(); UnittestLite.registerAllExtensions(registry); - TestParsingMergeLite parsingMerge = TestParsingMergeLite.parser().parseFrom(data, registry); + TestParsingMergeLite parsingMerge = TestParsingMergeLite.parseFrom(data, registry); // Required and optional fields should be merged. assertMessageMerged(parsingMerge.getRequiredAllTypes());
diff --git a/java/core/src/test/java/com/google/protobuf/ParserTest.java b/java/core/src/test/java/com/google/protobuf/ParserTest.java index f4cf529..69c5795 100644 --- a/java/core/src/test/java/com/google/protobuf/ParserTest.java +++ b/java/core/src/test/java/com/google/protobuf/ParserTest.java
@@ -195,8 +195,7 @@ @Test public void testParseUnknownFields() throws Exception { // All fields will be treated as unknown fields in emptyMessage. - TestEmptyMessage emptyMessage = - TestEmptyMessage.parser().parseFrom(TestUtil.getAllSet().toByteString()); + TestEmptyMessage emptyMessage = TestEmptyMessage.parseFrom(TestUtil.getAllSet().toByteString()); assertThat(emptyMessage.toByteString()).isEqualTo(TestUtil.getAllSet().toByteString()); } @@ -278,7 +277,7 @@ // Parse TestParsingMerge. ExtensionRegistry registry = ExtensionRegistry.newInstance(); UnittestProto.registerAllExtensions(registry); - TestParsingMerge parsingMerge = TestParsingMerge.parser().parseFrom(data, registry); + TestParsingMerge parsingMerge = TestParsingMerge.parseFrom(data, registry); // Required and optional fields should be merged. assertMessageMerged(parsingMerge.getRequiredAllTypes());
diff --git a/java/core/src/test/java/com/google/protobuf/ServiceTest.java b/java/core/src/test/java/com/google/protobuf/ServiceTest.java index eccdf1c..cdb5deb 100644 --- a/java/core/src/test/java/com/google/protobuf/ServiceTest.java +++ b/java/core/src/test/java/com/google/protobuf/ServiceTest.java
@@ -251,7 +251,4 @@ assertThat(file.getServices().get(0).getMethods()).hasSize(1); assertThat(file.getServices().get(0).getMethods().get(0).getName()).isEqualTo("Foo"); } - - - // ================================================================= }
diff --git a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java index 08a23ba..38d2471 100644 --- a/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java +++ b/java/core/src/test/java/com/google/protobuf/TestBadIdentifiers.java
@@ -49,6 +49,7 @@ TestBadIdentifiersProto.Override.getDefaultInstance(); } + @SuppressWarnings("IgnoredPureGetter") // TODO(b/221602772): Fix this public void testGetDescriptor() { TestBadIdentifiersProto.getDescriptor(); TestBadIdentifiersProto.Descriptor.getDefaultInstance().getDescriptor();
diff --git a/java/core/src/test/java/com/google/protobuf/TestUtil.java b/java/core/src/test/java/com/google/protobuf/TestUtil.java index 377f34c..46a4d17 100644 --- a/java/core/src/test/java/com/google/protobuf/TestUtil.java +++ b/java/core/src/test/java/com/google/protobuf/TestUtil.java
@@ -80,6 +80,7 @@ import static com.google.protobuf.UnittestLite.optionalStringPieceExtensionLite; import static com.google.protobuf.UnittestLite.optionalUint32ExtensionLite; import static com.google.protobuf.UnittestLite.optionalUint64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalUnverifiedLazyMessageExtensionLite; import static com.google.protobuf.UnittestLite.packedBoolExtensionLite; import static com.google.protobuf.UnittestLite.packedDoubleExtensionLite; import static com.google.protobuf.UnittestLite.packedEnumExtensionLite; @@ -169,6 +170,7 @@ import static protobuf_unittest.UnittestProto.optionalStringPieceExtension; import static protobuf_unittest.UnittestProto.optionalUint32Extension; import static protobuf_unittest.UnittestProto.optionalUint64Extension; +import static protobuf_unittest.UnittestProto.optionalUnverifiedLazyMessageExtension; import static protobuf_unittest.UnittestProto.packedBoolExtension; import static protobuf_unittest.UnittestProto.packedDoubleExtension; import static protobuf_unittest.UnittestProto.packedEnumExtension; @@ -343,6 +345,8 @@ message.setOptionalImportMessage(ImportMessage.newBuilder().setD(120).build()); message.setOptionalPublicImportMessage(PublicImportMessage.newBuilder().setE(126).build()); message.setOptionalLazyMessage(TestAllTypes.NestedMessage.newBuilder().setBb(127).build()); + message.setOptionalUnverifiedLazyMessage( + TestAllTypes.NestedMessage.newBuilder().setBb(128).build()); message.setOptionalNestedEnum(TestAllTypes.NestedEnum.BAZ); message.setOptionalForeignEnum(ForeignEnum.FOREIGN_BAZ); @@ -1240,6 +1244,9 @@ optionalPublicImportMessageExtension, PublicImportMessage.newBuilder().setE(126).build()); message.setExtension( optionalLazyMessageExtension, TestAllTypes.NestedMessage.newBuilder().setBb(127).build()); + message.setExtension( + optionalUnverifiedLazyMessageExtension, + TestAllTypes.NestedMessage.newBuilder().setBb(128).build()); message.setExtension(optionalNestedEnumExtension, TestAllTypes.NestedEnum.BAZ); message.setExtension(optionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ); @@ -1459,6 +1466,8 @@ assertEqualsExactType(120, message.getExtension(optionalImportMessageExtension).getD()); assertEqualsExactType(126, message.getExtension(optionalPublicImportMessageExtension).getE()); assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtension).getBb()); + assertEqualsExactType( + 128, message.getExtension(optionalUnverifiedLazyMessageExtension).getBb()); assertEqualsExactType( TestAllTypes.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtension)); @@ -2051,6 +2060,8 @@ assertEqualsExactType( 126, message.getExtension(optionalPublicImportMessageExtensionLite).getE()); assertEqualsExactType(127, message.getExtension(optionalLazyMessageExtensionLite).getBb()); + assertEqualsExactType( + 128, message.getExtension(optionalUnverifiedLazyMessageExtensionLite).getBb()); assertEqualsExactType( TestAllTypesLite.NestedEnum.BAZ, message.getExtension(optionalNestedEnumExtensionLite)); @@ -2244,6 +2255,7 @@ Assert.assertFalse(message.hasExtension(optionalImportMessageExtensionLite)); Assert.assertFalse(message.hasExtension(optionalPublicImportMessageExtensionLite)); Assert.assertFalse(message.hasExtension(optionalLazyMessageExtensionLite)); + Assert.assertFalse(message.hasExtension(optionalUnverifiedLazyMessageExtensionLite)); Assert.assertFalse(message.hasExtension(optionalNestedEnumExtensionLite)); Assert.assertFalse(message.hasExtension(optionalForeignEnumExtensionLite)); @@ -2276,6 +2288,7 @@ Assert.assertFalse(message.getExtension(optionalImportMessageExtensionLite).hasD()); Assert.assertFalse(message.getExtension(optionalPublicImportMessageExtensionLite).hasE()); Assert.assertFalse(message.getExtension(optionalLazyMessageExtensionLite).hasBb()); + Assert.assertFalse(message.getExtension(optionalUnverifiedLazyMessageExtensionLite).hasBb()); assertEqualsExactType(0, message.getExtension(optionalGroupExtensionLite).getA()); assertEqualsExactType(0, message.getExtension(optionalNestedMessageExtensionLite).getBb()); @@ -2283,6 +2296,8 @@ assertEqualsExactType(0, message.getExtension(optionalImportMessageExtensionLite).getD()); assertEqualsExactType(0, message.getExtension(optionalPublicImportMessageExtensionLite).getE()); assertEqualsExactType(0, message.getExtension(optionalLazyMessageExtensionLite).getBb()); + assertEqualsExactType( + 0, message.getExtension(optionalUnverifiedLazyMessageExtensionLite).getBb()); // Enums without defaults are set to the first value in the enum. assertEqualsExactType( @@ -2537,7 +2552,7 @@ // =================================================================== // oneof public static void setOneof(TestOneof2.Builder message) { - message.setFooLazyMessage(TestOneof2.NestedMessage.newBuilder().setQuxInt(100).build()); + message.setFooLazyMessage(TestOneof2.NestedMessage.newBuilder().setMooInt(100).build()); message.setBarString("101"); message.setBazInt(102); message.setBazString("103"); @@ -2545,13 +2560,13 @@ public static void assertOneofSet(TestOneof2 message) { Assert.assertTrue(message.hasFooLazyMessage()); - Assert.assertTrue(message.getFooLazyMessage().hasQuxInt()); + Assert.assertTrue(message.getFooLazyMessage().hasMooInt()); Assert.assertTrue(message.hasBarString()); Assert.assertTrue(message.hasBazInt()); Assert.assertTrue(message.hasBazString()); - Assert.assertEquals(100, message.getFooLazyMessage().getQuxInt()); + Assert.assertEquals(100, message.getFooLazyMessage().getMooInt()); Assert.assertEquals("101", message.getBarString()); Assert.assertEquals(102, message.getBazInt()); Assert.assertEquals("103", message.getBazString()); @@ -2850,6 +2865,11 @@ message.setField( f("optional_lazy_message"), newBuilderForField(message, f("optional_lazy_message")).setField(nestedB, 127).build()); + message.setField( + f("optional_unverified_lazy_message"), + newBuilderForField(message, f("optional_unverified_lazy_message")) + .setField(nestedB, 128) + .build()); message.setField(f("optional_nested_enum"), nestedBaz); message.setField(f("optional_foreign_enum"), foreignBaz); @@ -3100,6 +3120,9 @@ 126, ((Message) message.getField(f("optional_public_import_message"))).getField(importE)); Assert.assertEquals( 127, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB)); + Assert.assertEquals( + 128, + ((Message) message.getField(f("optional_unverified_lazy_message"))).getField(nestedB)); Assert.assertEquals(nestedBaz, message.getField(f("optional_nested_enum"))); Assert.assertEquals(foreignBaz, message.getField(f("optional_foreign_enum"))); @@ -3351,6 +3374,8 @@ ((Message) message.getField(f("optional_public_import_message"))).hasField(importE)); Assert.assertFalse( ((Message) message.getField(f("optional_lazy_message"))).hasField(nestedB)); + Assert.assertFalse( + ((Message) message.getField(f("optional_unverified_lazy_message"))).hasField(nestedB)); Assert.assertEquals(0, ((Message) message.getField(f("optionalgroup"))).getField(groupA)); Assert.assertEquals( @@ -3363,6 +3388,8 @@ 0, ((Message) message.getField(f("optional_public_import_message"))).getField(importE)); Assert.assertEquals( 0, ((Message) message.getField(f("optional_lazy_message"))).getField(nestedB)); + Assert.assertEquals( + 0, ((Message) message.getField(f("optional_unverified_lazy_message"))).getField(nestedB)); // Enums without defaults are set to the first value in the enum. Assert.assertEquals(nestedFoo, message.getField(f("optional_nested_enum")));
diff --git a/java/core/src/test/java/com/google/protobuf/TestUtilLite.java b/java/core/src/test/java/com/google/protobuf/TestUtilLite.java index 993dd9d..dd8c11a 100644 --- a/java/core/src/test/java/com/google/protobuf/TestUtilLite.java +++ b/java/core/src/test/java/com/google/protobuf/TestUtilLite.java
@@ -80,6 +80,7 @@ import static com.google.protobuf.UnittestLite.optionalStringPieceExtensionLite; import static com.google.protobuf.UnittestLite.optionalUint32ExtensionLite; import static com.google.protobuf.UnittestLite.optionalUint64ExtensionLite; +import static com.google.protobuf.UnittestLite.optionalUnverifiedLazyMessageExtensionLite; import static com.google.protobuf.UnittestLite.packedBoolExtensionLite; import static com.google.protobuf.UnittestLite.packedDoubleExtensionLite; import static com.google.protobuf.UnittestLite.packedEnumExtensionLite; @@ -197,6 +198,8 @@ builder.setOptionalImportMessage(ImportMessageLite.newBuilder().setD(120).build()); builder.setOptionalPublicImportMessage(PublicImportMessageLite.newBuilder().setE(126).build()); builder.setOptionalLazyMessage(TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); + builder.setOptionalUnverifiedLazyMessage( + TestAllTypesLite.NestedMessage.newBuilder().setBb(128).build()); builder.setOptionalNestedEnum(TestAllTypesLite.NestedEnum.BAZ); builder.setOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_BAZ); @@ -355,6 +358,9 @@ message.setExtension( optionalLazyMessageExtensionLite, TestAllTypesLite.NestedMessage.newBuilder().setBb(127).build()); + message.setExtension( + optionalUnverifiedLazyMessageExtensionLite, + TestAllTypesLite.NestedMessage.newBuilder().setBb(128).build()); message.setExtension(optionalNestedEnumExtensionLite, TestAllTypesLite.NestedEnum.BAZ); message.setExtension(optionalForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ);
diff --git a/java/core/src/test/proto/com/google/protobuf/map_lite_test.proto b/java/core/src/test/proto/com/google/protobuf/map_lite_test.proto index 7324653..ee291e9 100644 --- a/java/core/src/test/proto/com/google/protobuf/map_lite_test.proto +++ b/java/core/src/test/proto/com/google/protobuf/map_lite_test.proto
@@ -119,3 +119,8 @@ // null is not a 'reserved word' per se but as a literal needs similar care map<string, SampleEnum> null = 10; } + +// https://github.com/protocolbuffers/protobuf/issues/9785 +message MapContainer { + map<string,string> my_map = 1; +}
diff --git a/java/core/src/test/proto/com/google/protobuf/map_test.proto b/java/core/src/test/proto/com/google/protobuf/map_test.proto index 240600f..872f4ec 100644 --- a/java/core/src/test/proto/com/google/protobuf/map_test.proto +++ b/java/core/src/test/proto/com/google/protobuf/map_test.proto
@@ -118,3 +118,8 @@ // null is not a 'reserved word' per se but as a literal needs similar care map<string, SampleEnum> null = 10; } + +// https://github.com/protocolbuffers/protobuf/issues/9785 +message MapContainer { + map<string,string> my_map = 1; +}
diff --git a/java/kotlin-lite/src/test/kotlin/com/google/protobuf/Proto2LiteTest.kt b/java/kotlin-lite/src/test/kotlin/com/google/protobuf/Proto2LiteTest.kt index 1f45f65..c343ccd 100644 --- a/java/kotlin-lite/src/test/kotlin/com/google/protobuf/Proto2LiteTest.kt +++ b/java/kotlin-lite/src/test/kotlin/com/google/protobuf/Proto2LiteTest.kt
@@ -93,6 +93,7 @@ optionalImportMessage = ImportMessageLite.newBuilder().setD(120).build() optionalPublicImportMessage = PublicImportMessageLite.newBuilder().setE(126).build() optionalLazyMessage = nestedMessage { bb = 127 } + optionalUnverifiedLazyMessage = nestedMessage { bb = 128 } optionalNestedEnum = NestedEnum.BAZ optionalForeignEnum = ForeignEnumLite.FOREIGN_LITE_BAZ optionalImportEnum = ImportEnumLite.IMPORT_LITE_BAZ @@ -423,6 +424,8 @@ PublicImportMessageLite.newBuilder().setE(126).build() this[UnittestLite.optionalLazyMessageExtensionLite] = TestAllTypesLiteKt.nestedMessage { bb = 127 } + this[UnittestLite.optionalUnverifiedLazyMessageExtensionLite] = + TestAllTypesLiteKt.nestedMessage { bb = 128 } this[UnittestLite.optionalNestedEnumExtensionLite] = NestedEnum.BAZ this[UnittestLite.optionalForeignEnumExtensionLite] = ForeignEnumLite.FOREIGN_LITE_BAZ this[UnittestLite.optionalImportEnumExtensionLite] = ImportEnumLite.IMPORT_LITE_BAZ
diff --git a/java/kotlin/src/test/kotlin/com/google/protobuf/Proto2Test.kt b/java/kotlin/src/test/kotlin/com/google/protobuf/Proto2Test.kt index 4463bc1..af797cc 100644 --- a/java/kotlin/src/test/kotlin/com/google/protobuf/Proto2Test.kt +++ b/java/kotlin/src/test/kotlin/com/google/protobuf/Proto2Test.kt
@@ -98,6 +98,7 @@ optionalImportMessage = ImportMessage.newBuilder().setD(120).build() optionalPublicImportMessage = PublicImportMessage.newBuilder().setE(126).build() optionalLazyMessage = nestedMessage { bb = 127 } + optionalUnverifiedLazyMessage = nestedMessage { bb = 128 } optionalNestedEnum = NestedEnum.BAZ optionalForeignEnum = ForeignEnum.FOREIGN_BAZ optionalImportEnum = ImportEnum.IMPORT_BAZ @@ -415,6 +416,8 @@ PublicImportMessage.newBuilder().setE(126).build() this[UnittestProto.optionalLazyMessageExtension] = TestAllTypesKt.nestedMessage { bb = 127 } + this[UnittestProto.optionalUnverifiedLazyMessageExtension] = + TestAllTypesKt.nestedMessage { bb = 128 } this[UnittestProto.optionalNestedEnumExtension] = NestedEnum.BAZ this[UnittestProto.optionalForeignEnumExtension] = ForeignEnum.FOREIGN_BAZ this[UnittestProto.optionalImportEnumExtension] = ImportEnum.IMPORT_BAZ
diff --git a/java/lite.md b/java/lite.md index 01be2cc..0620a66 100644 --- a/java/lite.md +++ b/java/lite.md
@@ -4,27 +4,26 @@ https://developers.google.com/protocol-buffers/ -## Use Protobuf Java Lite Runtime +## Use the Protobuf Java Lite Runtime -Protobuf Java Lite runtime is separated from the main Java runtime because -it's designed/implemented with different constraints. In particular, Java -Lite runtime has a much smaller code size which makes it more suitable to -be used on Android. +The Protobuf Java Lite runtime is separated from the main Java runtime because +it's designed and implemented with different constraints. In particular, the Java +Lite runtime is much smaller which makes it more suitable to be used on Android. -Note that in order to achieve maximum performance and code size, we will +In order to achieve maximum performance and code size, we do NOT guarantee API/ABI stability for Java Lite. If this is not acceptable -for your use-case, please use the full Java runtime instead. Note that +for your use-case, use the full Java runtime instead. Note that the latest version of Java Lite is not compatible with the 3.0.0 version. You can generate Java Lite code for your .proto files: $ protoc --java_out=lite:${OUTPUT_DIR} path/to/your/proto/file -Note that "optimize_for = LITE_RUNTIME" option in proto file is deprecated -and will not have any effect any more. +The "optimize_for = LITE_RUNTIME" option in the .proto file no longer has any +effect on Java code. Include the generated Java files in your project and add a dependency on the -protobuf Java runtime. If you are using Maven, use the following: +protobuf Java Lite runtime. If you are using Maven, include the following: ```xml <dependency>
diff --git a/java/pom.xml b/java/pom.xml index bb2efef..3c44917 100644 --- a/java/pom.xml +++ b/java/pom.xml
@@ -87,12 +87,12 @@ <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> - <version>30.1.1-android</version> + <version>31.1-android</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava-testlib</artifactId> - <version>30.1.1-android</version> + <version>31.1-android</version> <scope>test</scope> </dependency> <dependency>
diff --git a/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java b/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java index 854c826..096acee 100644 --- a/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java +++ b/java/util/src/main/java/com/google/protobuf/util/FieldMaskTree.java
@@ -142,7 +142,7 @@ * <li>If all children of a node have been removed, the node itself will be removed as well. * That is, if "foo" only has one child "bar" and "foo.bar" only has one child "baz", * removing "foo.bar.barz" would remove both "foo" and "foo.bar". If "foo" has both "bar" - * and "qux" as children, removing "foo.bar" would leave the path "foo.qux" intact. + * and "moo" as children, removing "foo.bar" would leave the path "foo.moo" intact. * <li>If the field path to remove is a non-exist sub-path, nothing will be changed. * </ul> */
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 a2d18bc..6bed2e3 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
@@ -295,9 +295,9 @@ /** - * Create a new {@link Printer} that will omit all insignificant whitespace in the JSON output. + * Create a new {@link Printer} that omits insignificant whitespace in the JSON output. * This new Printer clones all other configurations from the current Printer. Insignificant - * whitespace is defined by the JSON spec as whitespace that appear between JSON structural + * whitespace is defined by the JSON spec as whitespace that appears between JSON structural * elements: * * <pre> @@ -308,8 +308,7 @@ * %x0D ) ; Carriage return * </pre> * - * See <a href="https://tools.ietf.org/html/rfc7159">https://tools.ietf.org/html/rfc7159</a> - * current {@link Printer}. + * See <a href="https://tools.ietf.org/html/rfc7159">https://tools.ietf.org/html/rfc7159</a>. */ public Printer omittingInsignificantWhitespace() { return new Printer( @@ -1719,7 +1718,8 @@ FieldDescriptor field, JsonElement json, Message.Builder builder) throws InvalidProtocolBufferException { if (!(json instanceof JsonArray)) { - throw new InvalidProtocolBufferException("Expect an array but found: " + json); + throw new InvalidProtocolBufferException( + "Expected an array for " + field.getName() + " but found " + json); } JsonArray array = (JsonArray) json; for (int i = 0; i < array.size(); ++i) {
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 2169690..c31031e 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
@@ -821,6 +821,23 @@ } @Test + // https://github.com/protocolbuffers/protobuf/issues/7456 + public void testArrayTypeMismatch() throws IOException { + TestAllTypes.Builder builder = TestAllTypes.newBuilder(); + try { + mergeFromJson( + "{\n" + + " \"repeated_int32\": 5\n" + + "}", + builder); + assertWithMessage("should have thrown exception for incorrect type").fail(); + } catch (InvalidProtocolBufferException expected) { + assertThat(expected).hasMessageThat() + .isEqualTo("Expected an array for repeated_int32 but found 5"); + } + } + + @Test public void testParserAcceptNonQuotedObjectKey() throws Exception { TestMap.Builder builder = TestMap.newBuilder(); mergeFromJson(
diff --git a/js/README.md b/js/README.md index 6169700..f700237 100644 --- a/js/README.md +++ b/js/README.md
@@ -35,7 +35,7 @@ If you want, you can compile `protoc` from source instead. To do this follow the instructions in [the top-level -README](https://github.com/protocolbuffers/protobuf/blob/master/src/README.md). +README](https://github.com/protocolbuffers/protobuf/blob/main/src/README.md). Once you have `protoc` compiled, you can run the tests provided along with our project to examine whether it can run successfully. In order to do this, you should download the Protocol Buffer source code from the release page with the link above. Then extract the source code and navigate to the folder named `js` containing a `package.json` file and a series of test files. In this folder, you can run the commands below to run the tests automatically. @@ -129,7 +129,7 @@ Where `OPTIONS` are separated by commas. Options are either `opt=val` or just `opt` (for options that don't take a value). The available options are specified and documented in the `GeneratorOptions` struct in -[src/google/protobuf/compiler/js/js_generator.h](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/compiler/js/js_generator.h#L53). +[src/google/protobuf/compiler/js/js_generator.h](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/compiler/js/js_generator.h#L53). Some examples:
diff --git a/js/binary/reader_test.js b/js/binary/reader_test.js index 7e46828..6963f77 100644 --- a/js/binary/reader_test.js +++ b/js/binary/reader_test.js
@@ -57,8 +57,8 @@ it('testInstanceCaches', /** @suppress {visibility} */ function() { var writer = new jspb.BinaryWriter(); var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); - writer.writeMessage(1, dummyMessage, goog.nullFunction); - writer.writeMessage(2, dummyMessage, goog.nullFunction); + writer.writeMessage(1, dummyMessage, () => {}); + writer.writeMessage(2, dummyMessage, () => {}); var buffer = writer.getResultBuffer(); @@ -139,7 +139,7 @@ var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); reader.nextField(); assertThrows(function() { - reader.readMessage(dummyMessage, goog.nullFunction); + reader.readMessage(dummyMessage, () => {}); }); // Reading past the end of the stream should trigger an assertion. @@ -651,7 +651,7 @@ }); // Add one empty message. - writer.writeMessage(6, dummyMessage, goog.nullFunction); + writer.writeMessage(6, dummyMessage, () => {}); writer.writeInt32(7, 700);
diff --git a/js/binary/writer_test.js b/js/binary/writer_test.js index 6c5f36e..543cff6 100644 --- a/js/binary/writer_test.js +++ b/js/binary/writer_test.js
@@ -65,7 +65,7 @@ var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); assertFails(function() { - writer.writeMessage(-1, dummyMessage, goog.nullFunction); + writer.writeMessage(-1, dummyMessage, () => {}); }); // Writing invalid field indices should assert.
diff --git a/js/compatibility_tests/v3.0.0/binary/reader_test.js b/js/compatibility_tests/v3.0.0/binary/reader_test.js index 9571138..285b0e5 100644 --- a/js/compatibility_tests/v3.0.0/binary/reader_test.js +++ b/js/compatibility_tests/v3.0.0/binary/reader_test.js
@@ -56,8 +56,8 @@ it('testInstanceCaches', /** @suppress {visibility} */ function() { var writer = new jspb.BinaryWriter(); var dummyMessage = /** @type {!jspb.BinaryMessage} */({}); - writer.writeMessage(1, dummyMessage, goog.nullFunction); - writer.writeMessage(2, dummyMessage, goog.nullFunction); + writer.writeMessage(1, dummyMessage, () => {}); + writer.writeMessage(2, dummyMessage, () => {}); var buffer = writer.getResultBuffer(); @@ -138,7 +138,7 @@ var dummyMessage = /** @type {!jspb.BinaryMessage} */({}); reader.nextField(); assertThrows(function() { - reader.readMessage(dummyMessage, goog.nullFunction); + reader.readMessage(dummyMessage, () => {}); }); // Reading past the end of the stream should trigger an assertion. @@ -596,7 +596,7 @@ }); // Add one empty message. - writer.writeMessage(6, dummyMessage, goog.nullFunction); + writer.writeMessage(6, dummyMessage, () => {}); writer.writeInt32(7, 700);
diff --git a/js/compatibility_tests/v3.0.0/binary/writer_test.js b/js/compatibility_tests/v3.0.0/binary/writer_test.js index d5dadb4..f896c3b 100644 --- a/js/compatibility_tests/v3.0.0/binary/writer_test.js +++ b/js/compatibility_tests/v3.0.0/binary/writer_test.js
@@ -62,7 +62,7 @@ var dummyMessage = /** @type {!jspb.BinaryMessage} */({}); assertFails(function() { - writer.writeMessage(-1, dummyMessage, goog.nullFunction); + writer.writeMessage(-1, dummyMessage, () => {}); }); // Writing invalid field indices should assert.
diff --git a/js/compatibility_tests/v3.1.0/binary/reader_test.js b/js/compatibility_tests/v3.1.0/binary/reader_test.js index d0062de..3b05176 100644 --- a/js/compatibility_tests/v3.1.0/binary/reader_test.js +++ b/js/compatibility_tests/v3.1.0/binary/reader_test.js
@@ -56,8 +56,8 @@ it('testInstanceCaches', /** @suppress {visibility} */ function() { var writer = new jspb.BinaryWriter(); var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); - writer.writeMessage(1, dummyMessage, goog.nullFunction); - writer.writeMessage(2, dummyMessage, goog.nullFunction); + writer.writeMessage(1, dummyMessage, () => {}); + writer.writeMessage(2, dummyMessage, () => {}); var buffer = writer.getResultBuffer(); @@ -138,7 +138,7 @@ var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); reader.nextField(); assertThrows(function() { - reader.readMessage(dummyMessage, goog.nullFunction); + reader.readMessage(dummyMessage, () => {}); }); // Reading past the end of the stream should trigger an assertion. @@ -620,7 +620,7 @@ }); // Add one empty message. - writer.writeMessage(6, dummyMessage, goog.nullFunction); + writer.writeMessage(6, dummyMessage, () => {}); writer.writeInt32(7, 700);
diff --git a/js/compatibility_tests/v3.1.0/binary/writer_test.js b/js/compatibility_tests/v3.1.0/binary/writer_test.js index 55bc6be..5779cc5 100644 --- a/js/compatibility_tests/v3.1.0/binary/writer_test.js +++ b/js/compatibility_tests/v3.1.0/binary/writer_test.js
@@ -62,7 +62,7 @@ var dummyMessage = /** @type {!jspb.BinaryMessage} */ ({}); assertFails(function() { - writer.writeMessage(-1, dummyMessage, goog.nullFunction); + writer.writeMessage(-1, dummyMessage, () => {}); }); // Writing invalid field indices should assert.
diff --git a/js/package.json b/js/package.json index 6affb98..f3c0e72 100644 --- a/js/package.json +++ b/js/package.json
@@ -20,7 +20,7 @@ }, "repository": { "type": "git", - "url": "https://github.com/protocolbuffers/protobuf/tree/master/js" + "url": "https://github.com/protocolbuffers/protobuf/tree/main/js" }, "author": "Google Protocol Buffers Team", "license": "BSD-3-Clause"
diff --git a/kokoro/caplog.sh b/kokoro/caplog.sh new file mode 100644 index 0000000..fe81949 --- /dev/null +++ b/kokoro/caplog.sh
@@ -0,0 +1,92 @@ +# Log capturing for the Kokoro runtime environment. +# +# This script should be `source`d from Kokoro build scripts to configure log +# capturing when running under Kokoro. +# +# When not running under Kokoro, no logs will be collected. If you want to run +# locally and collect logs anyway, set the KOKORO_ARTIFACTS_DIR environment +# variable to a directory where the logs should go. +# +# The job `.cfg` file needs the following stanzas to declare the captured logs +# as outputs (yes, these are globs, not regexes): +# +# action: { +# define_artifacts: { +# regex: "**/*sponge_log.log" +# regex: "**/*sponge_log.xml" +# } +# } +# +# Use the provided functions below as build/test fixtures, e.g.: +# +# source kokoro/capture_logs.sh +# caplog build/step1 <build command> +# caplog tests/step2 <test command> +# +# If log capturing is enabled, this script will set some variables that can be +# used if necessary: +# +# CAPLOG_DIR is used for logs +# CAPLOG_CMAKE_ARGS contains extra cmake args to enable test XML output +# CAPLOG_CTEST_ARGS contains extra ctest args to capture combined test logs +# +# For example: +# +# if [[ -v CAPLOG_DIR_BUILD ]]; then +# cp extra_diagnostics.log "${CAPLOG_DIR_BUILD}/diagnostics.log" +# fi +# +# # Use ${...:-} form under `set -u`: +# caplog build/01_configure cmake -G Ninja ${CAPLOG_CMAKE_ARGS:-} +# caplog build/02_build cmake --build +# caplog test/03_test ctest ${CAPLOG_CTEST_ARGS:-} + +if [[ -z ${KOKORO_ARTIFACTS_DIR:-} ]]; then + function caplog() { shift; "$@"; } +else + + CAPLOG_DIR="$(mktemp -d)" + CAPLOG_CMAKE_ARGS="-Dprotobuf_TEST_XML_OUTDIR=${CAPLOG_DIR}/tests/" + CAPLOG_CTEST_ARGS="--verbose" + + # Captures the stdout/stderr of a command to a named log file. + # Usage: caplog NAME COMMAND [ARGS...] + function caplog() { + _name="${CAPLOG_DIR}/${1%.log}.log"; shift + mkdir -p "${_name%/*}" + date + time ( "$@" 2>&1 | tee "${_name}" ) + if [[ $? != 0 ]] ; then + cat "${_name}" + return 1 + fi + } + + # Trap handler: renames logs on script exit so they will be found by Kokoro. + function _caplog_onexit() { + _rc=$? + set +x + echo "Collecting logs [${BASH_SOURCE}]" + + find "${CAPLOG_DIR}" -type f -name '*.log' \ + | while read _textlog; do + # Ensure an XML file exists for each .log file. + touch ${_textlog%.log}.xml + done + + find "${CAPLOG_DIR}" -type f \( -name '*.xml' -or -name '*.log' \) \ + | while read _src; do + # Move to artifacts dir, preserving the path relative to CAPLOG_DIR. + # The filename changes from foo/bar.log to foo/bar/sponge_log.log. + _logfile=${_src/${CAPLOG_DIR}\//} + _stem=${KOKORO_ARTIFACTS_DIR}/${_logfile%.*} + _ext=${_logfile##*.} + mkdir -p ${_stem} + mv -v "${_src}" "${_stem}/sponge_log.${_ext}" + done + rm -rv "${CAPLOG_DIR}" + exit ${_rc} + } + trap _caplog_onexit EXIT + +fi
diff --git a/kokoro/docs/publish-python.sh b/kokoro/docs/publish-python.sh index 457a24f..e6caf2d 100755 --- a/kokoro/docs/publish-python.sh +++ b/kokoro/docs/publish-python.sh
@@ -1,5 +1,5 @@ #!/bin/bash -# Adapted from https://github.com/googleapis/google-cloud-python/blob/master/.kokoro/publish-docs.sh +# Adapted from https://github.com/googleapis/google-cloud-python/blob/main/.kokoro/publish-docs.sh set -eo pipefail
diff --git a/kokoro/docs/trampoline.sh b/kokoro/docs/trampoline.sh index db7e90b..4cb78a5 100755 --- a/kokoro/docs/trampoline.sh +++ b/kokoro/docs/trampoline.sh
@@ -1,5 +1,5 @@ #!/bin/bash -# Copied from https://github.com/googleapis/google-cloud-python/blob/master/.kokoro/trampoline.sh +# Copied from https://github.com/googleapis/google-cloud-python/blob/main/.kokoro/trampoline.sh set -eo pipefail
diff --git a/kokoro/linux/dockerfile/test/ruby/Dockerfile b/kokoro/linux/dockerfile/test/ruby/Dockerfile index 914cd4b..0e34fe5 100644 --- a/kokoro/linux/dockerfile/test/ruby/Dockerfile +++ b/kokoro/linux/dockerfile/test/ruby/Dockerfile
@@ -38,6 +38,7 @@ RUN /bin/bash -l -c "rvm install 3.1.0" RUN /bin/bash -l -c "rvm install jruby-9.2.20.1" RUN /bin/bash -l -c "rvm install jruby-9.3.3.0" +RUN /bin/bash -l -c "rvm install jruby-9.3.4.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/macos-next/README.md b/kokoro/macos-next/README.md new file mode 100644 index 0000000..4657855 --- /dev/null +++ b/kokoro/macos-next/README.md
@@ -0,0 +1,4 @@ +# macOS-next + +This builder is temporary for developing and testing builds using the "next" +macOS version without affecting the ordinary builds.
diff --git a/kokoro/macos-next/cpp/build.sh b/kokoro/macos-next/cpp/build.sh new file mode 100755 index 0000000..490e990 --- /dev/null +++ b/kokoro/macos-next/cpp/build.sh
@@ -0,0 +1,55 @@ +#!/bin/bash -eux +# +# Build file to set up and run tests + +set -o pipefail + +if [[ -h /tmpfs ]] && [[ ${PWD} == /tmpfs/src ]]; then + # Workaround for internal Kokoro bug: b/227401944 + cd /Volumes/BuildData/tmpfs/src +fi + +# These vars can be changed when running manually, e.g.: +# +# % BUILD_CONFIG=RelWithDebInfo path/to/build.sh + +# By default, build using Debug config. +: ${BUILD_CONFIG:=Debug} + +# By default, find the sources based on this script path. +: ${SOURCE_DIR:=$(cd $(dirname $0)/../../..; pwd)} + +# By default, put outputs under <git root>/cmake/build. +: ${BUILD_DIR:=${SOURCE_DIR}/cmake/build} + +source ${SOURCE_DIR}/kokoro/caplog.sh + +# +# Update submodules +# +git -C "${SOURCE_DIR}" submodule update --init --recursive + +# +# Configure and build in a separate directory +# +mkdir -p "${BUILD_DIR}" + +caplog 01_configure \ + cmake -S "${SOURCE_DIR}" -B "${BUILD_DIR}" ${CAPLOG_CMAKE_ARGS:-} + +if [[ -n ${CAPLOG_DIR:-} ]]; then + mkdir -p "${CAPLOG_DIR}/CMakeFiles" + cp "${BUILD_DIR}"/CMakeFiles/CMake*.log "${CAPLOG_DIR}/CMakeFiles" +fi + +caplog 02_build \ + cmake --build "${BUILD_DIR}" --config "${BUILD_CONFIG}" + +# +# Run tests +# +( + cd "${BUILD_DIR}" + caplog 03_combined_testlog \ + ctest -C "${BUILD_CONFIG}" -j4 ${CAPLOG_CTEST_ARGS:-} +)
diff --git a/kokoro/macos-next/cpp/continuous.cfg b/kokoro/macos-next/cpp/continuous.cfg new file mode 100644 index 0000000..166caa5 --- /dev/null +++ b/kokoro/macos-next/cpp/continuous.cfg
@@ -0,0 +1,13 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos-next/cpp/build.sh" +timeout_mins: 1440 + +# Upload logs +action: { + define_artifacts: { + regex: "**/*sponge_log.log" + regex: "**/*sponge_log.xml" + } +}
diff --git a/kokoro/macos-next/cpp/presubmit.cfg b/kokoro/macos-next/cpp/presubmit.cfg new file mode 100644 index 0000000..166caa5 --- /dev/null +++ b/kokoro/macos-next/cpp/presubmit.cfg
@@ -0,0 +1,13 @@ +# Config file for running tests in Kokoro + +# Location of the build script in repository +build_file: "protobuf/kokoro/macos-next/cpp/build.sh" +timeout_mins: 1440 + +# Upload logs +action: { + define_artifacts: { + regex: "**/*sponge_log.log" + regex: "**/*sponge_log.xml" + } +}
diff --git a/kokoro/release/protoc/windows/build.bat b/kokoro/release/protoc/windows/build.bat index ae0fa94..75ea546 100644 --- a/kokoro/release/protoc/windows/build.bat +++ b/kokoro/release/protoc/windows/build.bat
@@ -8,6 +8,11 @@ echo Building protoc cd github\protobuf +echo Update Submodules +echo This is needed because this build uses CMake <3.13. +git submodule update --init --recursive +set ABSL_ROOT_DIR=%cd%\third_party\abseil-cpp + mkdir build32 cd build32 cmake -G "%generator32%" -Dprotobuf_BUILD_TESTS=OFF -Dprotobuf_BUILD_SHARED_LIBS=OFF -Dprotobuf_UNICODE=ON ../cmake
diff --git a/kokoro/release/python/linux/build_artifacts.sh b/kokoro/release/python/linux/build_artifacts.sh index 9a3fc58..3ddec74 100755 --- a/kokoro/release/python/linux/build_artifacts.sh +++ b/kokoro/release/python/linux/build_artifacts.sh
@@ -30,7 +30,7 @@ # silently creeping in (see https://github.com/protocolbuffers/protobuf/issues/9180). # IMPORTANT: always pin multibuild at the same commit for: # - linux/build_artifacts.sh -# - linux/build_artifacts.sh +# - macos/build_artifacts.sh # - windows/build_artifacts.bat (cd multibuild; git checkout b89bb903e94308be79abefa4f436bf123ebb1313) cp kokoro/release/python/linux/config.sh config.sh
diff --git a/kokoro/release/python/macos/build_artifacts.sh b/kokoro/release/python/macos/build_artifacts.sh index aeb4242..bd60d75 100755 --- a/kokoro/release/python/macos/build_artifacts.sh +++ b/kokoro/release/python/macos/build_artifacts.sh
@@ -30,7 +30,7 @@ # silently creeping in (see https://github.com/protocolbuffers/protobuf/issues/9180). # IMPORTANT: always pin multibuild at the same commit for: # - linux/build_artifacts.sh -# - linux/build_artifacts.sh +# - macos/build_artifacts.sh # - windows/build_artifacts.bat (cd multibuild; git checkout b89bb903e94308be79abefa4f436bf123ebb1313) cp kokoro/release/python/macos/config.sh config.sh
diff --git a/kokoro/release/python/windows/build_artifacts.bat b/kokoro/release/python/windows/build_artifacts.bat index 121283a..32fbec4 100644 --- a/kokoro/release/python/windows/build_artifacts.bat +++ b/kokoro/release/python/windows/build_artifacts.bat
@@ -18,7 +18,7 @@ REM silently creeping in (see https://github.com/protocolbuffers/protobuf/issues/9180). REM IMPORTANT: always pin multibuild at the same commit for: REM - linux/build_artifacts.sh -REM - linux/build_artifacts.sh +REM - macos/build_artifacts.sh REM - windows/build_artifacts.bat cd multibuild git checkout b89bb903e94308be79abefa4f436bf123ebb1313 @@ -34,6 +34,11 @@ del /Q zlib.zip del /Q zlib-src.zip +REM Update Submodules +REM This is needed because this build uses CMake <3.13. +git submodule update --init --recursive +SET ABSL_ROOT_DIR=%cd%\third_party\abseil-cpp + REM Create directory for artifacts SET ARTIFACT_DIR=%cd%\artifacts mkdir %ARTIFACT_DIR%
diff --git a/kokoro/release/python/windows/build_single_artifact.bat b/kokoro/release/python/windows/build_single_artifact.bat index af2d265..d2c96c3 100644 --- a/kokoro/release/python/windows/build_single_artifact.bat +++ b/kokoro/release/python/windows/build_single_artifact.bat
@@ -49,7 +49,7 @@ mkdir vcprojects pushd vcprojects -cmake -G "%generator%" -Dprotobuf_BUILD_SHARED_LIBS=%BUILD_DLL% -Dprotobuf_UNICODE=%UNICODE% -Dprotobuf_BUILD_TESTS=OFF ../cmake || goto :error +cmake -G "%generator%" -Dprotobuf_BUILD_SHARED_LIBS=%BUILD_DLL% -Dprotobuf_UNICODE=%UNICODE% -Dprotobuf_BUILD_TESTS=OFF -DABSL_ROOT_DIR=%ABSL_ROOT_DIR% ../cmake || goto :error msbuild protobuf.sln /p:Platform=%vcplatform% /p:Configuration=Release || goto :error dir /s /b popd
diff --git a/maven_install.json b/maven_install.json index 808e013..9c5860a 100644 --- a/maven_install.json +++ b/maven_install.json
@@ -1,10 +1,10 @@ { "dependency_tree": { "__AUTOGENERATED_FILE_DO_NOT_MODIFY_THIS_FILE_MANUALLY": "THERE_IS_NO_DATA_ONLY_ZUUL", - "__INPUT_ARTIFACTS_HASH": -1867950668, - "__RESOLVED_ARTIFACTS_HASH": 1254982283, + "__INPUT_ARTIFACTS_HASH": -228414992, + "__RESOLVED_ARTIFACTS_HASH": -722345565, "conflict_resolution": { - "com.google.errorprone:error_prone_annotations:2.3.2": "com.google.errorprone:error_prone_annotations:2.5.1", + "com.google.errorprone:error_prone_annotations:2.3.2": "com.google.errorprone:error_prone_annotations:2.11.0", "junit:junit:4.12": "junit:junit:4.13.2" }, "dependencies": [ @@ -45,16 +45,16 @@ "url": "https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.9/gson-2.8.9.jar" }, { - "coord": "com.google.errorprone:error_prone_annotations:2.5.1", + "coord": "com.google.errorprone:error_prone_annotations:2.11.0", "dependencies": [], "directDependencies": [], - "file": "v1/https/repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.5.1/error_prone_annotations-2.5.1.jar", + "file": "v1/https/repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.11.0/error_prone_annotations-2.11.0.jar", "mirror_urls": [ - "https://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.5.1/error_prone_annotations-2.5.1.jar", - "https://repo.maven.apache.org/maven2/com/google/errorprone/error_prone_annotations/2.5.1/error_prone_annotations-2.5.1.jar" + "https://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.11.0/error_prone_annotations-2.11.0.jar", + "https://repo.maven.apache.org/maven2/com/google/errorprone/error_prone_annotations/2.11.0/error_prone_annotations-2.11.0.jar" ], - "sha256": "ff80626baaf12a09342befd4e84cba9d50662f5fcd7f7a9b3490a6b7cf87e66c", - "url": "https://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.5.1/error_prone_annotations-2.5.1.jar" + "sha256": "721cb91842b46fa056847d104d5225c8b8e1e8b62263b993051e1e5a0137b7ec", + "url": "https://repo1.maven.org/maven2/com/google/errorprone/error_prone_annotations/2.11.0/error_prone_annotations-2.11.0.jar" }, { "coord": "com.google.guava:failureaccess:1.0.1", @@ -69,59 +69,59 @@ "url": "https://repo1.maven.org/maven2/com/google/guava/failureaccess/1.0.1/failureaccess-1.0.1.jar" }, { - "coord": "com.google.guava:guava-testlib:30.1.1-jre", + "coord": "com.google.guava:guava-testlib:31.1-jre", "dependencies": [ "com.google.code.findbugs:jsr305:3.0.2", - "com.google.errorprone:error_prone_annotations:2.5.1", + "com.google.errorprone:error_prone_annotations:2.11.0", "com.google.guava:failureaccess:1.0.1", - "com.google.guava:guava:30.1.1-jre", + "com.google.guava:guava:31.1-jre", "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava", "com.google.j2objc:j2objc-annotations:1.3", "junit:junit:4.13.2", - "org.checkerframework:checker-qual:3.9.1", + "org.checkerframework:checker-qual:3.12.0", "org.hamcrest:hamcrest-core:1.3" ], "directDependencies": [ "com.google.code.findbugs:jsr305:3.0.2", - "com.google.errorprone:error_prone_annotations:2.5.1", - "com.google.guava:guava:30.1.1-jre", + "com.google.errorprone:error_prone_annotations:2.11.0", + "com.google.guava:guava:31.1-jre", "com.google.j2objc:j2objc-annotations:1.3", "junit:junit:4.13.2", - "org.checkerframework:checker-qual:3.9.1" + "org.checkerframework:checker-qual:3.12.0" ], - "file": "v1/https/repo1.maven.org/maven2/com/google/guava/guava-testlib/30.1.1-jre/guava-testlib-30.1.1-jre.jar", + "file": "v1/https/repo1.maven.org/maven2/com/google/guava/guava-testlib/31.1-jre/guava-testlib-31.1-jre.jar", "mirror_urls": [ - "https://repo1.maven.org/maven2/com/google/guava/guava-testlib/30.1.1-jre/guava-testlib-30.1.1-jre.jar", - "https://repo.maven.apache.org/maven2/com/google/guava/guava-testlib/30.1.1-jre/guava-testlib-30.1.1-jre.jar" + "https://repo1.maven.org/maven2/com/google/guava/guava-testlib/31.1-jre/guava-testlib-31.1-jre.jar", + "https://repo.maven.apache.org/maven2/com/google/guava/guava-testlib/31.1-jre/guava-testlib-31.1-jre.jar" ], - "sha256": "8a7fc9adfa1e7441d1d30ca288c593ebc7c4a24c601d01169b781c398f24099b", - "url": "https://repo1.maven.org/maven2/com/google/guava/guava-testlib/30.1.1-jre/guava-testlib-30.1.1-jre.jar" + "sha256": "aadc71b10d5c3ac474dd16be84cfb18d257e584d1e0a59f8cab64ef4376226ce", + "url": "https://repo1.maven.org/maven2/com/google/guava/guava-testlib/31.1-jre/guava-testlib-31.1-jre.jar" }, { - "coord": "com.google.guava:guava:30.1.1-jre", + "coord": "com.google.guava:guava:31.1-jre", "dependencies": [ "com.google.code.findbugs:jsr305:3.0.2", - "com.google.errorprone:error_prone_annotations:2.5.1", + "com.google.errorprone:error_prone_annotations:2.11.0", "com.google.guava:failureaccess:1.0.1", "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava", "com.google.j2objc:j2objc-annotations:1.3", - "org.checkerframework:checker-qual:3.9.1" + "org.checkerframework:checker-qual:3.12.0" ], "directDependencies": [ "com.google.code.findbugs:jsr305:3.0.2", - "com.google.errorprone:error_prone_annotations:2.5.1", + "com.google.errorprone:error_prone_annotations:2.11.0", "com.google.guava:failureaccess:1.0.1", "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava", "com.google.j2objc:j2objc-annotations:1.3", - "org.checkerframework:checker-qual:3.9.1" + "org.checkerframework:checker-qual:3.12.0" ], - "file": "v1/https/repo1.maven.org/maven2/com/google/guava/guava/30.1.1-jre/guava-30.1.1-jre.jar", + "file": "v1/https/repo1.maven.org/maven2/com/google/guava/guava/31.1-jre/guava-31.1-jre.jar", "mirror_urls": [ - "https://repo1.maven.org/maven2/com/google/guava/guava/30.1.1-jre/guava-30.1.1-jre.jar", - "https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1.1-jre/guava-30.1.1-jre.jar" + "https://repo1.maven.org/maven2/com/google/guava/guava/31.1-jre/guava-31.1-jre.jar", + "https://repo.maven.apache.org/maven2/com/google/guava/guava/31.1-jre/guava-31.1-jre.jar" ], - "sha256": "44ce229ce26d880bf3afc362bbfcec34d7e6903d195bbb1db9f3b6e0d9834f06", - "url": "https://repo1.maven.org/maven2/com/google/guava/guava/30.1.1-jre/guava-30.1.1-jre.jar" + "sha256": "a42edc9cab792e39fe39bb94f3fca655ed157ff87a8af78e1d6ba5b07c4a00ab", + "url": "https://repo1.maven.org/maven2/com/google/guava/guava/31.1-jre/guava-31.1-jre.jar" }, { "coord": "com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava", @@ -151,18 +151,18 @@ "coord": "com.google.truth:truth:1.1.2", "dependencies": [ "com.google.auto.value:auto-value-annotations:1.7.4", - "com.google.errorprone:error_prone_annotations:2.5.1", - "com.google.guava:guava:30.1.1-jre", + "com.google.errorprone:error_prone_annotations:2.11.0", + "com.google.guava:guava:31.1-jre", "junit:junit:4.13.2", - "org.checkerframework:checker-qual:3.9.1", + "org.checkerframework:checker-qual:3.12.0", "org.ow2.asm:asm:9.0" ], "directDependencies": [ "com.google.auto.value:auto-value-annotations:1.7.4", - "com.google.errorprone:error_prone_annotations:2.5.1", - "com.google.guava:guava:30.1.1-jre", + "com.google.errorprone:error_prone_annotations:2.11.0", + "com.google.guava:guava:31.1-jre", "junit:junit:4.13.2", - "org.checkerframework:checker-qual:3.9.1", + "org.checkerframework:checker-qual:3.12.0", "org.ow2.asm:asm:9.0" ], "file": "v1/https/repo1.maven.org/maven2/com/google/truth/truth/1.1.2/truth-1.1.2.jar", @@ -214,16 +214,16 @@ "url": "https://repo1.maven.org/maven2/net/bytebuddy/byte-buddy/1.12.7/byte-buddy-1.12.7.jar" }, { - "coord": "org.checkerframework:checker-qual:3.9.1", + "coord": "org.checkerframework:checker-qual:3.12.0", "dependencies": [], "directDependencies": [], - "file": "v1/https/repo1.maven.org/maven2/org/checkerframework/checker-qual/3.9.1/checker-qual-3.9.1.jar", + "file": "v1/https/repo1.maven.org/maven2/org/checkerframework/checker-qual/3.12.0/checker-qual-3.12.0.jar", "mirror_urls": [ - "https://repo1.maven.org/maven2/org/checkerframework/checker-qual/3.9.1/checker-qual-3.9.1.jar", - "https://repo.maven.apache.org/maven2/org/checkerframework/checker-qual/3.9.1/checker-qual-3.9.1.jar" + "https://repo1.maven.org/maven2/org/checkerframework/checker-qual/3.12.0/checker-qual-3.12.0.jar", + "https://repo.maven.apache.org/maven2/org/checkerframework/checker-qual/3.12.0/checker-qual-3.12.0.jar" ], - "sha256": "ab0468b1ba35bb2ae45f61a60dc4960bd887660ab8f05113a662a7e675eae776", - "url": "https://repo1.maven.org/maven2/org/checkerframework/checker-qual/3.9.1/checker-qual-3.9.1.jar" + "sha256": "ff10785ac2a357ec5de9c293cb982a2cbb605c0309ea4cc1cb9b9bc6dbe7f3cb", + "url": "https://repo1.maven.org/maven2/org/checkerframework/checker-qual/3.12.0/checker-qual-3.12.0.jar" }, { "coord": "org.hamcrest:hamcrest-core:1.3",
diff --git a/objectivec/DevTools/full_mac_build.sh b/objectivec/DevTools/full_mac_build.sh index 49b0ff4..0e183f2 100755 --- a/objectivec/DevTools/full_mac_build.sh +++ b/objectivec/DevTools/full_mac_build.sh
@@ -234,8 +234,14 @@ objectivec/generate_well_known_types.sh --check-only -j "${NUM_MAKE_JOBS}" header "Checking on the ObjC Runtime Code" -objectivec/DevTools/pddm_tests.py -if ! objectivec/DevTools/pddm.py --dry-run objectivec/*.[hm] objectivec/Tests/*.[hm] ; then +# Some of the kokoro machines don't have python3 yet, so fall back to python if need be. +if hash python3 >/dev/null 2>&1 ; then + LOCAL_PYTHON=python3 +else + LOCAL_PYTHON=python +fi +"${LOCAL_PYTHON}" objectivec/DevTools/pddm_tests.py +if ! "${LOCAL_PYTHON}" objectivec/DevTools/pddm.py --dry-run objectivec/*.[hm] objectivec/Tests/*.[hm] ; then echo "" echo "Update by running:" echo " objectivec/DevTools/pddm.py objectivec/*.[hm] objectivec/Tests/*.[hm]"
diff --git a/objectivec/DevTools/pddm.py b/objectivec/DevTools/pddm.py index b572cc7..60ff089 100755 --- a/objectivec/DevTools/pddm.py +++ b/objectivec/DevTools/pddm.py
@@ -1,4 +1,4 @@ -#! /usr/bin/python +#! /usr/bin/env python3 # # Protocol Buffers - Google's data interchange format # Copyright 2015 Google Inc. All rights reserved. @@ -134,7 +134,10 @@ class PDDMError(Exception): """Error thrown by pddm.""" - pass + + def __init__(self, message="Error"): + self.message = message + super().__init__(self.message) class MacroCollection(object): @@ -318,7 +321,7 @@ # Nothing to do return macro.body assert len(arg_values) == len(macro.args) - args = dict(zip(macro.args, arg_values)) + args = dict(list(zip(macro.args, arg_values))) def _lookupArg(match): val = args[match.group('name')] @@ -351,7 +354,7 @@ return macro_arg_ref_re.sub(_lookupArg, macro.body) def _EvalMacrosRefs(self, text, macro_stack): - macro_ref_re = _MacroRefRe(self._macros.keys()) + macro_ref_re = _MacroRefRe(list(self._macros.keys())) def _resolveMacro(match): return self._Expand(match, macro_stack)
diff --git a/objectivec/DevTools/pddm_tests.py b/objectivec/DevTools/pddm_tests.py index 8184209..d5b88c9 100755 --- a/objectivec/DevTools/pddm_tests.py +++ b/objectivec/DevTools/pddm_tests.py
@@ -1,4 +1,4 @@ -#! /usr/bin/python +#! /usr/bin/env python3 # # Protocol Buffers - Google's data interchange format # Copyright 2015 Google Inc. All rights reserved. @@ -41,24 +41,24 @@ class TestParsingMacros(unittest.TestCase): def testParseEmpty(self): - f = io.StringIO(u'') + f = io.StringIO('') result = pddm.MacroCollection(f) self.assertEqual(len(result._macros), 0) def testParseOne(self): - f = io.StringIO(u"""PDDM-DEFINE foo( ) + f = io.StringIO("""PDDM-DEFINE foo( ) body""") result = pddm.MacroCollection(f) self.assertEqual(len(result._macros), 1) macro = result._macros.get('foo') self.assertIsNotNone(macro) - self.assertEquals(macro.name, 'foo') - self.assertEquals(macro.args, tuple()) - self.assertEquals(macro.body, 'body') + self.assertEqual(macro.name, 'foo') + self.assertEqual(macro.args, tuple()) + self.assertEqual(macro.body, 'body') def testParseGeneral(self): # Tests multiple defines, spaces in all places, etc. - f = io.StringIO(u""" + f = io.StringIO(""" PDDM-DEFINE noArgs( ) body1 body2 @@ -74,21 +74,21 @@ self.assertEqual(len(result._macros), 3) macro = result._macros.get('noArgs') self.assertIsNotNone(macro) - self.assertEquals(macro.name, 'noArgs') - self.assertEquals(macro.args, tuple()) - self.assertEquals(macro.body, 'body1\nbody2\n') + self.assertEqual(macro.name, 'noArgs') + self.assertEqual(macro.args, tuple()) + self.assertEqual(macro.body, 'body1\nbody2\n') macro = result._macros.get('oneArg') self.assertIsNotNone(macro) - self.assertEquals(macro.name, 'oneArg') - self.assertEquals(macro.args, ('foo',)) - self.assertEquals(macro.body, 'body3') + self.assertEqual(macro.name, 'oneArg') + self.assertEqual(macro.args, ('foo',)) + self.assertEqual(macro.body, 'body3') macro = result._macros.get('twoArgs') self.assertIsNotNone(macro) - self.assertEquals(macro.name, 'twoArgs') - self.assertEquals(macro.args, ('bar_', 'baz')) - self.assertEquals(macro.body, 'body4\nbody5') + self.assertEqual(macro.name, 'twoArgs') + self.assertEqual(macro.args, ('bar_', 'baz')) + self.assertEqual(macro.body, 'body4\nbody5') # Add into existing collection - f = io.StringIO(u""" + f = io.StringIO(""" PDDM-DEFINE another(a,b,c) body1 body2""") @@ -96,23 +96,23 @@ self.assertEqual(len(result._macros), 4) macro = result._macros.get('another') self.assertIsNotNone(macro) - self.assertEquals(macro.name, 'another') - self.assertEquals(macro.args, ('a', 'b', 'c')) - self.assertEquals(macro.body, 'body1\nbody2') + self.assertEqual(macro.name, 'another') + self.assertEqual(macro.args, ('a', 'b', 'c')) + self.assertEqual(macro.body, 'body1\nbody2') def testParseDirectiveIssues(self): test_list = [ # Unknown directive - (u'PDDM-DEFINE foo()\nbody\nPDDM-DEFINED foo\nbaz', + ('PDDM-DEFINE foo()\nbody\nPDDM-DEFINED foo\nbaz', 'Hit a line with an unknown directive: '), # End without begin - (u'PDDM-DEFINE foo()\nbody\nPDDM-DEFINE-END\nPDDM-DEFINE-END\n', + ('PDDM-DEFINE foo()\nbody\nPDDM-DEFINE-END\nPDDM-DEFINE-END\n', 'Got DEFINE-END directive without an active macro: '), # Line not in macro block - (u'PDDM-DEFINE foo()\nbody\nPDDM-DEFINE-END\nmumble\n', + ('PDDM-DEFINE foo()\nbody\nPDDM-DEFINE-END\nmumble\n', 'Hit a line that wasn\'t a directive and no open macro definition: '), # Redefine macro - (u'PDDM-DEFINE foo()\nbody\nPDDM-DEFINE foo(a)\nmumble\n', + ('PDDM-DEFINE foo()\nbody\nPDDM-DEFINE foo(a)\nmumble\n', 'Attempt to redefine macro: '), ] for idx, (input_str, expected_prefix) in enumerate(test_list, 1): @@ -127,47 +127,47 @@ def testParseBeginIssues(self): test_list = [ # 1. No name - (u'PDDM-DEFINE\nmumble', + ('PDDM-DEFINE\nmumble', 'Failed to parse macro definition: '), # 2. No name (with spaces) - (u'PDDM-DEFINE \nmumble', + ('PDDM-DEFINE \nmumble', 'Failed to parse macro definition: '), # 3. No open paren - (u'PDDM-DEFINE foo\nmumble', + ('PDDM-DEFINE foo\nmumble', 'Failed to parse macro definition: '), # 4. No close paren - (u'PDDM-DEFINE foo(\nmumble', + ('PDDM-DEFINE foo(\nmumble', 'Failed to parse macro definition: '), # 5. No close paren (with args) - (u'PDDM-DEFINE foo(a, b\nmumble', + ('PDDM-DEFINE foo(a, b\nmumble', 'Failed to parse macro definition: '), # 6. No name before args - (u'PDDM-DEFINE (a, b)\nmumble', + ('PDDM-DEFINE (a, b)\nmumble', 'Failed to parse macro definition: '), # 7. No name before args - (u'PDDM-DEFINE foo bar(a, b)\nmumble', + ('PDDM-DEFINE foo bar(a, b)\nmumble', 'Failed to parse macro definition: '), # 8. Empty arg name - (u'PDDM-DEFINE foo(a, ,b)\nmumble', + ('PDDM-DEFINE foo(a, ,b)\nmumble', 'Empty arg name in macro definition: '), - (u'PDDM-DEFINE foo(a,,b)\nmumble', + ('PDDM-DEFINE foo(a,,b)\nmumble', 'Empty arg name in macro definition: '), # 10. Duplicate name - (u'PDDM-DEFINE foo(a,b,a,c)\nmumble', + ('PDDM-DEFINE foo(a,b,a,c)\nmumble', 'Arg name "a" used more than once in macro definition: '), # 11. Invalid arg name - (u'PDDM-DEFINE foo(a b,c)\nmumble', + ('PDDM-DEFINE foo(a b,c)\nmumble', 'Invalid arg name "a b" in macro definition: '), - (u'PDDM-DEFINE foo(a.b,c)\nmumble', + ('PDDM-DEFINE foo(a.b,c)\nmumble', 'Invalid arg name "a.b" in macro definition: '), - (u'PDDM-DEFINE foo(a-b,c)\nmumble', + ('PDDM-DEFINE foo(a-b,c)\nmumble', 'Invalid arg name "a-b" in macro definition: '), - (u'PDDM-DEFINE foo(a,b,c.)\nmumble', + ('PDDM-DEFINE foo(a,b,c.)\nmumble', 'Invalid arg name "c." in macro definition: '), # 15. Extra stuff after the name - (u'PDDM-DEFINE foo(a,c) foo\nmumble', + ('PDDM-DEFINE foo(a,c) foo\nmumble', 'Failed to parse macro definition: '), - (u'PDDM-DEFINE foo(a,c) foo)\nmumble', + ('PDDM-DEFINE foo(a,c) foo)\nmumble', 'Failed to parse macro definition: '), ] for idx, (input_str, expected_prefix) in enumerate(test_list, 1): @@ -183,7 +183,7 @@ class TestExpandingMacros(unittest.TestCase): def testExpandBasics(self): - f = io.StringIO(u""" + f = io.StringIO(""" PDDM-DEFINE noArgs( ) body1 body2 @@ -203,21 +203,21 @@ """) mc = pddm.MacroCollection(f) test_list = [ - (u'noArgs()', + ('noArgs()', 'body1\nbody2\n'), - (u'oneArg(wee)', + ('oneArg(wee)', 'body3 wee\n'), - (u'twoArgs(having some, fun)', + ('twoArgs(having some, fun)', 'body4 having some fun\nbody5'), # One arg, pass empty. - (u'oneArg()', + ('oneArg()', 'body3 \n'), # Two args, gets empty in each slot. - (u'twoArgs(, empty)', + ('twoArgs(, empty)', 'body4 empty\nbody5'), - (u'twoArgs(empty, )', + ('twoArgs(empty, )', 'body4 empty \nbody5'), - (u'twoArgs(, )', + ('twoArgs(, )', 'body4 \nbody5'), ] for idx, (input_str, expected) in enumerate(test_list, 1): @@ -227,7 +227,7 @@ (idx, result, expected)) def testExpandArgOptions(self): - f = io.StringIO(u""" + f = io.StringIO(""" PDDM-DEFINE bar(a) a-a$S-a$l-a$L-a$u-a$U PDDM-DEFINE-END @@ -240,7 +240,7 @@ self.assertEqual(mc.Expand('bar()'), '-----') def testExpandSimpleMacroErrors(self): - f = io.StringIO(u""" + f = io.StringIO(""" PDDM-DEFINE foo(a, b) <a-z> PDDM-DEFINE baz(a) @@ -249,19 +249,19 @@ mc = pddm.MacroCollection(f) test_list = [ # 1. Unknown macro - (u'bar()', + ('bar()', 'No macro named "bar".'), - (u'bar(a)', + ('bar(a)', 'No macro named "bar".'), # 3. Arg mismatch - (u'foo()', + ('foo()', 'Expected 2 args, got: "foo()".'), - (u'foo(a b)', + ('foo(a b)', 'Expected 2 args, got: "foo(a b)".'), - (u'foo(a,b,c)', + ('foo(a,b,c)', 'Expected 2 args, got: "foo(a,b,c)".'), # 6. Unknown option in expansion - (u'baz(mumble)', + ('baz(mumble)', 'Unknown arg option "a$z" while expanding "baz(mumble)".'), ] for idx, (input_str, expected_err) in enumerate(test_list, 1): @@ -273,7 +273,7 @@ 'Entry %d failed: %r' % (idx, e)) def testExpandReferences(self): - f = io.StringIO(u""" + f = io.StringIO(""" PDDM-DEFINE StartIt() foo(abc, def) foo(ghi, jkl) @@ -301,7 +301,7 @@ self.assertEqual(mc.Expand('StartIt()'), expected) def testCatchRecursion(self): - f = io.StringIO(u""" + f = io.StringIO(""" PDDM-DEFINE foo(a, b) bar(1, a) bar(2, b) @@ -322,29 +322,29 @@ def testBasicParse(self): test_list = [ # 1. no directives - (u'a\nb\nc', + ('a\nb\nc', (3,) ), # 2. One define - (u'a\n//%PDDM-DEFINE foo()\n//%body\nc', + ('a\n//%PDDM-DEFINE foo()\n//%body\nc', (1, 2, 1) ), # 3. Two defines - (u'a\n//%PDDM-DEFINE foo()\n//%body\n//%PDDM-DEFINE bar()\n//%body2\nc', + ('a\n//%PDDM-DEFINE foo()\n//%body\n//%PDDM-DEFINE bar()\n//%body2\nc', (1, 4, 1) ), # 4. Two defines with ends - (u'a\n//%PDDM-DEFINE foo()\n//%body\n//%PDDM-DEFINE-END\n' - u'//%PDDM-DEFINE bar()\n//%body2\n//%PDDM-DEFINE-END\nc', + ('a\n//%PDDM-DEFINE foo()\n//%body\n//%PDDM-DEFINE-END\n' + '//%PDDM-DEFINE bar()\n//%body2\n//%PDDM-DEFINE-END\nc', (1, 6, 1) ), # 5. One expand, one define (that runs to end of file) - (u'a\n//%PDDM-EXPAND foo()\nbody\n//%PDDM-EXPAND-END\n' - u'//%PDDM-DEFINE bar()\n//%body2\n', + ('a\n//%PDDM-EXPAND foo()\nbody\n//%PDDM-EXPAND-END\n' + '//%PDDM-DEFINE bar()\n//%body2\n', (1, 1, 2) ), # 6. One define ended with an expand. - (u'a\nb\n//%PDDM-DEFINE bar()\n//%body2\n' - u'//%PDDM-EXPAND bar()\nbody2\n//%PDDM-EXPAND-END\n', + ('a\nb\n//%PDDM-DEFINE bar()\n//%body2\n' + '//%PDDM-EXPAND bar()\nbody2\n//%PDDM-EXPAND-END\n', (2, 2, 1) ), # 7. Two expands (one end), one define. - (u'a\n//%PDDM-EXPAND foo(1)\nbody\n//%PDDM-EXPAND foo(2)\nbody2\n//%PDDM-EXPAND-END\n' - u'//%PDDM-DEFINE foo()\n//%body2\n', + ('a\n//%PDDM-EXPAND foo(1)\nbody\n//%PDDM-EXPAND foo(2)\nbody2\n//%PDDM-EXPAND-END\n' + '//%PDDM-DEFINE foo()\n//%body2\n', (1, 2, 2) ), ] for idx, (input_str, line_counts) in enumerate(test_list, 1): @@ -362,24 +362,24 @@ def testErrors(self): test_list = [ # 1. Directive within expansion - (u'//%PDDM-EXPAND a()\n//%PDDM-BOGUS', + ('//%PDDM-EXPAND a()\n//%PDDM-BOGUS', 'Ran into directive ("//%PDDM-BOGUS", line 2) while in "//%PDDM-EXPAND a()".'), - (u'//%PDDM-EXPAND a()\n//%PDDM-DEFINE a()\n//%body\n', + ('//%PDDM-EXPAND a()\n//%PDDM-DEFINE a()\n//%body\n', 'Ran into directive ("//%PDDM-DEFINE", line 2) while in "//%PDDM-EXPAND a()".'), # 3. Expansion ran off end of file - (u'//%PDDM-EXPAND a()\na\nb\n', + ('//%PDDM-EXPAND a()\na\nb\n', 'Hit the end of the file while in "//%PDDM-EXPAND a()".'), # 4. Directive within define - (u'//%PDDM-DEFINE a()\n//%body\n//%PDDM-BOGUS', + ('//%PDDM-DEFINE a()\n//%body\n//%PDDM-BOGUS', 'Ran into directive ("//%PDDM-BOGUS", line 3) while in "//%PDDM-DEFINE a()".'), - (u'//%PDDM-DEFINE a()\n//%body\n//%PDDM-EXPAND-END a()', + ('//%PDDM-DEFINE a()\n//%body\n//%PDDM-EXPAND-END a()', 'Ran into directive ("//%PDDM-EXPAND-END", line 3) while in "//%PDDM-DEFINE a()".'), # 6. Directives that shouldn't start sections - (u'a\n//%PDDM-DEFINE-END a()\n//a\n', + ('a\n//%PDDM-DEFINE-END a()\n//a\n', 'Unexpected line 2: "//%PDDM-DEFINE-END a()".'), - (u'a\n//%PDDM-EXPAND-END a()\n//a\n', + ('a\n//%PDDM-EXPAND-END a()\n//a\n', 'Unexpected line 2: "//%PDDM-EXPAND-END a()".'), - (u'//%PDDM-BOGUS\n//a\n', + ('//%PDDM-BOGUS\n//a\n', 'Unexpected line 1: "//%PDDM-BOGUS".'), ] for idx, (input_str, expected_err) in enumerate(test_list, 1): @@ -395,7 +395,7 @@ def testBasics(self): self.maxDiff = None - input_str = u""" + input_str = """ //%PDDM-IMPORT-DEFINES ImportFile foo //%PDDM-EXPAND mumble(abc) @@ -408,12 +408,12 @@ //%PDDM-DEFINE mumble(a_) //%a_: getName(a_) """ - input_str2 = u""" + input_str2 = """ //%PDDM-DEFINE getName(x_) //%do##x_$u##(int x_); """ - expected = u""" + expected = """ //%PDDM-IMPORT-DEFINES ImportFile foo //%PDDM-EXPAND mumble(abc) @@ -441,7 +441,7 @@ //%PDDM-DEFINE mumble(a_) //%a_: getName(a_) """ - expected_stripped = u""" + expected_stripped = """ //%PDDM-IMPORT-DEFINES ImportFile foo //%PDDM-EXPAND mumble(abc) @@ -478,7 +478,7 @@ self.assertEqual(sf2.processed_content, expected_stripped) def testProcessFileWithMacroParseError(self): - input_str = u""" + input_str = """ foo //%PDDM-DEFINE mumble(a_) //%body @@ -498,7 +498,7 @@ ' Line 3: //%PDDM-DEFINE mumble(a_)') def testProcessFileWithExpandError(self): - input_str = u""" + input_str = """ foo //%PDDM-DEFINE mumble(a_) //%body
diff --git a/objectivec/GPBCodedInputStream.m b/objectivec/GPBCodedInputStream.m index 1864d91..c459391 100644 --- a/objectivec/GPBCodedInputStream.m +++ b/objectivec/GPBCodedInputStream.m
@@ -46,9 +46,9 @@ GPBNSStringifySymbol(GPBCodedInputStreamErrorDomain); // Matching: -// https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/CodedInputStream.java#L62 +// https://github.com/protocolbuffers/protobuf/blob/main/java/core/src/main/java/com/google/protobuf/CodedInputStream.java#L62 // private static final int DEFAULT_RECURSION_LIMIT = 100; -// https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/io/coded_stream.cc#L86 +// https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/io/coded_stream.cc#L86 // int CodedInputStream::default_recursion_limit_ = 100; static const NSUInteger kDefaultRecursionLimit = 100;
diff --git a/objectivec/GPBEmpty.pbobjc.h b/objectivec/GPBEmpty.pbobjc.h index 8a31c04..5878223 100644 --- a/objectivec/GPBEmpty.pbobjc.h +++ b/objectivec/GPBEmpty.pbobjc.h
@@ -46,8 +46,6 @@ * 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
diff --git a/php/ext/google/protobuf/def.c b/php/ext/google/protobuf/def.c index 9210026..dfb96f2 100644 --- a/php/ext/google/protobuf/def.c +++ b/php/ext/google/protobuf/def.c
@@ -732,20 +732,16 @@ } upb_DefPool *DescriptorPool_GetSymbolTable() { - DescriptorPool *intern = GetPool(get_generated_pool()); - return intern->symtab; + return get_global_symtab(); } - /* * DescriptorPool::getGeneratedPool() * * Returns the generated DescriptorPool. */ PHP_METHOD(DescriptorPool, getGeneratedPool) { - zval ret; - ZVAL_COPY(&ret, get_generated_pool()); - RETURN_COPY_VALUE(&ret); + DescriptorPool_CreateWithSymbolTable(return_value, get_global_symtab()); } /* @@ -880,14 +876,14 @@ } } -static void add_descriptor(DescriptorPool *pool, +static void add_descriptor(upb_DefPool *symtab, const google_protobuf_FileDescriptorProto *file) { upb_StringView name = google_protobuf_FileDescriptorProto_name(file); upb_Status status; const upb_FileDef *file_def; upb_Status_Clear(&status); - if (upb_DefPool_FindFileByNameWithSize(pool->symtab, name.data, name.size)) { + if (upb_DefPool_FindFileByNameWithSize(symtab, name.data, name.size)) { // Already added. // TODO(teboring): Re-enable this warning when aggregate metadata is // deprecated. @@ -902,10 +898,10 @@ // doesn't add it as a dependency even if the proto file actually does // depend on it. if (depends_on_descriptor(file)) { - google_protobuf_FileDescriptorProto_getmsgdef(pool->symtab); + google_protobuf_FileDescriptorProto_getmsgdef(symtab); } - file_def = upb_DefPool_AddFile(pool->symtab, file, &status); + file_def = upb_DefPool_AddFile(symtab, file, &status); CheckUpbStatus(&status, "Unable to load descriptor"); add_name_mappings(file_def); } @@ -915,7 +911,7 @@ * * Adds the given descriptor data to this DescriptorPool. */ -static void add_descriptor_set(DescriptorPool *pool, const char *data, +static void add_descriptor_set(upb_DefPool *symtab, const char *data, int data_len, upb_Arena *arena) { size_t i, n; google_protobuf_FileDescriptorSet *set; @@ -932,13 +928,12 @@ for (i = 0; i < n; i++) { const google_protobuf_FileDescriptorProto* file = files[i]; - add_descriptor(pool, file); + add_descriptor(symtab, file); } } bool DescriptorPool_HasFile(const char *filename) { - DescriptorPool *intern = GetPool(get_generated_pool()); - return upb_DefPool_FindFileByName(intern->symtab, filename) != NULL; + return upb_DefPool_FindFileByName(get_global_symtab(), filename) != NULL; } void DescriptorPool_AddDescriptor(const char *filename, const char *data, @@ -952,7 +947,7 @@ return; } - add_descriptor(GetPool(get_generated_pool()), file); + add_descriptor(get_global_symtab(), file); upb_Arena_Free(arena); } @@ -974,7 +969,7 @@ } arena = upb_Arena_New(); - add_descriptor_set(intern, data, data_len, arena); + add_descriptor_set(intern->symtab, data, data_len, arena); upb_Arena_Free(arena); } @@ -1015,7 +1010,7 @@ * instance. */ PHP_METHOD(InternalDescriptorPool, getGeneratedPool) { - RETURN_COPY(get_generated_pool()); + DescriptorPool_CreateWithSymbolTable(return_value, get_global_symtab()); } static zend_function_entry InternalDescriptorPool_methods[] = {
diff --git a/php/ext/google/protobuf/names.c b/php/ext/google/protobuf/names.c index 5d7b68a..a298881 100644 --- a/php/ext/google/protobuf/names.c +++ b/php/ext/google/protobuf/names.c
@@ -82,12 +82,12 @@ "global", "goto", "insteadof", "interface", "isset", "list", "match", "namespace", "new", "object", "or", "parent", "print", "private", "protected", - "public", "require", "require_once", "return", "self", - "static", "switch", "throw", "trait", "try", - "unset", "use", "var", "while", "xor", - "yield", "int", "float", "bool", "string", - "true", "false", "null", "void", "iterable", - NULL}; + "public", "readonly", "require", "require_once", "return", + "self", "static", "switch", "throw", "trait", + "try", "unset", "use", "var", "while", + "xor", "yield", "int", "float", "bool", + "string", "true", "false", "null", "void", + "iterable", NULL}; bool is_reserved_name(const char* name) { int i;
diff --git a/php/ext/google/protobuf/package.xml b/php/ext/google/protobuf/package.xml index e640bf9..0acb23c 100644 --- a/php/ext/google/protobuf/package.xml +++ b/php/ext/google/protobuf/package.xml
@@ -17,8 +17,8 @@ <api>3.20.1</api> </version> <stability> - <release>stable</release> - <api>stable</api> + <release>beta</release> + <api>beta</api> </stability> <license uri="https://opensource.org/licenses/BSD-3-Clause">BSD-3-Clause</license> <notes>
diff --git a/php/ext/google/protobuf/php_protobuf.h b/php/ext/google/protobuf/php_protobuf.h new file mode 100644 index 0000000..59a6610 --- /dev/null +++ b/php/ext/google/protobuf/php_protobuf.h
@@ -0,0 +1,45 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2022 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// ! THIS FILE ONLY APPROACHING IN-TREE PHP EXTENSION BUILD ! +// ! DOES NOT USE NORMALLY. ! +// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +#ifndef PHP_PROTOBUF_H +# define PHP_PROTOBUF_H + +# ifdef HAVE_CONFIG_H +# include "config.h" +# endif + +extern zend_module_entry protobuf_module_entry; +# define phpext_protobuf_ptr &protobuf_module_entry + +#endif /* PHP_PROTOBUF_H */
diff --git a/php/ext/google/protobuf/protobuf.c b/php/ext/google/protobuf/protobuf.c index 6f8a534..68c0ef0 100644 --- a/php/ext/google/protobuf/protobuf.c +++ b/php/ext/google/protobuf/protobuf.c
@@ -56,12 +56,6 @@ // Set by the user to make the descriptor pool persist between requests. zend_bool keep_descriptor_pool_after_request; - // Currently we make the generated pool a "global", which means that if a user - // does explicitly create threads within their request, the other threads will - // get different results from DescriptorPool::getGeneratedPool(). We require - // that all descriptors are loaded from the main thread. - zval generated_pool; - // A upb_DefPool that we are saving for the next request so that we don't have // to rebuild it from scratch. When keep_descriptor_pool_after_request==true, // we steal the upb_DefPool from the global DescriptorPool object just before @@ -91,8 +85,8 @@ ZEND_DECLARE_MODULE_GLOBALS(protobuf) -const zval *get_generated_pool() { - return &PROTOBUF_G(generated_pool); +upb_DefPool *get_global_symtab() { + return PROTOBUF_G(global_symtab); } // This is a PHP extension (not a Zend extension). What follows is a summary of @@ -159,7 +153,6 @@ } static PHP_GINIT_FUNCTION(protobuf) { - ZVAL_NULL(&protobuf_globals->generated_pool); protobuf_globals->global_symtab = NULL; } @@ -177,7 +170,6 @@ zend_hash_init(&PROTOBUF_G(name_msg_cache), 64, NULL, NULL, 0); zend_hash_init(&PROTOBUF_G(name_enum_cache), 64, NULL, NULL, 0); } - DescriptorPool_CreateWithSymbolTable(&PROTOBUF_G(generated_pool), symtab); zend_hash_init(&PROTOBUF_G(object_cache), 64, NULL, NULL, 0); zend_hash_init(&PROTOBUF_G(descriptors), 64, NULL, ZVAL_PTR_DTOR, 0); @@ -196,7 +188,6 @@ free_protobuf_globals(ZEND_MODULE_GLOBALS_BULK(protobuf)); } - zval_dtor(&PROTOBUF_G(generated_pool)); zend_hash_destroy(&PROTOBUF_G(object_cache)); zend_hash_destroy(&PROTOBUF_G(descriptors));
diff --git a/php/ext/google/protobuf/protobuf.h b/php/ext/google/protobuf/protobuf.h index 169a68a..97adedb 100644 --- a/php/ext/google/protobuf/protobuf.h +++ b/php/ext/google/protobuf/protobuf.h
@@ -36,7 +36,7 @@ #include "php-upb.h" -const zval *get_generated_pool(); +upb_DefPool *get_global_symtab(); #if PHP_VERSION_ID < 70300 #define GC_ADDREF(h) ++GC_REFCOUNT(h)
diff --git a/php/ext/google/protobuf/tests/unnecessary_zval.phpt b/php/ext/google/protobuf/tests/unnecessary_zval.phpt new file mode 100644 index 0000000..9a169ab --- /dev/null +++ b/php/ext/google/protobuf/tests/unnecessary_zval.phpt
@@ -0,0 +1,9 @@ +--TEST-- +unnecessary zval +--FILE-- +<?php +var_dump(new \stdClass()); +?> +--EXPECT-- +object(stdClass)#1 (0) { +}
diff --git a/php/src/Google/Protobuf/Api.php b/php/src/Google/Protobuf/Api.php index e7d76c0..3784263 100644 --- a/php/src/Google/Protobuf/Api.php +++ b/php/src/Google/Protobuf/Api.php
@@ -92,9 +92,9 @@ * @type string $name * The fully qualified name of this interface, including package name * followed by the interface's simple name. - * @type \Google\Protobuf\Method[]|\Google\Protobuf\Internal\RepeatedField $methods + * @type array<\Google\Protobuf\Method>|\Google\Protobuf\Internal\RepeatedField $methods * The methods of this interface, in unspecified order. - * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options + * @type array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $options * Any metadata attached to the interface. * @type string $version * A version string for this interface. If specified, must have the form @@ -117,7 +117,7 @@ * @type \Google\Protobuf\SourceContext $source_context * Source context for the protocol buffer service represented by this * message. - * @type \Google\Protobuf\Mixin[]|\Google\Protobuf\Internal\RepeatedField $mixins + * @type array<\Google\Protobuf\Mixin>|\Google\Protobuf\Internal\RepeatedField $mixins * Included interfaces. See [Mixin][]. * @type int $syntax * The source syntax of the service. @@ -171,7 +171,7 @@ * The methods of this interface, in unspecified order. * * Generated from protobuf field <code>repeated .google.protobuf.Method methods = 2;</code> - * @param \Google\Protobuf\Method[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Method>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setMethods($var) @@ -197,7 +197,7 @@ * Any metadata attached to the interface. * * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code> - * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setOptions($var) @@ -319,7 +319,7 @@ * Included interfaces. See [Mixin][]. * * Generated from protobuf field <code>repeated .google.protobuf.Mixin mixins = 6;</code> - * @param \Google\Protobuf\Mixin[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Mixin>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setMixins($var)
diff --git a/php/src/Google/Protobuf/Enum.php b/php/src/Google/Protobuf/Enum.php index e803e93..185e54e 100644 --- a/php/src/Google/Protobuf/Enum.php +++ b/php/src/Google/Protobuf/Enum.php
@@ -54,9 +54,9 @@ * * @type string $name * Enum type name. - * @type \Google\Protobuf\EnumValue[]|\Google\Protobuf\Internal\RepeatedField $enumvalue + * @type array<\Google\Protobuf\EnumValue>|\Google\Protobuf\Internal\RepeatedField $enumvalue * Enum value definitions. - * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options + * @type array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $options * Protocol buffer options. * @type \Google\Protobuf\SourceContext $source_context * The source context. @@ -110,7 +110,7 @@ * Enum value definitions. * * Generated from protobuf field <code>repeated .google.protobuf.EnumValue enumvalue = 2;</code> - * @param \Google\Protobuf\EnumValue[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\EnumValue>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setEnumvalue($var) @@ -136,7 +136,7 @@ * Protocol buffer options. * * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code> - * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setOptions($var)
diff --git a/php/src/Google/Protobuf/EnumValue.php b/php/src/Google/Protobuf/EnumValue.php index 905f4ad..93c20f9 100644 --- a/php/src/Google/Protobuf/EnumValue.php +++ b/php/src/Google/Protobuf/EnumValue.php
@@ -44,7 +44,7 @@ * Enum value name. * @type int $number * Enum value number. - * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options + * @type array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $options * Protocol buffer options. * } */ @@ -120,7 +120,7 @@ * Protocol buffer options. * * Generated from protobuf field <code>repeated .google.protobuf.Option options = 3;</code> - * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setOptions($var)
diff --git a/php/src/Google/Protobuf/Field.php b/php/src/Google/Protobuf/Field.php index 76a505e..ddae570 100644 --- a/php/src/Google/Protobuf/Field.php +++ b/php/src/Google/Protobuf/Field.php
@@ -100,7 +100,7 @@ * types. The first type has index 1; zero means the type is not in the list. * @type bool $packed * Whether to use alternative packed wire representation. - * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options + * @type array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $options * The protocol buffer options. * @type string $json_name * The field JSON name. @@ -314,7 +314,7 @@ * The protocol buffer options. * * Generated from protobuf field <code>repeated .google.protobuf.Option options = 9;</code> - * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setOptions($var)
diff --git a/php/src/Google/Protobuf/FieldMask.php b/php/src/Google/Protobuf/FieldMask.php index 0b9659d..a8e5243 100644 --- a/php/src/Google/Protobuf/FieldMask.php +++ b/php/src/Google/Protobuf/FieldMask.php
@@ -178,7 +178,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type string[]|\Google\Protobuf\Internal\RepeatedField $paths + * @type array<string>|\Google\Protobuf\Internal\RepeatedField $paths * The set of field mask paths. * } */ @@ -202,7 +202,7 @@ * The set of field mask paths. * * Generated from protobuf field <code>repeated string paths = 1;</code> - * @param string[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<string>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setPaths($var)
diff --git a/php/src/Google/Protobuf/GPBEmpty.php b/php/src/Google/Protobuf/GPBEmpty.php index 2de9c3b..4db6923 100644 --- a/php/src/Google/Protobuf/GPBEmpty.php +++ b/php/src/Google/Protobuf/GPBEmpty.php
@@ -15,7 +15,6 @@ * service Foo { * rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); * } - * The JSON representation for `Empty` is empty JSON object `{}`. * * Generated from protobuf message <code>google.protobuf.Empty</code> */
diff --git a/php/src/Google/Protobuf/Internal/DescriptorProto.php b/php/src/Google/Protobuf/Internal/DescriptorProto.php index c58c573..2937c5a 100644 --- a/php/src/Google/Protobuf/Internal/DescriptorProto.php +++ b/php/src/Google/Protobuf/Internal/DescriptorProto.php
@@ -68,15 +68,15 @@ * Optional. Data for populating the Message object. * * @type string $name - * @type \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $field - * @type \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $extension - * @type \Google\Protobuf\Internal\DescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $nested_type - * @type \Google\Protobuf\Internal\EnumDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $enum_type - * @type \Google\Protobuf\Internal\DescriptorProto\ExtensionRange[]|\Google\Protobuf\Internal\RepeatedField $extension_range - * @type \Google\Protobuf\Internal\OneofDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $oneof_decl + * @type array<\Google\Protobuf\Internal\FieldDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $field + * @type array<\Google\Protobuf\Internal\FieldDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $extension + * @type array<\Google\Protobuf\Internal\DescriptorProto>|\Google\Protobuf\Internal\RepeatedField $nested_type + * @type array<\Google\Protobuf\Internal\EnumDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $enum_type + * @type array<\Google\Protobuf\Internal\DescriptorProto\ExtensionRange>|\Google\Protobuf\Internal\RepeatedField $extension_range + * @type array<\Google\Protobuf\Internal\OneofDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $oneof_decl * @type \Google\Protobuf\Internal\MessageOptions $options - * @type \Google\Protobuf\Internal\DescriptorProto\ReservedRange[]|\Google\Protobuf\Internal\RepeatedField $reserved_range - * @type string[]|\Google\Protobuf\Internal\RepeatedField $reserved_name + * @type array<\Google\Protobuf\Internal\DescriptorProto\ReservedRange>|\Google\Protobuf\Internal\RepeatedField $reserved_range + * @type array<string>|\Google\Protobuf\Internal\RepeatedField $reserved_name * Reserved field names, which may not be used by fields in the same message. * A given name may only be reserved once. * } @@ -129,7 +129,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto field = 2;</code> - * @param \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\FieldDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setField($var) @@ -151,7 +151,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto extension = 6;</code> - * @param \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\FieldDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setExtension($var) @@ -173,7 +173,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto nested_type = 3;</code> - * @param \Google\Protobuf\Internal\DescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\DescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setNestedType($var) @@ -195,7 +195,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 4;</code> - * @param \Google\Protobuf\Internal\EnumDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\EnumDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setEnumType($var) @@ -217,7 +217,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;</code> - * @param \Google\Protobuf\Internal\DescriptorProto\ExtensionRange[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\DescriptorProto\ExtensionRange>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setExtensionRange($var) @@ -239,7 +239,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8;</code> - * @param \Google\Protobuf\Internal\OneofDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\OneofDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setOneofDecl($var) @@ -293,7 +293,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;</code> - * @param \Google\Protobuf\Internal\DescriptorProto\ReservedRange[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\DescriptorProto\ReservedRange>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setReservedRange($var) @@ -321,7 +321,7 @@ * A given name may only be reserved once. * * Generated from protobuf field <code>repeated string reserved_name = 10;</code> - * @param string[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<string>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setReservedName($var)
diff --git a/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php b/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php index bd50834..cb2a42a 100644 --- a/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php +++ b/php/src/Google/Protobuf/Internal/EnumDescriptorProto.php
@@ -52,13 +52,13 @@ * Optional. Data for populating the Message object. * * @type string $name - * @type \Google\Protobuf\Internal\EnumValueDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $value + * @type array<\Google\Protobuf\Internal\EnumValueDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $value * @type \Google\Protobuf\Internal\EnumOptions $options - * @type \Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange[]|\Google\Protobuf\Internal\RepeatedField $reserved_range + * @type array<\Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange>|\Google\Protobuf\Internal\RepeatedField $reserved_range * Range of reserved numeric values. Reserved numeric values may not be used * by enum values in the same enum declaration. Reserved ranges may not * overlap. - * @type string[]|\Google\Protobuf\Internal\RepeatedField $reserved_name + * @type array<string>|\Google\Protobuf\Internal\RepeatedField $reserved_name * Reserved enum value names, which may not be reused. A given name may only * be reserved once. * } @@ -111,7 +111,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.EnumValueDescriptorProto value = 2;</code> - * @param \Google\Protobuf\Internal\EnumValueDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\EnumValueDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setValue($var) @@ -173,7 +173,7 @@ * overlap. * * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;</code> - * @param \Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\EnumDescriptorProto\EnumReservedRange>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setReservedRange($var) @@ -201,7 +201,7 @@ * be reserved once. * * Generated from protobuf field <code>repeated string reserved_name = 5;</code> - * @param string[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<string>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setReservedName($var)
diff --git a/php/src/Google/Protobuf/Internal/EnumOptions.php b/php/src/Google/Protobuf/Internal/EnumOptions.php index 7a69676..838bc84 100644 --- a/php/src/Google/Protobuf/Internal/EnumOptions.php +++ b/php/src/Google/Protobuf/Internal/EnumOptions.php
@@ -52,7 +52,7 @@ * Depending on the target platform, this can emit Deprecated annotations * for the enum, or it will be completely ignored; in the very least, this * is a formalization for deprecating enums. - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. See above. * } */ @@ -156,7 +156,7 @@ * The parser stores options it doesn't recognize here. See above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/EnumValueOptions.php b/php/src/Google/Protobuf/Internal/EnumValueOptions.php index 84ba7bc..2db7fce 100644 --- a/php/src/Google/Protobuf/Internal/EnumValueOptions.php +++ b/php/src/Google/Protobuf/Internal/EnumValueOptions.php
@@ -42,7 +42,7 @@ * Depending on the target platform, this can emit Deprecated annotations * for the enum value, or it will be completely ignored; in the very least, * this is a formalization for deprecating enum values. - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. See above. * } */ @@ -108,7 +108,7 @@ * The parser stores options it doesn't recognize here. See above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php b/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php index b5e27c3..245173c 100644 --- a/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php +++ b/php/src/Google/Protobuf/Internal/ExtensionRangeOptions.php
@@ -28,7 +28,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. See above. * } */ @@ -52,7 +52,7 @@ * The parser stores options it doesn't recognize here. See above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/FieldOptions.php b/php/src/Google/Protobuf/Internal/FieldOptions.php index 5fe7a19..665cb06 100644 --- a/php/src/Google/Protobuf/Internal/FieldOptions.php +++ b/php/src/Google/Protobuf/Internal/FieldOptions.php
@@ -180,7 +180,7 @@ * is a formalization for deprecating fields. * @type bool $weak * For Google-internal migration only. Do not use. - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. See above. * } */ @@ -552,7 +552,7 @@ * The parser stores options it doesn't recognize here. See above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/FileDescriptorProto.php b/php/src/Google/Protobuf/Internal/FileDescriptorProto.php index 435bd5f..5ba7db6 100644 --- a/php/src/Google/Protobuf/Internal/FileDescriptorProto.php +++ b/php/src/Google/Protobuf/Internal/FileDescriptorProto.php
@@ -97,18 +97,18 @@ * file name, relative to root of source tree * @type string $package * e.g. "foo", "foo.bar", etc. - * @type string[]|\Google\Protobuf\Internal\RepeatedField $dependency + * @type array<string>|\Google\Protobuf\Internal\RepeatedField $dependency * Names of files imported by this file. - * @type int[]|\Google\Protobuf\Internal\RepeatedField $public_dependency + * @type array<int>|\Google\Protobuf\Internal\RepeatedField $public_dependency * Indexes of the public imported files in the dependency list above. - * @type int[]|\Google\Protobuf\Internal\RepeatedField $weak_dependency + * @type array<int>|\Google\Protobuf\Internal\RepeatedField $weak_dependency * Indexes of the weak imported files in the dependency list. * For Google-internal migration only. Do not use. - * @type \Google\Protobuf\Internal\DescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $message_type + * @type array<\Google\Protobuf\Internal\DescriptorProto>|\Google\Protobuf\Internal\RepeatedField $message_type * All top-level definitions in this file. - * @type \Google\Protobuf\Internal\EnumDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $enum_type - * @type \Google\Protobuf\Internal\ServiceDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $service - * @type \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $extension + * @type array<\Google\Protobuf\Internal\EnumDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $enum_type + * @type array<\Google\Protobuf\Internal\ServiceDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $service + * @type array<\Google\Protobuf\Internal\FieldDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $extension * @type \Google\Protobuf\Internal\FileOptions $options * @type \Google\Protobuf\Internal\SourceCodeInfo $source_code_info * This field contains optional information about the original source code. @@ -212,7 +212,7 @@ * Names of files imported by this file. * * Generated from protobuf field <code>repeated string dependency = 3;</code> - * @param string[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<string>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setDependency($var) @@ -238,7 +238,7 @@ * Indexes of the public imported files in the dependency list above. * * Generated from protobuf field <code>repeated int32 public_dependency = 10;</code> - * @param int[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<int>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setPublicDependency($var) @@ -266,7 +266,7 @@ * For Google-internal migration only. Do not use. * * Generated from protobuf field <code>repeated int32 weak_dependency = 11;</code> - * @param int[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<int>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setWeakDependency($var) @@ -292,7 +292,7 @@ * All top-level definitions in this file. * * Generated from protobuf field <code>repeated .google.protobuf.DescriptorProto message_type = 4;</code> - * @param \Google\Protobuf\Internal\DescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\DescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setMessageType($var) @@ -314,7 +314,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.EnumDescriptorProto enum_type = 5;</code> - * @param \Google\Protobuf\Internal\EnumDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\EnumDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setEnumType($var) @@ -336,7 +336,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.ServiceDescriptorProto service = 6;</code> - * @param \Google\Protobuf\Internal\ServiceDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\ServiceDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setService($var) @@ -358,7 +358,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.FieldDescriptorProto extension = 7;</code> - * @param \Google\Protobuf\Internal\FieldDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\FieldDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setExtension($var)
diff --git a/php/src/Google/Protobuf/Internal/FileDescriptorSet.php b/php/src/Google/Protobuf/Internal/FileDescriptorSet.php index 794e634..1dae6fb 100644 --- a/php/src/Google/Protobuf/Internal/FileDescriptorSet.php +++ b/php/src/Google/Protobuf/Internal/FileDescriptorSet.php
@@ -29,7 +29,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type \Google\Protobuf\Internal\FileDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $file + * @type array<\Google\Protobuf\Internal\FileDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $file * } */ public function __construct($data = NULL) { @@ -48,7 +48,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.FileDescriptorProto file = 1;</code> - * @param \Google\Protobuf\Internal\FileDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\FileDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setFile($var)
diff --git a/php/src/Google/Protobuf/Internal/FileOptions.php b/php/src/Google/Protobuf/Internal/FileOptions.php index 3f2c3a4..43931be 100644 --- a/php/src/Google/Protobuf/Internal/FileOptions.php +++ b/php/src/Google/Protobuf/Internal/FileOptions.php
@@ -266,7 +266,7 @@ * Use this option to change the package of ruby generated classes. Default * is empty. When this option is not set, the package name will be used for * determining the ruby package. - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. * See the documentation for the "Options" section above. * } @@ -1091,7 +1091,7 @@ * See the documentation for the "Options" section above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/GPBUtil.php b/php/src/Google/Protobuf/Internal/GPBUtil.php index 4b15283..d7f2faa 100644 --- a/php/src/Google/Protobuf/Internal/GPBUtil.php +++ b/php/src/Google/Protobuf/Internal/GPBUtil.php
@@ -285,11 +285,12 @@ "include"=>0, "include_once"=>0, "instanceof"=>0, "insteadof"=>0, "interface"=>0, "isset"=>0, "list"=>0, "match"=>0, "namespace"=>0, "new"=>0, "or"=>0, "parent"=>0, "print"=>0, "private"=>0, - "protected"=>0,"public"=>0, "require"=>0, "require_once"=>0, - "return"=>0, "self"=>0, "static"=>0, "switch"=>0, "throw"=>0, - "trait"=>0, "try"=>0,"unset"=>0, "use"=>0, "var"=>0, "while"=>0, - "xor"=>0, "yield"=>0, "int"=>0, "float"=>0, "bool"=>0, "string"=>0, - "true"=>0, "false"=>0, "null"=>0, "void"=>0, "iterable"=>0 + "protected"=>0,"public"=>0, "readonly" => 0,"require"=>0, + "require_once"=>0,"return"=>0, "self"=>0, "static"=>0, "switch"=>0, + "throw"=>0,"trait"=>0, "try"=>0,"unset"=>0, "use"=>0, "var"=>0, + "while"=>0,"xor"=>0, "yield"=>0, "int"=>0, "float"=>0, "bool"=>0, + "string"=>0,"true"=>0, "false"=>0, "null"=>0, "void"=>0, + "iterable"=>0 ); if (array_key_exists(strtolower($classname), $reserved_words)) {
diff --git a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php index c261ed6..a1db269 100644 --- a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php +++ b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo.php
@@ -33,7 +33,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type \Google\Protobuf\Internal\GeneratedCodeInfo\Annotation[]|\Google\Protobuf\Internal\RepeatedField $annotation + * @type array<\Google\Protobuf\Internal\GeneratedCodeInfo\Annotation>|\Google\Protobuf\Internal\RepeatedField $annotation * An Annotation connects some span of text in generated code to an element * of its generating .proto file. * } @@ -60,7 +60,7 @@ * of its generating .proto file. * * Generated from protobuf field <code>repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;</code> - * @param \Google\Protobuf\Internal\GeneratedCodeInfo\Annotation[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\GeneratedCodeInfo\Annotation>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setAnnotation($var)
diff --git a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo/Annotation.php b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo/Annotation.php index 0b043d0..617fdac 100644 --- a/php/src/Google/Protobuf/Internal/GeneratedCodeInfo/Annotation.php +++ b/php/src/Google/Protobuf/Internal/GeneratedCodeInfo/Annotation.php
@@ -50,7 +50,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type int[]|\Google\Protobuf\Internal\RepeatedField $path + * @type array<int>|\Google\Protobuf\Internal\RepeatedField $path * Identifies the element in the original source .proto file. This field * is formatted the same as SourceCodeInfo.Location.path. * @type string $source_file @@ -86,7 +86,7 @@ * is formatted the same as SourceCodeInfo.Location.path. * * Generated from protobuf field <code>repeated int32 path = 1 [packed = true];</code> - * @param int[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<int>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setPath($var)
diff --git a/php/src/Google/Protobuf/Internal/MessageOptions.php b/php/src/Google/Protobuf/Internal/MessageOptions.php index 2f4e3cb..5c61580 100644 --- a/php/src/Google/Protobuf/Internal/MessageOptions.php +++ b/php/src/Google/Protobuf/Internal/MessageOptions.php
@@ -132,7 +132,7 @@ * NOTE: Do not set the option in .proto files. Always use the maps syntax * instead. The option should only be implicitly set by the proto compiler * parser. - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. See above. * } */ @@ -372,7 +372,7 @@ * The parser stores options it doesn't recognize here. See above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/MethodOptions.php b/php/src/Google/Protobuf/Internal/MethodOptions.php index a4595b7..87af451 100644 --- a/php/src/Google/Protobuf/Internal/MethodOptions.php +++ b/php/src/Google/Protobuf/Internal/MethodOptions.php
@@ -47,7 +47,7 @@ * for the method, or it will be completely ignored; in the very least, * this is a formalization for deprecating methods. * @type int $idempotency_level - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. See above. * } */ @@ -145,7 +145,7 @@ * The parser stores options it doesn't recognize here. See above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/OneofOptions.php b/php/src/Google/Protobuf/Internal/OneofOptions.php index 8dde8f3..b44d194 100644 --- a/php/src/Google/Protobuf/Internal/OneofOptions.php +++ b/php/src/Google/Protobuf/Internal/OneofOptions.php
@@ -28,7 +28,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. See above. * } */ @@ -52,7 +52,7 @@ * The parser stores options it doesn't recognize here. See above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/RepeatedField.php b/php/src/Google/Protobuf/Internal/RepeatedField.php index cfe5140..ea7971f 100644 --- a/php/src/Google/Protobuf/Internal/RepeatedField.php +++ b/php/src/Google/Protobuf/Internal/RepeatedField.php
@@ -118,7 +118,7 @@ * This will also be called for: $ele = $arr[0] * * @param integer $offset The index of the element to be fetched. - * @return object The stored element at given index. + * @return mixed The stored element at given index. * @throws \ErrorException Invalid type for index. * @throws \ErrorException Non-existing index. * @todo need to add return type mixed (require update php version to 8.0) @@ -134,8 +134,8 @@ * * This will also be called for: $arr []= $ele and $arr[0] = ele * - * @param integer $offset The index of the element to be assigned. - * @param object $value The element to be assigned. + * @param int|null $offset The index of the element to be assigned. + * @param mixed $value The element to be assigned. * @return void * @throws \ErrorException Invalid type for index. * @throws \ErrorException Non-existing index.
diff --git a/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php b/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php index c511247..e322e2a 100644 --- a/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php +++ b/php/src/Google/Protobuf/Internal/ServiceDescriptorProto.php
@@ -37,7 +37,7 @@ * Optional. Data for populating the Message object. * * @type string $name - * @type \Google\Protobuf\Internal\MethodDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $method + * @type array<\Google\Protobuf\Internal\MethodDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $method * @type \Google\Protobuf\Internal\ServiceOptions $options * } */ @@ -89,7 +89,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.MethodDescriptorProto method = 2;</code> - * @param \Google\Protobuf\Internal\MethodDescriptorProto[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\MethodDescriptorProto>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setMethod($var)
diff --git a/php/src/Google/Protobuf/Internal/ServiceOptions.php b/php/src/Google/Protobuf/Internal/ServiceOptions.php index d15a36a..8ac27ee 100644 --- a/php/src/Google/Protobuf/Internal/ServiceOptions.php +++ b/php/src/Google/Protobuf/Internal/ServiceOptions.php
@@ -42,7 +42,7 @@ * Depending on the target platform, this can emit Deprecated annotations * for the service, or it will be completely ignored; in the very least, * this is a formalization for deprecating services. - * @type \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option + * @type array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $uninterpreted_option * The parser stores options it doesn't recognize here. See above. * } */ @@ -108,7 +108,7 @@ * The parser stores options it doesn't recognize here. See above. * * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setUninterpretedOption($var)
diff --git a/php/src/Google/Protobuf/Internal/SourceCodeInfo.php b/php/src/Google/Protobuf/Internal/SourceCodeInfo.php index 1c572e7..0005bc6 100644 --- a/php/src/Google/Protobuf/Internal/SourceCodeInfo.php +++ b/php/src/Google/Protobuf/Internal/SourceCodeInfo.php
@@ -71,7 +71,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type \Google\Protobuf\Internal\SourceCodeInfo\Location[]|\Google\Protobuf\Internal\RepeatedField $location + * @type array<\Google\Protobuf\Internal\SourceCodeInfo\Location>|\Google\Protobuf\Internal\RepeatedField $location * A Location identifies a piece of source code in a .proto file which * corresponds to a particular definition. This information is intended * to be useful to IDEs, code indexers, documentation generators, and similar @@ -215,7 +215,7 @@ * be recorded in the future. * * Generated from protobuf field <code>repeated .google.protobuf.SourceCodeInfo.Location location = 1;</code> - * @param \Google\Protobuf\Internal\SourceCodeInfo\Location[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\SourceCodeInfo\Location>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setLocation($var)
diff --git a/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php b/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php index a3e8e72..032be39 100644 --- a/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php +++ b/php/src/Google/Protobuf/Internal/SourceCodeInfo/Location.php
@@ -72,12 +72,12 @@ * optional string baz = 3; * // Comment attached to baz. * // Another line attached to baz. - * // Comment attached to qux. + * // Comment attached to moo. * // - * // Another line attached to qux. - * optional double qux = 4; + * // Another line attached to moo. + * optional double moo = 4; * // Detached comment for corge. This is not leading or trailing comments - * // to qux or corge because there are blank lines separating it from + * // to moo or corge because there are blank lines separating it from * // both. * // Detached comment for corge paragraph 2. * optional string corge = 5; @@ -107,7 +107,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type int[]|\Google\Protobuf\Internal\RepeatedField $path + * @type array<int>|\Google\Protobuf\Internal\RepeatedField $path * Identifies which part of the FileDescriptorProto was defined at this * location. * Each element is a field number or an index. They form a path from @@ -129,7 +129,7 @@ * [ 4, 3, 2, 7 ] * this path refers to the whole field declaration (from the beginning * of the label to the terminating semicolon). - * @type int[]|\Google\Protobuf\Internal\RepeatedField $span + * @type array<int>|\Google\Protobuf\Internal\RepeatedField $span * Always has exactly three or four elements: start line, start column, * end line (optional, otherwise assumed same as start line), end column. * These are packed into a single field for efficiency. Note that line @@ -156,12 +156,12 @@ * optional string baz = 3; * // Comment attached to baz. * // Another line attached to baz. - * // Comment attached to qux. + * // Comment attached to moo. * // - * // Another line attached to qux. - * optional double qux = 4; + * // Another line attached to moo. + * optional double moo = 4; * // Detached comment for corge. This is not leading or trailing comments - * // to qux or corge because there are blank lines separating it from + * // to moo or corge because there are blank lines separating it from * // both. * // Detached comment for corge paragraph 2. * optional string corge = 5; @@ -173,7 +173,7 @@ * optional int32 grault = 6; * // ignored detached comments. * @type string $trailing_comments - * @type string[]|\Google\Protobuf\Internal\RepeatedField $leading_detached_comments + * @type array<string>|\Google\Protobuf\Internal\RepeatedField $leading_detached_comments * } */ public function __construct($data = NULL) { @@ -236,7 +236,7 @@ * of the label to the terminating semicolon). * * Generated from protobuf field <code>repeated int32 path = 1 [packed = true];</code> - * @param int[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<int>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setPath($var) @@ -270,7 +270,7 @@ * 1 to each before displaying to a user. * * Generated from protobuf field <code>repeated int32 span = 2 [packed = true];</code> - * @param int[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<int>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setSpan($var) @@ -302,12 +302,12 @@ * optional string baz = 3; * // Comment attached to baz. * // Another line attached to baz. - * // Comment attached to qux. + * // Comment attached to moo. * // - * // Another line attached to qux. - * optional double qux = 4; + * // Another line attached to moo. + * optional double moo = 4; * // Detached comment for corge. This is not leading or trailing comments - * // to qux or corge because there are blank lines separating it from + * // to moo or corge because there are blank lines separating it from * // both. * // Detached comment for corge paragraph 2. * optional string corge = 5; @@ -358,12 +358,12 @@ * optional string baz = 3; * // Comment attached to baz. * // Another line attached to baz. - * // Comment attached to qux. + * // Comment attached to moo. * // - * // Another line attached to qux. - * optional double qux = 4; + * // Another line attached to moo. + * optional double moo = 4; * // Detached comment for corge. This is not leading or trailing comments - * // to qux or corge because there are blank lines separating it from + * // to moo or corge because there are blank lines separating it from * // both. * // Detached comment for corge paragraph 2. * optional string corge = 5; @@ -430,7 +430,7 @@ /** * Generated from protobuf field <code>repeated string leading_detached_comments = 6;</code> - * @param string[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<string>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setLeadingDetachedComments($var)
diff --git a/php/src/Google/Protobuf/Internal/UninterpretedOption.php b/php/src/Google/Protobuf/Internal/UninterpretedOption.php index a2aae3e..a1cdca5 100644 --- a/php/src/Google/Protobuf/Internal/UninterpretedOption.php +++ b/php/src/Google/Protobuf/Internal/UninterpretedOption.php
@@ -60,7 +60,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type \Google\Protobuf\Internal\UninterpretedOption\NamePart[]|\Google\Protobuf\Internal\RepeatedField $name + * @type array<\Google\Protobuf\Internal\UninterpretedOption\NamePart>|\Google\Protobuf\Internal\RepeatedField $name * @type string $identifier_value * The value of the uninterpreted option, in whatever type the tokenizer * identified it as during parsing. Exactly one of these should be set. @@ -87,7 +87,7 @@ /** * Generated from protobuf field <code>repeated .google.protobuf.UninterpretedOption.NamePart name = 2;</code> - * @param \Google\Protobuf\Internal\UninterpretedOption\NamePart[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Internal\UninterpretedOption\NamePart>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setName($var)
diff --git a/php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php b/php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php index 6212d1e..2debf83 100644 --- a/php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php +++ b/php/src/Google/Protobuf/Internal/UninterpretedOption/NamePart.php
@@ -14,8 +14,8 @@ * The name of the uninterpreted option. Each string represents a segment in * a dot-separated name. is_extension is true iff a segment represents an * extension (denoted with parentheses in options specs in .proto files). - * E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - * "foo.(bar.baz).qux". + * E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + * "foo.(bar.baz).moo". * * Generated from protobuf message <code>google.protobuf.UninterpretedOption.NamePart</code> */
diff --git a/php/src/Google/Protobuf/ListValue.php b/php/src/Google/Protobuf/ListValue.php index 70f5423..891283c 100644 --- a/php/src/Google/Protobuf/ListValue.php +++ b/php/src/Google/Protobuf/ListValue.php
@@ -29,7 +29,7 @@ * @param array $data { * Optional. Data for populating the Message object. * - * @type \Google\Protobuf\Value[]|\Google\Protobuf\Internal\RepeatedField $values + * @type array<\Google\Protobuf\Value>|\Google\Protobuf\Internal\RepeatedField $values * Repeated field of dynamically typed values. * } */ @@ -53,7 +53,7 @@ * Repeated field of dynamically typed values. * * Generated from protobuf field <code>repeated .google.protobuf.Value values = 1;</code> - * @param \Google\Protobuf\Value[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Value>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setValues($var)
diff --git a/php/src/Google/Protobuf/Method.php b/php/src/Google/Protobuf/Method.php index 2755baa..eda00bf 100644 --- a/php/src/Google/Protobuf/Method.php +++ b/php/src/Google/Protobuf/Method.php
@@ -74,7 +74,7 @@ * The URL of the output message type. * @type bool $response_streaming * If true, the response is streamed. - * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options + * @type array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $options * Any metadata attached to the method. * @type int $syntax * The source syntax of this method. @@ -230,7 +230,7 @@ * Any metadata attached to the method. * * Generated from protobuf field <code>repeated .google.protobuf.Option options = 6;</code> - * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setOptions($var)
diff --git a/php/src/Google/Protobuf/Type.php b/php/src/Google/Protobuf/Type.php index 41b9e36..d4af7df 100644 --- a/php/src/Google/Protobuf/Type.php +++ b/php/src/Google/Protobuf/Type.php
@@ -60,11 +60,11 @@ * * @type string $name * The fully qualified message name. - * @type \Google\Protobuf\Field[]|\Google\Protobuf\Internal\RepeatedField $fields + * @type array<\Google\Protobuf\Field>|\Google\Protobuf\Internal\RepeatedField $fields * The list of fields. - * @type string[]|\Google\Protobuf\Internal\RepeatedField $oneofs + * @type array<string>|\Google\Protobuf\Internal\RepeatedField $oneofs * The list of types appearing in `oneof` definitions in this type. - * @type \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $options + * @type array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $options * The protocol buffer options. * @type \Google\Protobuf\SourceContext $source_context * The source context. @@ -118,7 +118,7 @@ * The list of fields. * * Generated from protobuf field <code>repeated .google.protobuf.Field fields = 2;</code> - * @param \Google\Protobuf\Field[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Field>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setFields($var) @@ -144,7 +144,7 @@ * The list of types appearing in `oneof` definitions in this type. * * Generated from protobuf field <code>repeated string oneofs = 3;</code> - * @param string[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<string>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setOneofs($var) @@ -170,7 +170,7 @@ * The protocol buffer options. * * Generated from protobuf field <code>repeated .google.protobuf.Option options = 4;</code> - * @param \Google\Protobuf\Option[]|\Google\Protobuf\Internal\RepeatedField $var + * @param array<\Google\Protobuf\Option>|\Google\Protobuf\Internal\RepeatedField $var * @return $this */ public function setOptions($var)
diff --git a/php/tests/GeneratedClassTest.php b/php/tests/GeneratedClassTest.php index 42b1f74..3c4ef13 100644 --- a/php/tests/GeneratedClassTest.php +++ b/php/tests/GeneratedClassTest.php
@@ -330,6 +330,18 @@ $this->legacyEnum(new TestLegacyMessage\NestedEnum); } + public function testLegacyReadOnlyMessage() + { + $this->assertTrue(class_exists('\Upper\READONLY')); + $this->assertTrue(class_exists('\Lower\readonly')); + } + + public function testLegacyReadOnlyEnum() + { + $this->assertTrue(class_exists('\Upper_enum\READONLY')); + $this->assertTrue(class_exists('\Lower_enum\readonly')); + } + private function legacyEnum(TestLegacyMessage_NestedEnum $enum) { // If we made it here without a PHP Fatal error, the typehint worked @@ -939,6 +951,7 @@ $m = new \Lower\PBprivate(); $m = new \Lower\PBprotected(); $m = new \Lower\PBpublic(); + $m = new \Lower\PBreadonly(); $m = new \Lower\PBrequire(); $m = new \Lower\PBrequire_once(); $m = new \Lower\PBreturn(); @@ -1019,6 +1032,7 @@ $m = new \Upper\PBPRIVATE(); $m = new \Upper\PBPROTECTED(); $m = new \Upper\PBPUBLIC(); + $m = new \Upper\PBREADONLY(); $m = new \Upper\PBREQUIRE(); $m = new \Upper\PBREQUIRE_ONCE(); $m = new \Upper\PBRETURN(); @@ -1100,6 +1114,7 @@ $m = new \Lower_enum\PBprotected(); $m = new \Lower_enum\PBpublic(); $m = new \Lower_enum\PBrequire(); + $m = new \Lower_enum\PBreadonly(); $m = new \Lower_enum\PBrequire_once(); $m = new \Lower_enum\PBreturn(); $m = new \Lower_enum\PBself(); @@ -1179,6 +1194,7 @@ $m = new \Upper_enum\PBPRIVATE(); $m = new \Upper_enum\PBPROTECTED(); $m = new \Upper_enum\PBPUBLIC(); + $m = new \Upper_enum\PBREADONLY(); $m = new \Upper_enum\PBREQUIRE(); $m = new \Upper_enum\PBREQUIRE_ONCE(); $m = new \Upper_enum\PBRETURN(); @@ -1283,6 +1299,7 @@ $m = \Lower_enum_value\NotAllowed::iterable; $m = \Lower_enum_value\NotAllowed::parent; $m = \Lower_enum_value\NotAllowed::self; + $m = \Lower_enum_value\NotAllowed::readonly; $m = \Upper_enum_value\NotAllowed::PBABSTRACT; $m = \Upper_enum_value\NotAllowed::PBAND; @@ -1363,6 +1380,7 @@ $m = \Upper_enum_value\NotAllowed::ITERABLE; $m = \Upper_enum_value\NotAllowed::PARENT; $m = \Upper_enum_value\NotAllowed::SELF; + $m = \Upper_enum_value\NotAllowed::READONLY; $this->assertTrue(true); }
diff --git a/php/tests/GeneratedPhpdocTest.php b/php/tests/GeneratedPhpdocTest.php index a0b912b..78ac623 100644 --- a/php/tests/GeneratedPhpdocTest.php +++ b/php/tests/GeneratedPhpdocTest.php
@@ -163,7 +163,7 @@ 'setRepeatedEnum', 'setRepeatedNoNamespaceEnum', ], - '@param int[]|\Google\Protobuf\Internal\RepeatedField $var' + '@param array<int>|\Google\Protobuf\Internal\RepeatedField $var' ], [ [ @@ -173,45 +173,45 @@ 'setRepeatedFixed64', 'setRepeatedSfixed64', ], - '@param int[]|string[]|\Google\Protobuf\Internal\RepeatedField $var' + '@param array<int>|array<string>|\Google\Protobuf\Internal\RepeatedField $var' ], [ [ 'setRepeatedFloat', 'setRepeatedDouble', ], - '@param float[]|\Google\Protobuf\Internal\RepeatedField $var' + '@param array<float>|\Google\Protobuf\Internal\RepeatedField $var' ], [ [ 'setRepeatedBool', ], - '@param bool[]|\Google\Protobuf\Internal\RepeatedField $var' + '@param array<bool>|\Google\Protobuf\Internal\RepeatedField $var' ], [ [ 'setRepeatedString', 'setRepeatedBytes', ], - '@param string[]|\Google\Protobuf\Internal\RepeatedField $var' + '@param array<string>|\Google\Protobuf\Internal\RepeatedField $var' ], [ [ 'setRepeatedMessage', ], - '@param \Foo\TestMessage\Sub[]|\Google\Protobuf\Internal\RepeatedField $var' + '@param array<\Foo\TestMessage\Sub>|\Google\Protobuf\Internal\RepeatedField $var' ], [ [ 'setRepeatedRecursive', ], - '@param \Foo\TestMessage[]|\Google\Protobuf\Internal\RepeatedField $var' + '@param array<\Foo\TestMessage>|\Google\Protobuf\Internal\RepeatedField $var' ], [ [ 'setRepeatedNoNamespaceMessage', ], - '@param \NoNamespaceMessage[]|\Google\Protobuf\Internal\RepeatedField $var' + '@param array<\NoNamespaceMessage>|\Google\Protobuf\Internal\RepeatedField $var' ], [ [
diff --git a/php/tests/compile_extension.sh b/php/tests/compile_extension.sh index d334587..3261917 100755 --- a/php/tests/compile_extension.sh +++ b/php/tests/compile_extension.sh
@@ -34,4 +34,5 @@ fi make +TEST_PHP_ARGS="-q" make test popd > /dev/null
diff --git a/php/tests/proto/test_reserved_enum_lower.proto b/php/tests/proto/test_reserved_enum_lower.proto index f8557d2..1f96ac6 100644 --- a/php/tests/proto/test_reserved_enum_lower.proto +++ b/php/tests/proto/test_reserved_enum_lower.proto
@@ -57,6 +57,7 @@ enum private { ZERO52 = 0; } enum protected { ZERO53 = 0; } enum public { ZERO54 = 0; } +enum readonly { ZERO80 = 0; } enum require { ZERO55 = 0; } enum require_once { ZERO56 = 0; } enum return { ZERO57 = 0; }
diff --git a/php/tests/proto/test_reserved_enum_upper.proto b/php/tests/proto/test_reserved_enum_upper.proto index 8d382ab..c5e7e99 100644 --- a/php/tests/proto/test_reserved_enum_upper.proto +++ b/php/tests/proto/test_reserved_enum_upper.proto
@@ -57,6 +57,7 @@ enum PRIVATE { ZERO52 = 0; } enum PROTECTED { ZERO53 = 0; } enum PUBLIC { ZERO54 = 0; } +enum READONLY { ZERO80 = 0; } enum REQUIRE { ZERO55 = 0; } enum REQUIRE_ONCE { ZERO56 = 0; } enum RETURN { ZERO57 = 0; }
diff --git a/php/tests/proto/test_reserved_enum_value_lower.proto b/php/tests/proto/test_reserved_enum_value_lower.proto index ca5a7c7..86c6877 100644 --- a/php/tests/proto/test_reserved_enum_value_lower.proto +++ b/php/tests/proto/test_reserved_enum_value_lower.proto
@@ -58,6 +58,7 @@ private = 51; protected = 52; public = 53; + readonly = 79; require = 54; require_once = 55; return = 56;
diff --git a/php/tests/proto/test_reserved_enum_value_upper.proto b/php/tests/proto/test_reserved_enum_value_upper.proto index 6b4040d..ac0beda 100644 --- a/php/tests/proto/test_reserved_enum_value_upper.proto +++ b/php/tests/proto/test_reserved_enum_value_upper.proto
@@ -58,6 +58,7 @@ PRIVATE = 51; PROTECTED = 52; PUBLIC = 53; + READONLY = 79; REQUIRE = 54; REQUIRE_ONCE = 55; RETURN = 56;
diff --git a/php/tests/proto/test_reserved_message_lower.proto b/php/tests/proto/test_reserved_message_lower.proto index 2390a87..551ed7a 100644 --- a/php/tests/proto/test_reserved_message_lower.proto +++ b/php/tests/proto/test_reserved_message_lower.proto
@@ -57,6 +57,7 @@ message private {} message protected {} message public {} +message readonly {} message require {} message require_once {} message return {}
diff --git a/php/tests/proto/test_reserved_message_upper.proto b/php/tests/proto/test_reserved_message_upper.proto index 9f55330..96995c9 100644 --- a/php/tests/proto/test_reserved_message_upper.proto +++ b/php/tests/proto/test_reserved_message_upper.proto
@@ -57,6 +57,7 @@ message PRIVATE {} message PROTECTED {} message PUBLIC {} +message READONLY {} message REQUIRE {} message REQUIRE_ONCE {} message RETURN {}
diff --git a/pkg/BUILD b/pkg/BUILD new file mode 100644 index 0000000..3e5f5d1 --- /dev/null +++ b/pkg/BUILD
@@ -0,0 +1,117 @@ +load("@rules_pkg//:pkg.bzl", "pkg_zip") +load("@rules_pkg//:mappings.bzl", "pkg_attributes", "pkg_files") +load("//:protobuf_release.bzl", "package_naming") +load(":cc_dist_library.bzl", "cc_dist_library") + +pkg_files( + name = "wkt_protos_files", + srcs = [ + "//:any_proto", + "//:api_proto", + "//:duration_proto", + "//:empty_proto", + "//:field_mask_proto", + "//:source_context_proto", + "//:struct_proto", + "//:timestamp_proto", + "//:type_proto", + "//:wrappers_proto", + ], + prefix = "include/google/protobuf", + visibility = ["//visibility:private"], +) + +pkg_files( + name = "descriptor_protos_files", + srcs = [ + "//:descriptor_proto", + ], + prefix = "include/google/protobuf", + visibility = ["//visibility:private"], +) + +pkg_files( + name = "compiler_plugin_protos_files", + srcs = ["//:compiler_plugin_proto"], + prefix = "include/google/protobuf/compiler", + visibility = ["//visibility:private"], +) + +################################################################################ +# Generates protoc release artifacts. +################################################################################ + +genrule( + name = "protoc_readme", + outs = ["readme.txt"], + cmd = """ +echo "Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. +https://developers.google.com/protocol-buffers/ +This package contains a precompiled binary version of the protocol buffer +compiler (protoc). This binary is intended for users who want to use Protocol +Buffers in languages other than C++ but do not want to compile protoc +themselves. To install, simply place this binary somewhere in your PATH. +If you intend to use the included well known types then don't forget to +copy the contents of the 'include' directory somewhere as well, for example +into '/usr/local/include/'. +Please refer to our official github site for more installation instructions: + https://github.com/protocolbuffers/protobuf" > $@ + """, + visibility = ["//visibility:private"], +) + +pkg_files( + name = "protoc_files", + srcs = ["//:protoc"], + attributes = pkg_attributes(mode = "0555"), + prefix = "bin/", + visibility = ["//visibility:private"], +) + +package_naming( + name = "protoc_pkg_naming", +) + +pkg_zip( + name = "protoc_release", + srcs = [ + ":compiler_plugin_protos_files", + ":descriptor_protos_files", + ":protoc_files", + ":protoc_readme", + ":wkt_protos_files", + ], + package_file_name = "protoc-{version}-{platform}.zip", + package_variables = ":protoc_pkg_naming", +) + +################################################################################ +# Protobuf runtime libraries. +################################################################################ + +cc_dist_library( + name = "protobuf_lite", + linkopts = select({ + "//:msvc": [], + "//conditions:default": ["-lpthread"], + }), + deps = [ + "//:protobuf_lite", + ], +) + +cc_dist_library( + name = "protobuf", + linkopts = select({ + "//:msvc": [], + "//conditions:default": [ + "-lz", + "-lpthread", + ], + }), + deps = [ + "//:protobuf", + "//:protobuf_lite", + ], +)
diff --git a/pkg/cc_dist_library.bzl b/pkg/cc_dist_library.bzl new file mode 100644 index 0000000..654fb73 --- /dev/null +++ b/pkg/cc_dist_library.bzl
@@ -0,0 +1,232 @@ +# Rules for distributable C++ libraries + +load("@rules_cc//cc:action_names.bzl", cc_action_names = "ACTION_NAMES") +load("@rules_cc//cc:find_cc_toolchain.bzl", "find_cc_toolchain") + +# Creates an action to build the `output_file` static library (archive) +# using `object_files`. +def _create_archive_action( + ctx, + feature_configuration, + cc_toolchain, + output_file, + object_files): + # Based on Bazel's src/main/starlark/builtins_bzl/common/cc/cc_import.bzl: + + # Build the command line and add args for all of the input files: + archiver_variables = cc_common.create_link_variables( + feature_configuration = feature_configuration, + cc_toolchain = cc_toolchain, + output_file = output_file.path, + is_using_linker = False, + ) + command_line = cc_common.get_memory_inefficient_command_line( + feature_configuration = feature_configuration, + action_name = cc_action_names.cpp_link_static_library, + variables = archiver_variables, + ) + args = ctx.actions.args() + args.add_all(command_line) + args.add_all(object_files) + args.use_param_file("@%s", use_always = True) + + archiver_path = cc_common.get_tool_for_action( + feature_configuration = feature_configuration, + action_name = cc_action_names.cpp_link_static_library, + ) + + env = cc_common.get_environment_variables( + feature_configuration = feature_configuration, + action_name = cc_action_names.cpp_link_static_library, + variables = archiver_variables, + ) + + ctx.actions.run( + executable = archiver_path, + arguments = [args], + env = env, + inputs = depset( + direct = object_files, + transitive = [ + cc_toolchain.all_files, + ], + ), + use_default_shell_env = True, + outputs = [output_file], + mnemonic = "CppArchiveDist", + ) + +# Implementation for cc_dist_library rule. +def _cc_dist_library_impl(ctx): + cc_toolchain_info = find_cc_toolchain(ctx) + if cc_toolchain_info.ar_executable == None: + return [] + + feature_configuration = cc_common.configure_features( + ctx = ctx, + cc_toolchain = cc_toolchain_info, + ) + + # Collect the set of object files from the immediate deps. + + objs = [] + pic_objs = [] + for dep in ctx.attr.deps: + if CcInfo not in dep: + continue + + link_ctx = dep[CcInfo].linking_context + if link_ctx == None: + continue + + linker_inputs = link_ctx.linker_inputs.to_list() + for link_input in linker_inputs: + if link_input.owner != dep.label: + # This is a transitive dep: skip it. + continue + + for lib in link_input.libraries: + objs.extend(lib.objects or []) + pic_objs.extend(lib.pic_objects or []) + + # For static libraries, build separately with and without pic. + + stemname = "lib" + ctx.label.name + outputs = [] + + if len(objs) > 0: + archive_out = ctx.actions.declare_file(stemname + ".a") + _create_archive_action( + ctx, + feature_configuration, + cc_toolchain_info, + archive_out, + objs, + ) + outputs.append(archive_out) + + if len(pic_objs) > 0: + pic_archive_out = ctx.actions.declare_file(stemname + ".pic.a") + _create_archive_action( + ctx, + feature_configuration, + cc_toolchain_info, + pic_archive_out, + pic_objs, + ) + outputs.append(pic_archive_out) + + # For dynamic libraries, use the `cc_common.link` command to ensure + # everything gets built correctly according to toolchain definitions. + + compilation_outputs = cc_common.create_compilation_outputs( + objects = depset(objs), + pic_objects = depset(pic_objs), + ) + link_output = cc_common.link( + actions = ctx.actions, + feature_configuration = feature_configuration, + cc_toolchain = cc_toolchain_info, + compilation_outputs = compilation_outputs, + name = ctx.label.name, + output_type = "dynamic_library", + user_link_flags = ctx.attr.linkopts, + ) + library_to_link = link_output.library_to_link + + # Note: library_to_link.dynamic_library and interface_library are often + # symlinks in the solib directory. For DefaultInfo, prefer reporting + # the resolved artifact paths. + if library_to_link.resolved_symlink_dynamic_library != None: + outputs.append(library_to_link.resolved_symlink_dynamic_library) + elif library_to_link.dynamic_library != None: + outputs.append(library_to_link.dynamic_library) + + if library_to_link.resolved_symlink_interface_library != None: + outputs.append(library_to_link.resolved_symlink_interface_library) + elif library_to_link.interface_library != None: + outputs.append(library_to_link.interface_library) + + # We could expose the libraries for use from cc rules: + # + # linking_context = cc_common.create_linking_context( + # linker_inputs = depset([ + # cc_common.create_linker_input( + # owner = ctx.label, + # libraries = depset([library_to_link]), + # ), + # ]), + # ) + # cc_info = CcInfo(linking_context = linking_context) # and return this + # + # However, if the goal is to force a protobuf dependency to use the + # DSO, then `cc_import` is a better-supported way to do so. + # + # If we wanted to expose CcInfo from this rule (and make it usable as a + # C++ dependency), then we would probably want to include the static + # archive and headers as well. exposing headers would probably require + # an additional aspect to extract CcInfos with just the deps' headers. + + return [ + DefaultInfo(files = depset(outputs)), + ] + +cc_dist_library = rule( + implementation = _cc_dist_library_impl, + doc = """ +Create libraries suitable for distribution. + +This rule creates static and dynamic libraries from the libraries listed in +'deps'. The resulting libraries are suitable for distributing all of 'deps' +in a single logical library, for example, in an installable binary package. +Only the targets listed in 'deps' are included in the result (i.e., the +output does not include transitive dependencies), allowing precise control +over the library boundary. + +The outputs of this rule are a dynamic library and a static library. (If +the build produces both PIC and non-PIC object files, then there is also a +second static library.) The example below illustrates additional details. + +This rule is different from Bazel's experimental `shared_cc_library` in +several ways. First, this rule ignores transitive dependencies, which means +that dynamic library dependencies generally need to be specified via +'linkopts'. Second, this rule produces a static archive library in addition +to the dynamic shared library. Third, this rule is not directly usable as a +C++ dependency (although the outputs could be used, e.g., by `cc_import`). + +Example: + + cc_library(name = "a", srcs = ["a.cc"], hdrs = ["a.h"]) + cc_library(name = "b", srcs = ["b.cc"], hdrs = ["b.h"], deps = [":a"]) + cc_library(name = "c", srcs = ["c.cc"], hdrs = ["c.h"], deps = [":b"]) + + # Creates libdist.so and (typically) libdist.pic.a: + # (This may also produce libdist.a if the build produces non-PIC objects.) + cc_dist_library( + name = "dist", + linkopts = ["-la"], # libdist.so dynamically links against liba.so. + deps = [":b", ":c"], # Output contains b.o and c.o, but not a.o. + ) +""", + attrs = { + "deps": attr.label_list( + doc = ("The list of libraries to be included in the outputs. " + + "Only these targets' compilation outputs will be " + + "included (i.e., the transitive dependencies are not " + + "included in the output)."), + ), + "linkopts": attr.string_list( + doc = ("Add these flags to the C++ linker command when creating " + + "the dynamic library."), + ), + # C++ toolchain before https://github.com/bazelbuild/bazel/issues/7260: + "_cc_toolchain": attr.label( + default = Label("@rules_cc//cc:current_cc_toolchain"), + ), + }, + toolchains = [ + # C++ toolchain after https://github.com/bazelbuild/bazel/issues/7260: + "@bazel_tools//tools/cpp:toolchain_type", + ], + fragments = ["cpp"], +)
diff --git a/protobuf.bzl b/protobuf.bzl index 8e173fd..2dc4ecd 100644 --- a/protobuf.bzl +++ b/protobuf.bzl
@@ -79,17 +79,20 @@ deps = depset(direct=ctx.files.srcs) source_dir = _SourceDir(ctx) gen_dir = _GenDir(ctx).rstrip("/") + import_flags = [] + if source_dir: has_sources = any([src.is_source for src in srcs]) - has_generated = any([not src.is_source for src in srcs]) - import_flags = [] if has_sources: import_flags += ["-I" + source_dir] - if has_generated: - import_flags += ["-I" + gen_dir] - import_flags = depset(direct=import_flags) else: - import_flags = depset(direct=["-I."]) + import_flags += ["-I."] + + has_generated = any([not src.is_source for src in srcs]) + if has_generated: + import_flags += ["-I" + gen_dir] + + import_flags = depset(direct=import_flags) for dep in ctx.attr.deps: if type(dep.proto.import_flags) == "list": @@ -163,7 +166,7 @@ for out in outs: orig_command = " ".join( ["$(realpath %s)" % ctx.executable.protoc.path] + args + - import_flags_real + ["-I.", src.basename], + import_flags_real + [src.basename], ) command = ";".join([ 'CMD="%s"' % orig_command,
diff --git a/protobuf_deps.bzl b/protobuf_deps.bzl index 54f8e22..38d13ff 100644 --- a/protobuf_deps.bzl +++ b/protobuf_deps.bzl
@@ -7,10 +7,10 @@ "com.google.code.gson:gson:2.8.9", "com.google.errorprone:error_prone_annotations:2.3.2", "com.google.j2objc:j2objc-annotations:1.3", - "com.google.guava:guava:30.1.1-jre", - "com.google.guava:guava-testlib:30.1.1-jre", + "com.google.guava:guava:31.1-jre", + "com.google.guava:guava-testlib:31.1-jre", "com.google.truth:truth:1.1.2", - "junit:junit:4.12", + "junit:junit:4.13.2", "org.mockito:mockito-core:4.3.1", ] @@ -27,6 +27,15 @@ ], ) + if not native.existing_rule("com_google_absl"): + # Abseil LTS from November 2021 + http_archive( + name = "com_google_absl", + sha256 = "b4e20d9e752a75c10636675691b1e9c2698e0764cb404987d0ffa77223041c19", + urls = ["https://github.com/abseil/abseil-cpp/archive/215105818dfde3174fe799600bb0f3cae233d0bf.zip"], + strip_prefix = "abseil-cpp-215105818dfde3174fe799600bb0f3cae233d0bf", + ) + if not native.existing_rule("zlib"): http_archive( name = "zlib", @@ -79,10 +88,10 @@ http_archive( name = "rules_pkg", urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_pkg/releases/download/0.5.1/rules_pkg-0.5.1.tar.gz", - "https://github.com/bazelbuild/rules_pkg/releases/download/0.5.1/rules_pkg-0.5.1.tar.gz", + "https://mirror.bazel.build/github.com/bazelbuild/rules_pkg/releases/download/0.7.0/rules_pkg-0.7.0.tar.gz", + "https://github.com/bazelbuild/rules_pkg/releases/download/0.7.0/rules_pkg-0.7.0.tar.gz", ], - sha256 = "a89e203d3cf264e564fcb96b6e06dd70bc0557356eb48400ce4b5d97c2c3720d", + sha256 = "8a298e832762eda1830597d64fe7db58178aa84cd5926d76d5b744d6558941c2", ) if not native.existing_rule("io_bazel_rules_kotlin"):
diff --git a/python/docs/generate_docs.py b/python/docs/generate_docs.py index e024aaa..6b38398 100755 --- a/python/docs/generate_docs.py +++ b/python/docs/generate_docs.py
@@ -111,7 +111,7 @@ .. warning:: You are reading the documentation for the `latest committed changes - <https://github.com/protocolbuffers/protobuf/tree/master/python>`_ of + <https://github.com/protocolbuffers/protobuf/tree/main/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
diff --git a/python/google/protobuf/descriptor.py b/python/google/protobuf/descriptor.py index ad70be9..f5a0caa 100644 --- a/python/google/protobuf/descriptor.py +++ b/python/google/protobuf/descriptor.py
@@ -40,11 +40,15 @@ from google.protobuf.internal import api_implementation _USE_C_DESCRIPTORS = False -if api_implementation.Type() == 'cpp': +if api_implementation.Type() != 'python': # Used by MakeDescriptor in cpp mode import binascii import os - from google.protobuf.pyext import _message + # pylint: disable=protected-access + _message = api_implementation._c_module + # TODO(jieluo): Remove this import after fix api_implementation + if _message is None: + from google.protobuf.pyext import _message _USE_C_DESCRIPTORS = True @@ -598,13 +602,13 @@ self.is_extension = is_extension self.extension_scope = extension_scope self.containing_oneof = containing_oneof - if api_implementation.Type() == 'cpp': + if api_implementation.Type() == 'python': + self._cdescriptor = None + else: if is_extension: self._cdescriptor = _message.default_pool.FindExtensionByName(full_name) else: self._cdescriptor = _message.default_pool.FindFieldByName(full_name) - else: - self._cdescriptor = None @property def camelcase_name(self): @@ -1135,7 +1139,7 @@ Returns: A Descriptor for protobuf messages. """ - if api_implementation.Type() == 'cpp' and build_file_if_cpp: + if api_implementation.Type() != 'python' and build_file_if_cpp: # The C++ implementation requires all descriptors to be backed by the same # definition in the C++ descriptor pool. To do this, we build a # FileDescriptorProto with the same definition as this descriptor and build
diff --git a/python/google/protobuf/internal/api_implementation.py b/python/google/protobuf/internal/api_implementation.py index 7fef237..96dd096 100644 --- a/python/google/protobuf/internal/api_implementation.py +++ b/python/google/protobuf/internal/api_implementation.py
@@ -31,41 +31,81 @@ """Determine which implementation of the protobuf API is used in this process. """ +import importlib import os import sys import warnings + +def _ApiVersionToImplementationType(api_version): + if api_version == 2: + return 'cpp' + if api_version == 1: + raise ValueError('api_version=1 is no longer supported.') + if api_version == 0: + return 'python' + return None + + +_implementation_type = None try: # pylint: disable=g-import-not-at-top from google.protobuf.internal import _api_implementation # The compile-time constants in the _api_implementation module can be used to # switch to a certain implementation of the Python API at build time. - _api_version = _api_implementation.api_version + _implementation_type = _ApiVersionToImplementationType( + _api_implementation.api_version) except ImportError: - _api_version = -1 # Unspecified by compiler flags. - -if _api_version == 1: - raise ValueError('api_version=1 is no longer supported.') + pass # Unspecified by compiler flags. -_default_implementation_type = ('cpp' if _api_version > 0 else 'python') +if _implementation_type is None: + _implementation_type = 'python' + # This environment variable can be used to switch to a certain implementation # of the Python API, overriding the compile-time constants in the -# _api_implementation module. Right now only 'python' and 'cpp' are valid -# values. Any other value will be ignored. +# _api_implementation module. Right now only 'python', 'cpp' and 'upb' are +# valid values. Any other value will raise error. _implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION', - _default_implementation_type) + _implementation_type) -if _implementation_type != 'python': - _implementation_type = 'cpp' +if _implementation_type not in ('python', 'cpp', 'upb'): + raise ValueError('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION {0} is not ' + 'supported. Please set to \'python\', \'cpp\' or ' + '\'upb\'.'.format(_implementation_type)) if 'PyPy' in sys.version and _implementation_type == 'cpp': warnings.warn('PyPy does not work yet with cpp protocol buffers. ' 'Falling back to the python implementation.') _implementation_type = 'python' +_c_module = None + +if _implementation_type == 'cpp': + try: + # pylint: disable=g-import-not-at-top + from google.protobuf.pyext import _message + _c_module = _message + del _message + except ImportError: + # TODO(jieluo): fail back to python + warnings.warn( + 'Selected implementation cpp is not available.') + pass + +if _implementation_type == 'upb': + try: + # pylint: disable=g-import-not-at-top + from google.protobuf.pyext import _upb_message as _message + _c_module = _message + del _message + except ImportError: + warnings.warn('Selected implementation upb is not available. ' + 'Falling back to the python implementation.') + _implementation_type = 'python' + pass # Detect if serialization should be deterministic by default try: @@ -103,6 +143,7 @@ # See comment on 'Type' above. +# TODO(jieluo): Remove the API, it returns a constant. b/228102101 def Version(): return 2
diff --git a/python/google/protobuf/internal/decoder.py b/python/google/protobuf/internal/decoder.py index bc1b7b7..a916276 100644 --- a/python/google/protobuf/internal/decoder.py +++ b/python/google/protobuf/internal/decoder.py
@@ -831,6 +831,45 @@ return DecodeItem + +def UnknownMessageSetItemDecoder(): + """Returns a decoder for a Unknown MessageSet item.""" + + type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) + message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) + item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) + + def DecodeUnknownItem(buffer): + pos = 0 + end = len(buffer) + message_start = -1 + message_end = -1 + while 1: + (tag_bytes, pos) = ReadTag(buffer, pos) + if tag_bytes == type_id_tag_bytes: + (type_id, pos) = _DecodeVarint(buffer, pos) + elif tag_bytes == message_tag_bytes: + (size, message_start) = _DecodeVarint(buffer, pos) + pos = message_end = message_start + size + elif tag_bytes == item_end_tag_bytes: + break + else: + pos = SkipField(buffer, pos, end, tag_bytes) + if pos == -1: + raise _DecodeError('Missing group end tag.') + + if pos > end: + raise _DecodeError('Truncated message.') + + if type_id == -1: + raise _DecodeError('MessageSet item missing type_id.') + if message_start == -1: + raise _DecodeError('MessageSet item missing message.') + + return (type_id, buffer[message_start:message_end].tobytes()) + + return DecodeUnknownItem + # -------------------------------------------------------------------- def MapDecoder(field_descriptor, new_default, is_message_map):
diff --git a/python/google/protobuf/internal/descriptor_test.py b/python/google/protobuf/internal/descriptor_test.py index d026a74..6a8532c 100644 --- a/python/google/protobuf/internal/descriptor_test.py +++ b/python/google/protobuf/internal/descriptor_test.py
@@ -144,7 +144,7 @@ self.assertEqual(self.my_service, self.my_method.containing_service) @unittest.skipIf( - api_implementation.Type() != 'cpp', + api_implementation.Type() == 'python', 'GetDebugString is only available with the cpp implementation', ) def testGetDebugString(self): @@ -328,10 +328,10 @@ unittest_custom_options_pb2.complex_opt1].foo) self.assertEqual(324, options.Extensions[ unittest_custom_options_pb2.complex_opt1].Extensions[ - unittest_custom_options_pb2.quux]) + unittest_custom_options_pb2.mooo]) self.assertEqual(876, options.Extensions[ unittest_custom_options_pb2.complex_opt1].Extensions[ - unittest_custom_options_pb2.corge].qux) + unittest_custom_options_pb2.corge].moo) self.assertEqual(987, options.Extensions[ unittest_custom_options_pb2.complex_opt2].baz) self.assertEqual(654, options.Extensions[ @@ -341,28 +341,28 @@ unittest_custom_options_pb2.complex_opt2].bar.foo) self.assertEqual(1999, options.Extensions[ unittest_custom_options_pb2.complex_opt2].bar.Extensions[ - unittest_custom_options_pb2.quux]) + unittest_custom_options_pb2.mooo]) self.assertEqual(2008, options.Extensions[ unittest_custom_options_pb2.complex_opt2].bar.Extensions[ - unittest_custom_options_pb2.corge].qux) + unittest_custom_options_pb2.corge].moo) self.assertEqual(741, options.Extensions[ unittest_custom_options_pb2.complex_opt2].Extensions[ unittest_custom_options_pb2.garply].foo) self.assertEqual(1998, options.Extensions[ unittest_custom_options_pb2.complex_opt2].Extensions[ unittest_custom_options_pb2.garply].Extensions[ - unittest_custom_options_pb2.quux]) + unittest_custom_options_pb2.mooo]) self.assertEqual(2121, options.Extensions[ unittest_custom_options_pb2.complex_opt2].Extensions[ unittest_custom_options_pb2.garply].Extensions[ - unittest_custom_options_pb2.corge].qux) + unittest_custom_options_pb2.corge].moo) self.assertEqual(1971, options.Extensions[ unittest_custom_options_pb2.ComplexOptionType2 .ComplexOptionType4.complex_opt4].waldo) self.assertEqual(321, options.Extensions[ unittest_custom_options_pb2.complex_opt2].fred.waldo) self.assertEqual(9, options.Extensions[ - unittest_custom_options_pb2.complex_opt3].qux) + unittest_custom_options_pb2.complex_opt3].moo) self.assertEqual(22, options.Extensions[ unittest_custom_options_pb2.complex_opt3].complexoptiontype5.plugh) self.assertEqual(24, options.Extensions[ @@ -457,7 +457,7 @@ self.assertEqual(unittest_pb2.DESCRIPTOR.pool, descriptor_pool.Default()) @unittest.skipIf( - api_implementation.Type() != 'cpp' or api_implementation.Version() != 2, + api_implementation.Type() == 'python', 'Immutability of descriptors is only enforced in v2 implementation') def testImmutableCppDescriptor(self): file_descriptor = unittest_pb2.DESCRIPTOR
diff --git a/python/google/protobuf/internal/message_factory_test.py b/python/google/protobuf/internal/message_factory_test.py index 97ef3aa..efba619 100644 --- a/python/google/protobuf/internal/message_factory_test.py +++ b/python/google/protobuf/internal/message_factory_test.py
@@ -174,48 +174,42 @@ factory = message_factory.MessageFactory(pool=pool) # Add Container message. - f = descriptor_pb2.FileDescriptorProto() - f.name = 'google/protobuf/internal/container.proto' - f.package = 'google.protobuf.python.internal' - msg = f.message_type.add() - msg.name = 'Container' - rng = msg.extension_range.add() - rng.start = 1 - rng.end = 10 + f = descriptor_pb2.FileDescriptorProto( + name='google/protobuf/internal/container.proto', + package='google.protobuf.python.internal') + f.message_type.add(name='Container').extension_range.add(start=1, end=10) pool.Add(f) msgs = factory.GetMessages([f.name]) self.assertIn('google.protobuf.python.internal.Container', msgs) # Extend container. - f = descriptor_pb2.FileDescriptorProto() - f.name = 'google/protobuf/internal/extension.proto' - f.package = 'google.protobuf.python.internal' - f.dependency.append('google/protobuf/internal/container.proto') - msg = f.message_type.add() - msg.name = 'Extension' - ext = msg.extension.add() - ext.name = 'extension_field' - ext.number = 2 - ext.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL - ext.type_name = 'Extension' - ext.extendee = 'Container' + f = descriptor_pb2.FileDescriptorProto( + name='google/protobuf/internal/extension.proto', + package='google.protobuf.python.internal', + dependency=['google/protobuf/internal/container.proto']) + msg = f.message_type.add(name='Extension') + msg.extension.add( + name='extension_field', + number=2, + label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL, + type_name='Extension', + extendee='Container') pool.Add(f) msgs = factory.GetMessages([f.name]) self.assertIn('google.protobuf.python.internal.Extension', msgs) # Add Duplicate extending the same field number. - f = descriptor_pb2.FileDescriptorProto() - f.name = 'google/protobuf/internal/duplicate.proto' - f.package = 'google.protobuf.python.internal' - f.dependency.append('google/protobuf/internal/container.proto') - msg = f.message_type.add() - msg.name = 'Duplicate' - ext = msg.extension.add() - ext.name = 'extension_field' - ext.number = 2 - ext.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL - ext.type_name = 'Duplicate' - ext.extendee = 'Container' + f = descriptor_pb2.FileDescriptorProto( + name='google/protobuf/internal/duplicate.proto', + package='google.protobuf.python.internal', + dependency=['google/protobuf/internal/container.proto']) + msg = f.message_type.add(name='Duplicate') + msg.extension.add( + name='extension_field', + number=2, + label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL, + type_name='Duplicate', + extendee='Container') pool.Add(f) with self.assertRaises(Exception) as cm: @@ -230,6 +224,76 @@ ' with field number 2.', 'Double registration of Extensions']) + def testExtensionValueInDifferentFile(self): + # Add Container message. + f1 = descriptor_pb2.FileDescriptorProto( + name='google/protobuf/internal/container.proto', + package='google.protobuf.python.internal') + f1.message_type.add(name='Container').extension_range.add(start=1, end=10) + + # Add ValueType message. + f2 = descriptor_pb2.FileDescriptorProto( + name='google/protobuf/internal/value_type.proto', + package='google.protobuf.python.internal') + f2.message_type.add(name='ValueType').field.add( + name='setting', + number=1, + label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL, + type=descriptor_pb2.FieldDescriptorProto.TYPE_INT32, + default_value='123') + + # Extend container with field of ValueType. + f3 = descriptor_pb2.FileDescriptorProto( + name='google/protobuf/internal/extension.proto', + package='google.protobuf.python.internal', + dependency=[f1.name, f2.name]) + f3.extension.add( + name='top_level_extension_field', + number=2, + label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL, + type_name='ValueType', + extendee='Container') + f3.message_type.add(name='Extension').extension.add( + name='nested_extension_field', + number=3, + label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL, + type_name='ValueType', + extendee='Container') + + class SimpleDescriptorDB: + + def __init__(self, files): + self._files = files + + def FindFileByName(self, name): + return self._files[name] + + db = SimpleDescriptorDB({f1.name: f1, f2.name: f2, f3.name: f3}) + + pool = descriptor_pool.DescriptorPool(db) + factory = message_factory.MessageFactory(pool=pool) + msgs = factory.GetMessages([f1.name, f3.name]) # Deliberately not f2. + msg = msgs['google.protobuf.python.internal.Container'] + desc = msgs['google.protobuf.python.internal.Extension'].DESCRIPTOR + ext1 = desc.file.extensions_by_name['top_level_extension_field'] + ext2 = desc.extensions_by_name['nested_extension_field'] + m = msg() + m.Extensions[ext1].setting = 234 + m.Extensions[ext2].setting = 345 + serialized = m.SerializeToString() + + pool = descriptor_pool.DescriptorPool(db) + factory = message_factory.MessageFactory(pool=pool) + msgs = factory.GetMessages([f1.name, f3.name]) # Deliberately not f2. + msg = msgs['google.protobuf.python.internal.Container'] + desc = msgs['google.protobuf.python.internal.Extension'].DESCRIPTOR + ext1 = desc.file.extensions_by_name['top_level_extension_field'] + ext2 = desc.extensions_by_name['nested_extension_field'] + m = msg.FromString(serialized) + self.assertEqual(2, len(m.ListFields())) + self.assertEqual(234, m.Extensions[ext1].setting) + self.assertEqual(345, m.Extensions[ext2].setting) + if __name__ == '__main__': unittest.main()
diff --git a/python/google/protobuf/internal/message_test.py b/python/google/protobuf/internal/message_test.py index a5c5a0d..4002685 100644 --- a/python/google/protobuf/internal/message_test.py +++ b/python/google/protobuf/internal/message_test.py
@@ -129,10 +129,13 @@ # TODO(jieluo): Fix cpp extension to raise error instead of warning. # b/27494216 end_tag = encoder.TagBytes(1, 4) - if api_implementation.Type() == 'python': + if (api_implementation.Type() == 'python' or + api_implementation.Type() == 'upb'): with self.assertRaises(message.DecodeError) as context: msg.FromString(end_tag) - self.assertEqual('Unexpected end-group tag.', str(context.exception)) + if api_implementation.Type() == 'python': + # Only pure-Python has an error message this specific. + self.assertEqual('Unexpected end-group tag.', str(context.exception)) # Field number 0 is illegal. self.assertRaises(message.DecodeError, msg.FromString, b'\3\4')
diff --git a/python/google/protobuf/internal/python_message.py b/python/google/protobuf/internal/python_message.py index 2921d5c..5550b42 100644 --- a/python/google/protobuf/internal/python_message.py +++ b/python/google/protobuf/internal/python_message.py
@@ -1479,7 +1479,7 @@ In order to support semantics like: - foo.bar.baz.qux = 23 + foo.bar.baz.moo = 23 assert foo.HasField('bar') ...child objects must have back references to their parents.
diff --git a/python/google/protobuf/internal/reflection_test.py b/python/google/protobuf/internal/reflection_test.py index 66dd0c7..62957d3 100644 --- a/python/google/protobuf/internal/reflection_test.py +++ b/python/google/protobuf/internal/reflection_test.py
@@ -1933,17 +1933,17 @@ def testDisconnectingInOneof(self): m = unittest_pb2.TestOneof2() # This message has two messages in a oneof. - m.foo_message.qux_int = 5 + m.foo_message.moo_int = 5 sub_message = m.foo_message # Accessing another message's field does not clear the first one - self.assertEqual(m.foo_lazy_message.qux_int, 0) - self.assertEqual(m.foo_message.qux_int, 5) + self.assertEqual(m.foo_lazy_message.moo_int, 0) + self.assertEqual(m.foo_message.moo_int, 5) # But mutating another message in the oneof detaches the first one. - m.foo_lazy_message.qux_int = 6 - self.assertEqual(m.foo_message.qux_int, 0) + m.foo_lazy_message.moo_int = 6 + self.assertEqual(m.foo_message.moo_int, 0) # The reference we got above was detached and is still valid. - self.assertEqual(sub_message.qux_int, 5) - sub_message.qux_int = 7 + self.assertEqual(sub_message.moo_int, 5) + sub_message.moo_int = 7 def assertInitialized(self, proto): self.assertTrue(proto.IsInitialized()) @@ -2020,7 +2020,7 @@ self.assertRaises(TypeError, proto.IsInitialized, 1, 2, 3) @unittest.skipIf( - api_implementation.Type() != 'cpp' or api_implementation.Version() != 2, + api_implementation.Type() == 'python', 'Errors are only available from the most recent C++ implementation.') def testFileDescriptorErrors(self): file_name = 'test_file_descriptor_errors.proto' @@ -3225,7 +3225,7 @@ class ClassAPITest(unittest.TestCase): @unittest.skipIf( - api_implementation.Type() == 'cpp' and api_implementation.Version() == 2, + api_implementation.Type() != 'python', 'C++ implementation requires a call to MakeDescriptor()') @testing_refleaks.SkipReferenceLeakChecker('MakeClass is not repeatable') def testMakeClassWithNestedDescriptor(self):
diff --git a/python/google/protobuf/internal/test_util.py b/python/google/protobuf/internal/test_util.py index a6e34ef..85284ce 100644 --- a/python/google/protobuf/internal/test_util.py +++ b/python/google/protobuf/internal/test_util.py
@@ -218,6 +218,7 @@ def SetAllFields(message): SetAllNonLazyFields(message) message.optional_lazy_message.bb = 127 + message.optional_unverified_lazy_message.bb = 128 def SetAllExtensions(message): @@ -257,6 +258,7 @@ extensions[pb2.optional_import_message_extension].d = 120 extensions[pb2.optional_public_import_message_extension].e = 126 extensions[pb2.optional_lazy_message_extension].bb = 127 + extensions[pb2.optional_unverified_lazy_message_extension].bb = 128 extensions[pb2.optional_nested_enum_extension] = pb2.TestAllTypes.BAZ extensions[pb2.optional_nested_enum_extension] = pb2.TestAllTypes.BAZ @@ -465,6 +467,7 @@ test_case.assertEqual(120, message.optional_import_message.d) test_case.assertEqual(126, message.optional_public_import_message.e) test_case.assertEqual(127, message.optional_lazy_message.bb) + test_case.assertEqual(128, message.optional_unverified_lazy_message.bb) test_case.assertEqual(unittest_pb2.TestAllTypes.BAZ, message.optional_nested_enum)
diff --git a/python/google/protobuf/internal/testing_refleaks.py b/python/google/protobuf/internal/testing_refleaks.py index abe88ed..445406a 100644 --- a/python/google/protobuf/internal/testing_refleaks.py +++ b/python/google/protobuf/internal/testing_refleaks.py
@@ -78,12 +78,23 @@ oldrefcount = 0 local_result = LocalTestResult(result) + num_flakes = 0 refcount_deltas = [] - for _ in range(self.NB_RUNS): + while len(refcount_deltas) < self.NB_RUNS: oldrefcount = self._getRefcounts() super(ReferenceLeakCheckerMixin, self).run(result=local_result) newrefcount = self._getRefcounts() + # If the GC was able to collect some objects after the call to run() that + # it could not collect before the call, then the counts won't match. + if newrefcount < oldrefcount and num_flakes < 2: + # This result is (probably) a flake -- garbage collectors aren't very + # predictable, but a lower ending refcount is the opposite of the + # failure we are testing for. If the result is repeatable, then we will + # eventually report it, but not after trying to eliminate it. + num_flakes += 1 + continue + num_flakes = 0 refcount_deltas.append(newrefcount - oldrefcount) print(refcount_deltas, self)
diff --git a/python/google/protobuf/internal/text_format_test.py b/python/google/protobuf/internal/text_format_test.py index ec1ad52..18b784e 100644 --- a/python/google/protobuf/internal/text_format_test.py +++ b/python/google/protobuf/internal/text_format_test.py
@@ -40,6 +40,7 @@ import unittest from google.protobuf import any_pb2 +from google.protobuf import struct_pb2 from google.protobuf import any_test_pb2 from google.protobuf import map_unittest_pb2 from google.protobuf import unittest_custom_options_pb2 @@ -48,6 +49,7 @@ from google.protobuf import unittest_proto3_arena_pb2 from google.protobuf import descriptor_pb2 from google.protobuf.internal import any_test_pb2 as test_extend_any +from google.protobuf.internal import api_implementation 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 @@ -582,6 +584,10 @@ text_format.Parse(expected_text, parsed_proto) self.assertEqual(message_proto, parsed_proto) + @unittest.skipIf( + api_implementation.Type() == 'upb', + "upb API doesn't support old UnknownField API. The TextFormat library " + "needs to convert to the new API.") def testPrintUnknownFieldsEmbeddedMessageInBytes(self, message_module): inner_msg = message_module.TestAllTypes() inner_msg.optional_int32 = 101 @@ -1470,9 +1476,11 @@ text = ('message_set {\n' ' [unknown_extension] {\n' ' i: 23\n' - ' bin: "\xe0"' + ' repeated_i: []\n' + ' bin: "\xe0"\n' ' [nested_unknown_ext]: {\n' ' i: 23\n' + ' repeated_i: [1, 2]\n' ' x: x\n' ' test: "test_string"\n' ' floaty_float: -0.315\n' @@ -1485,6 +1493,7 @@ ' i: 24\n' ' pointfloat: .3\n' ' test: "test_string"\n' + ' repeated_test: ["test_string1", "test_string2"]\n' ' floaty_float: -0.315\n' ' num: -inf\n' ' long_string: "test" "test2" \n' @@ -1931,6 +1940,16 @@ text_format.Merge(text, message) self.assertEqual(str(e.exception), '3:11 : Expected "}".') + def testParseExpandedAnyListValue(self): + any_msg = any_pb2.Any() + any_msg.Pack(struct_pb2.ListValue()) + msg = any_test_pb2.TestAny(any_value=any_msg) + text = ('any_value {\n' + ' [type.googleapis.com/google.protobuf.ListValue] {}\n' + '}\n') + parsed_msg = text_format.Parse(text, any_test_pb2.TestAny()) + self.assertEqual(msg, parsed_msg) + def testProto3Optional(self): msg = test_proto3_optional_pb2.TestProto3Optional() self.assertEqual(text_format.MessageToString(msg), '')
diff --git a/python/google/protobuf/internal/unknown_fields_test.py b/python/google/protobuf/internal/unknown_fields_test.py index e8caf6b..0459dba 100644 --- a/python/google/protobuf/internal/unknown_fields_test.py +++ b/python/google/protobuf/internal/unknown_fields_test.py
@@ -49,7 +49,7 @@ from google.protobuf.internal import type_checkers from google.protobuf.internal import wire_format from google.protobuf import descriptor - +from google.protobuf import unknown_fields try: import tracemalloc # pylint: disable=g-import-not-at-top except ImportError: @@ -106,14 +106,14 @@ proto = message_set_extensions_pb2.TestMessageSet() proto.MergeFromString(serialized) - unknown_fields = proto.UnknownFields() - self.assertEqual(len(unknown_fields), 1) + unknown_field_set = unknown_fields.UnknownFieldSet(proto) + self.assertEqual(len(unknown_field_set), 1) # Unknown field should have wire format data which can be parsed back to # original message. - self.assertEqual(unknown_fields[0].field_number, item.type_id) - self.assertEqual(unknown_fields[0].wire_type, + self.assertEqual(unknown_field_set[0].field_number, item.type_id) + self.assertEqual(unknown_field_set[0].wire_type, wire_format.WIRETYPE_LENGTH_DELIMITED) - d = unknown_fields[0].data + d = unknown_field_set[0].data message_new = message_set_extensions_pb2.TestMessageSetExtension1() message_new.ParseFromString(d) self.assertEqual(message1, message_new) @@ -196,11 +196,11 @@ decoder(memoryview(value), 0, len(value), self.all_fields, result_dict) self.assertEqual(expected_value, result_dict[field_descriptor]) - def CheckUnknownField(self, name, unknown_fields, expected_value): + def CheckUnknownField(self, name, unknown_field_set, expected_value): field_descriptor = self.descriptor.fields_by_name[name] expected_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[ field_descriptor.type] - for unknown_field in unknown_fields: + for unknown_field in unknown_field_set: if unknown_field.field_number == field_descriptor.number: self.assertEqual(expected_type, unknown_field.wire_type) if expected_type == 3: @@ -218,57 +218,57 @@ self.assertEqual(expected_value, unknown_field.data) def testCheckUnknownFieldValue(self): - unknown_fields = self.empty_message.UnknownFields() + unknown_field_set = unknown_fields.UnknownFieldSet(self.empty_message) # Test enum. self.CheckUnknownField('optional_nested_enum', - unknown_fields, + unknown_field_set, self.all_fields.optional_nested_enum) self.InternalCheckUnknownField('optional_nested_enum', self.all_fields.optional_nested_enum) # Test repeated enum. self.CheckUnknownField('repeated_nested_enum', - unknown_fields, + unknown_field_set, self.all_fields.repeated_nested_enum) self.InternalCheckUnknownField('repeated_nested_enum', self.all_fields.repeated_nested_enum) # Test varint. self.CheckUnknownField('optional_int32', - unknown_fields, + unknown_field_set, self.all_fields.optional_int32) self.InternalCheckUnknownField('optional_int32', self.all_fields.optional_int32) # Test fixed32. self.CheckUnknownField('optional_fixed32', - unknown_fields, + unknown_field_set, self.all_fields.optional_fixed32) self.InternalCheckUnknownField('optional_fixed32', self.all_fields.optional_fixed32) # Test fixed64. self.CheckUnknownField('optional_fixed64', - unknown_fields, + unknown_field_set, self.all_fields.optional_fixed64) self.InternalCheckUnknownField('optional_fixed64', self.all_fields.optional_fixed64) # Test length delimited. self.CheckUnknownField('optional_string', - unknown_fields, + unknown_field_set, self.all_fields.optional_string.encode('utf-8')) self.InternalCheckUnknownField('optional_string', self.all_fields.optional_string) # Test group. self.CheckUnknownField('optionalgroup', - unknown_fields, + unknown_field_set, (17, 0, 117)) self.InternalCheckUnknownField('optionalgroup', self.all_fields.optionalgroup) - self.assertEqual(97, len(unknown_fields)) + self.assertEqual(98, len(unknown_field_set)) def testCopyFrom(self): message = unittest_pb2.TestEmptyMessage() @@ -286,18 +286,14 @@ message.optional_int64 = 3 message.optional_uint32 = 4 destination = unittest_pb2.TestEmptyMessage() - unknown_fields = destination.UnknownFields() - self.assertEqual(0, len(unknown_fields)) + unknown_field_set = unknown_fields.UnknownFieldSet(destination) + self.assertEqual(0, len(unknown_field_set)) destination.ParseFromString(message.SerializeToString()) - # ParseFromString clears the message thus unknown fields is invalid. - with self.assertRaises(ValueError) as context: - len(unknown_fields) - self.assertIn('UnknownFields does not exist.', - str(context.exception)) - unknown_fields = destination.UnknownFields() - self.assertEqual(2, len(unknown_fields)) + self.assertEqual(0, len(unknown_field_set)) + unknown_field_set = unknown_fields.UnknownFieldSet(destination) + self.assertEqual(2, len(unknown_field_set)) destination.MergeFrom(source) - self.assertEqual(4, len(unknown_fields)) + self.assertEqual(2, len(unknown_field_set)) # Check that the fields where correctly merged, even stored in the unknown # fields set. message.ParseFromString(destination.SerializeToString()) @@ -306,14 +302,11 @@ self.assertEqual(message.optional_int64, 3) def testClear(self): - unknown_fields = self.empty_message.UnknownFields() + unknown_field_set = unknown_fields.UnknownFieldSet(self.empty_message) self.empty_message.Clear() # All cleared, even unknown fields. self.assertEqual(self.empty_message.SerializeToString(), b'') - with self.assertRaises(ValueError) as context: - len(unknown_fields) - self.assertIn('UnknownFields does not exist.', - str(context.exception)) + self.assertEqual(len(unknown_field_set), 98) @unittest.skipIf((sys.version_info.major, sys.version_info.minor) < (3, 4), 'tracemalloc requires python 3.4+') @@ -323,7 +316,7 @@ def leaking_function(): for _ in range(nb_leaks): - self.empty_message.UnknownFields() + unknown_fields.UnknownFieldSet(self.empty_message) tracemalloc.start() snapshot1 = tracemalloc.take_snapshot() @@ -340,49 +333,39 @@ message.optionalgroup.a = 123 destination = unittest_pb2.TestEmptyMessage() destination.ParseFromString(message.SerializeToString()) - sub_unknown_fields = destination.UnknownFields()[0].data + sub_unknown_fields = unknown_fields.UnknownFieldSet(destination)[0].data self.assertEqual(1, len(sub_unknown_fields)) self.assertEqual(sub_unknown_fields[0].data, 123) destination.Clear() - with self.assertRaises(ValueError) as context: - len(sub_unknown_fields) - self.assertIn('UnknownFields does not exist.', - str(context.exception)) - with self.assertRaises(ValueError) as context: - # pylint: disable=pointless-statement - sub_unknown_fields[0] - self.assertIn('UnknownFields does not exist.', - str(context.exception)) + self.assertEqual(1, len(sub_unknown_fields)) + self.assertEqual(sub_unknown_fields[0].data, 123) message.Clear() message.optional_uint32 = 456 nested_message = unittest_pb2.NestedTestAllTypes() nested_message.payload.optional_nested_message.ParseFromString( message.SerializeToString()) - unknown_fields = ( - nested_message.payload.optional_nested_message.UnknownFields()) - self.assertEqual(unknown_fields[0].data, 456) + unknown_field_set = unknown_fields.UnknownFieldSet( + nested_message.payload.optional_nested_message) + self.assertEqual(unknown_field_set[0].data, 456) nested_message.ClearField('payload') - self.assertEqual(unknown_fields[0].data, 456) - unknown_fields = ( - nested_message.payload.optional_nested_message.UnknownFields()) - self.assertEqual(0, len(unknown_fields)) + self.assertEqual(unknown_field_set[0].data, 456) + unknown_field_set = unknown_fields.UnknownFieldSet( + nested_message.payload.optional_nested_message) + self.assertEqual(0, len(unknown_field_set)) def testUnknownField(self): message = unittest_pb2.TestAllTypes() message.optional_int32 = 123 destination = unittest_pb2.TestEmptyMessage() destination.ParseFromString(message.SerializeToString()) - unknown_field = destination.UnknownFields()[0] + unknown_field = unknown_fields.UnknownFieldSet(destination)[0] destination.Clear() - with self.assertRaises(ValueError) as context: - unknown_field.data # pylint: disable=pointless-statement - self.assertIn('The parent message might be cleared.', - str(context.exception)) + self.assertEqual(unknown_field.data, 123) def testUnknownExtensions(self): message = unittest_pb2.TestEmptyMessageWithExtensions() message.ParseFromString(self.all_fields_data) - self.assertEqual(len(message.UnknownFields()), 97) + self.assertEqual(len(unknown_fields.UnknownFieldSet(message)), 98) self.assertEqual(message.SerializeToString(), self.all_fields_data) @@ -416,9 +399,10 @@ def CheckUnknownField(self, name, expected_value): field_descriptor = self.descriptor.fields_by_name[name] - unknown_fields = self.missing_message.UnknownFields() + unknown_field_set = unknown_fields.UnknownFieldSet(self.missing_message) + self.assertIsInstance(unknown_field_set, unknown_fields.UnknownFieldSet) count = 0 - for field in unknown_fields: + for field in unknown_field_set: if field.field_number == field_descriptor.number: count += 1 if field_descriptor.label == descriptor.FieldDescriptor.LABEL_REPEATED: @@ -458,8 +442,8 @@ self.assertEqual([], self.missing_message.packed_nested_enum) def testCheckUnknownFieldValueForEnum(self): - unknown_fields = self.missing_message.UnknownFields() - self.assertEqual(len(unknown_fields), 5) + unknown_field_set = unknown_fields.UnknownFieldSet(self.missing_message) + self.assertEqual(len(unknown_field_set), 5) self.CheckUnknownField('optional_nested_enum', self.message.optional_nested_enum) self.CheckUnknownField('repeated_nested_enum',
diff --git a/python/google/protobuf/internal/well_known_types.py b/python/google/protobuf/internal/well_known_types.py index b581ab7..8881d75 100644 --- a/python/google/protobuf/internal/well_known_types.py +++ b/python/google/protobuf/internal/well_known_types.py
@@ -868,6 +868,7 @@ collections.abc.MutableSequence.register(ListValue) +# LINT.IfChange(wktbases) WKTBASES = { 'google.protobuf.Any': Any, 'google.protobuf.Duration': Duration, @@ -876,3 +877,4 @@ 'google.protobuf.Struct': Struct, 'google.protobuf.Timestamp': Timestamp, } +# LINT.ThenChange(//depot/google.protobuf/compiler/python/pyi_generator.cc:wktbases)
diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py index 3912901..a32459a 100644 --- a/python/google/protobuf/internal/well_known_types_test.py +++ b/python/google/protobuf/internal/well_known_types_test.py
@@ -426,7 +426,7 @@ mask = field_mask_pb2.FieldMask() msg_descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR mask.AllFieldsFromDescriptor(msg_descriptor) - self.assertEqual(75, len(mask.paths)) + self.assertEqual(76, len(mask.paths)) self.assertTrue(mask.IsValidForDescriptor(msg_descriptor)) for field in msg_descriptor.fields: self.assertTrue(field.name in mask.paths) @@ -657,9 +657,9 @@ # Test Merge oneof field. new_msg = unittest_pb2.TestOneof2() dst = unittest_pb2.TestOneof2() - dst.foo_message.qux_int = 1 + dst.foo_message.moo_int = 1 mask = field_mask_pb2.FieldMask() - mask.FromJsonString('fooMessage,fooLazyMessage.quxInt') + mask.FromJsonString('fooMessage,fooLazyMessage.mooInt') mask.MergeMessage(new_msg, dst) self.assertTrue(dst.HasField('foo_message')) self.assertFalse(dst.HasField('foo_lazy_message'))
diff --git a/python/google/protobuf/message_factory.py b/python/google/protobuf/message_factory.py index 3656fa6..8d65204 100644 --- a/python/google/protobuf/message_factory.py +++ b/python/google/protobuf/message_factory.py
@@ -43,10 +43,10 @@ from google.protobuf import descriptor_pool from google.protobuf import message -if api_implementation.Type() == 'cpp': - from google.protobuf.pyext import cpp_message as message_impl -else: +if api_implementation.Type() == 'python': from google.protobuf.internal import python_message as message_impl +else: + from google.protobuf.pyext import cpp_message as message_impl # pylint: disable=g-import-not-at-top # The type of all Message classes. @@ -118,6 +118,8 @@ self.GetPrototype(extension.containing_type) extended_class = self._classes[extension.containing_type] extended_class.RegisterExtension(extension) + if extension.message_type: + self.GetPrototype(extension.message_type) return result_class def GetMessages(self, files): @@ -154,6 +156,8 @@ self.GetPrototype(extension.containing_type) extended_class = self._classes[extension.containing_type] extended_class.RegisterExtension(extension) + if extension.message_type: + self.GetPrototype(extension.message_type) return result
diff --git a/python/google/protobuf/pyext/cpp_message.py b/python/google/protobuf/pyext/cpp_message.py index fc8eb32..ca29029 100644 --- a/python/google/protobuf/pyext/cpp_message.py +++ b/python/google/protobuf/pyext/cpp_message.py
@@ -36,7 +36,14 @@ __author__ = 'tibell@google.com (Johan Tibell)' -from google.protobuf.pyext import _message +from google.protobuf.internal import api_implementation + + +# pylint: disable=protected-access +_message = api_implementation._c_module +# TODO(jieluo): Remove this import after fix api_implementation +if _message is None: + from google.protobuf.pyext import _message class GeneratedProtocolMessageType(_message.MessageMeta):
diff --git a/python/google/protobuf/pyext/extension_dict.cc b/python/google/protobuf/pyext/extension_dict.cc index 692029f..66703da 100644 --- a/python/google/protobuf/pyext/extension_dict.cc +++ b/python/google/protobuf/pyext/extension_dict.cc
@@ -331,7 +331,7 @@ } bool equals = false; if (PyObject_TypeCheck(other, &ExtensionDict_Type)) { - equals = self->parent == reinterpret_cast<ExtensionDict*>(other)->parent;; + equals = self->parent == reinterpret_cast<ExtensionDict*>(other)->parent; } if (equals ^ (opid == Py_EQ)) { Py_RETURN_FALSE;
diff --git a/python/google/protobuf/pyext/map_container.cc b/python/google/protobuf/pyext/map_container.cc index 4d516d2..e8a6888 100644 --- a/python/google/protobuf/pyext/map_container.cc +++ b/python/google/protobuf/pyext/map_container.cc
@@ -264,7 +264,7 @@ case FieldDescriptor::CPPTYPE_BOOL: { GOOGLE_CHECK_GET_BOOL(obj, value, false); value_ref->SetBoolValue(value); - return true;; + return true; } case FieldDescriptor::CPPTYPE_STRING: { std::string str;
diff --git a/python/google/protobuf/pyext/message.cc b/python/google/protobuf/pyext/message.cc index 920c17d..2c4a957 100644 --- a/python/google/protobuf/pyext/message.cc +++ b/python/google/protobuf/pyext/message.cc
@@ -68,6 +68,7 @@ #include <google/protobuf/pyext/repeated_scalar_container.h> #include <google/protobuf/pyext/safe_numerics.h> #include <google/protobuf/pyext/scoped_pyobject_ptr.h> +#include <google/protobuf/pyext/unknown_field_set.h> #include <google/protobuf/pyext/unknown_fields.h> #include <google/protobuf/util/message_differencer.h> #include <google/protobuf/io/strtod.h> @@ -2424,7 +2425,7 @@ return reinterpret_cast<PyObject*>(extension_dict); } -static PyObject* UnknownFieldSet(CMessage* self) { +static PyObject* GetUnknownFields(CMessage* self) { if (self->unknown_field_set == nullptr) { self->unknown_field_set = unknown_fields::NewPyUnknownFields(self); } else { @@ -2493,7 +2494,7 @@ "Serializes the message to a string, only for initialized messages."}, {"SetInParent", (PyCFunction)SetInParent, METH_NOARGS, "Sets the has bit of the given field in its parent message."}, - {"UnknownFields", (PyCFunction)UnknownFieldSet, METH_NOARGS, + {"UnknownFields", (PyCFunction)GetUnknownFields, METH_NOARGS, "Parse unknown field set"}, {"WhichOneof", (PyCFunction)WhichOneof, METH_O, "Returns the name of the field set inside a oneof, " @@ -2970,15 +2971,20 @@ return false; } + if (PyType_Ready(&PyUnknownFieldSet_Type) < 0) { + return false; + } + PyModule_AddObject(m, "UnknownFieldSet", - reinterpret_cast<PyObject*>(&PyUnknownFields_Type)); + reinterpret_cast<PyObject*>(&PyUnknownFieldSet_Type)); if (PyType_Ready(&PyUnknownFieldRef_Type) < 0) { return false; } - PyModule_AddObject(m, "UnknownField", - reinterpret_cast<PyObject*>(&PyUnknownFieldRef_Type)); + if (PyType_Ready(&PyUnknownField_Type) < 0) { + return false; + } // Initialize Map container types. if (!InitMapContainers()) {
diff --git a/python/google/protobuf/pyext/unknown_field_set.cc b/python/google/protobuf/pyext/unknown_field_set.cc new file mode 100644 index 0000000..42f9bbc --- /dev/null +++ b/python/google/protobuf/pyext/unknown_field_set.cc
@@ -0,0 +1,355 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include <google/protobuf/pyext/unknown_field_set.h> + +#define PY_SSIZE_T_CLEAN +#include <Python.h> + +#include <memory> +#include <set> + +#include <google/protobuf/message.h> +#include <google/protobuf/unknown_field_set.h> +#include <google/protobuf/wire_format_lite.h> +#include <google/protobuf/pyext/message.h> +#include <google/protobuf/pyext/scoped_pyobject_ptr.h> + +namespace google { +namespace protobuf { +namespace python { + +namespace unknown_field_set { + +static Py_ssize_t Len(PyObject* pself) { + PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>(pself); + if (self->fields == nullptr) { + PyErr_Format(PyExc_ValueError, "UnknownFieldSet does not exist. "); + return -1; + } + return self->fields->field_count(); +} + +PyObject* NewPyUnknownField(PyUnknownFieldSet* parent, Py_ssize_t index); + +static PyObject* Item(PyObject* pself, Py_ssize_t index) { + PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>(pself); + if (self->fields == nullptr) { + PyErr_Format(PyExc_ValueError, "UnknownFieldSet does not exist. "); + return nullptr; + } + Py_ssize_t total_size = self->fields->field_count(); + if (index < 0) { + index = total_size + index; + } + if (index < 0 || index >= total_size) { + PyErr_Format(PyExc_IndexError, "index (%zd) out of range", index); + return nullptr; + } + return unknown_field_set::NewPyUnknownField(self, index); +} + +PyObject* New(PyTypeObject* type, PyObject* args, PyObject* kwargs) { + if (args == nullptr || PyTuple_Size(args) != 1) { + PyErr_SetString(PyExc_TypeError, + "Must provide a message to create UnknownFieldSet"); + return nullptr; + } + + PyObject* c_message; + if (!PyArg_ParseTuple(args, "O", &c_message)) { + PyErr_SetString(PyExc_TypeError, + "Must provide a message to create UnknownFieldSet"); + return nullptr; + } + + if (!PyObject_TypeCheck(c_message, CMessage_Type)) { + PyErr_Format(PyExc_TypeError, + "Parameter to UnknownFieldSet() must be a message " + "got %s.", + Py_TYPE(c_message)->tp_name); + return nullptr; + } + + PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>( + PyType_GenericAlloc(&PyUnknownFieldSet_Type, 0)); + if (self == nullptr) { + return nullptr; + } + + // Top UnknownFieldSet should set parent nullptr. + self->parent = nullptr; + + // Copy c_message's UnknownFieldSet. + Message* message = reinterpret_cast<CMessage*>(c_message)->message; + const Reflection* reflection = message->GetReflection(); + self->fields = new google::protobuf::UnknownFieldSet; + self->fields->MergeFrom(reflection->GetUnknownFields(*message)); + return reinterpret_cast<PyObject*>(self); +} + +PyObject* NewPyUnknownField(PyUnknownFieldSet* parent, Py_ssize_t index) { + PyUnknownField* self = reinterpret_cast<PyUnknownField*>( + PyType_GenericAlloc(&PyUnknownField_Type, 0)); + if (self == nullptr) { + return nullptr; + } + + Py_INCREF(parent); + self->parent = parent; + self->index = index; + + return reinterpret_cast<PyObject*>(self); +} + +static void Dealloc(PyObject* pself) { + PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>(pself); + if (self->parent == nullptr) { + delete self->fields; + } else { + Py_CLEAR(self->parent); + } + auto* py_type = Py_TYPE(pself); + self->~PyUnknownFieldSet(); + py_type->tp_free(pself); +} + +static PySequenceMethods SqMethods = { + Len, /* sq_length */ + nullptr, /* sq_concat */ + nullptr, /* sq_repeat */ + Item, /* sq_item */ + nullptr, /* sq_slice */ + nullptr, /* sq_ass_item */ +}; + +} // namespace unknown_field_set + +PyTypeObject PyUnknownFieldSet_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME + ".PyUnknownFieldSet", // tp_name + sizeof(PyUnknownFieldSet), // tp_basicsize + 0, // tp_itemsize + unknown_field_set::Dealloc, // tp_dealloc +#if PY_VERSION_HEX < 0x03080000 + nullptr, // tp_print +#else + 0, // tp_vectorcall_offset +#endif + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare + nullptr, // tp_repr + nullptr, // tp_as_number + &unknown_field_set::SqMethods, // tp_as_sequence + nullptr, // tp_as_mapping + PyObject_HashNotImplemented, // tp_hash + nullptr, // tp_call + nullptr, // tp_str + nullptr, // tp_getattro + nullptr, // tp_setattro + nullptr, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "unknown field set", // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare + 0, // tp_weaklistoffset + nullptr, // tp_iter + nullptr, // tp_iternext + nullptr, // tp_methods + nullptr, // tp_members + nullptr, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set + 0, // tp_dictoffset + nullptr, // tp_init + nullptr, // tp_alloc + unknown_field_set::New, // tp_new +}; + +namespace unknown_field { +static PyObject* PyUnknownFieldSet_FromUnknownFieldSet( + PyUnknownFieldSet* parent, const UnknownFieldSet& fields) { + PyUnknownFieldSet* self = reinterpret_cast<PyUnknownFieldSet*>( + PyType_GenericAlloc(&PyUnknownFieldSet_Type, 0)); + if (self == nullptr) { + return nullptr; + } + + Py_INCREF(parent); + self->parent = parent; + self->fields = const_cast<UnknownFieldSet*>(&fields); + + return reinterpret_cast<PyObject*>(self); +} + +const UnknownField* GetUnknownField(PyUnknownField* self) { + const UnknownFieldSet* fields = self->parent->fields; + if (fields == nullptr) { + PyErr_Format(PyExc_ValueError, "UnknownField does not exist. "); + return nullptr; + } + Py_ssize_t total_size = fields->field_count(); + if (self->index >= total_size) { + PyErr_Format(PyExc_ValueError, "UnknownField does not exist. "); + return nullptr; + } + return &fields->field(self->index); +} + +static PyObject* GetFieldNumber(PyUnknownField* self, void* closure) { + const UnknownField* unknown_field = GetUnknownField(self); + if (unknown_field == nullptr) { + return nullptr; + } + return PyLong_FromLong(unknown_field->number()); +} + +using internal::WireFormatLite; +static PyObject* GetWireType(PyUnknownField* self, void* closure) { + const UnknownField* unknown_field = GetUnknownField(self); + if (unknown_field == nullptr) { + return nullptr; + } + + // 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()) { + case UnknownField::TYPE_VARINT: + wire_type = WireFormatLite::WIRETYPE_VARINT; + break; + case UnknownField::TYPE_FIXED32: + wire_type = WireFormatLite::WIRETYPE_FIXED32; + break; + case UnknownField::TYPE_FIXED64: + wire_type = WireFormatLite::WIRETYPE_FIXED64; + break; + case UnknownField::TYPE_LENGTH_DELIMITED: + wire_type = WireFormatLite::WIRETYPE_LENGTH_DELIMITED; + break; + case UnknownField::TYPE_GROUP: + wire_type = WireFormatLite::WIRETYPE_START_GROUP; + break; + } + return PyLong_FromLong(wire_type); +} + +static PyObject* GetData(PyUnknownField* self, void* closure) { + const UnknownField* field = GetUnknownField(self); + if (field == nullptr) { + return nullptr; + } + PyObject* data = nullptr; + switch (field->type()) { + case UnknownField::TYPE_VARINT: + data = PyLong_FromUnsignedLongLong(field->varint()); + break; + case UnknownField::TYPE_FIXED32: + data = PyLong_FromUnsignedLong(field->fixed32()); + break; + case UnknownField::TYPE_FIXED64: + data = PyLong_FromUnsignedLongLong(field->fixed64()); + break; + case UnknownField::TYPE_LENGTH_DELIMITED: + data = PyBytes_FromStringAndSize(field->length_delimited().data(), + field->GetLengthDelimitedSize()); + break; + case UnknownField::TYPE_GROUP: + data = + PyUnknownFieldSet_FromUnknownFieldSet(self->parent, field->group()); + break; + } + return data; +} + +static void Dealloc(PyObject* pself) { + PyUnknownField* self = reinterpret_cast<PyUnknownField*>(pself); + Py_CLEAR(self->parent); +} + +static PyGetSetDef Getters[] = { + {"field_number", (getter)GetFieldNumber, nullptr}, + {"wire_type", (getter)GetWireType, nullptr}, + {"data", (getter)GetData, nullptr}, + {nullptr}, +}; + +} // namespace unknown_field + +PyTypeObject PyUnknownField_Type = { + PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME + ".PyUnknownField", // tp_name + sizeof(PyUnknownField), // tp_basicsize + 0, // tp_itemsize + unknown_field::Dealloc, // tp_dealloc +#if PY_VERSION_HEX < 0x03080000 + nullptr, // tp_print +#else + 0, // tp_vectorcall_offset +#endif + nullptr, // tp_getattr + nullptr, // tp_setattr + nullptr, // tp_compare + nullptr, // tp_repr + nullptr, // tp_as_number + nullptr, // tp_as_sequence + nullptr, // tp_as_mapping + PyObject_HashNotImplemented, // tp_hash + nullptr, // tp_call + nullptr, // tp_str + nullptr, // tp_getattro + nullptr, // tp_setattro + nullptr, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + "unknown field", // tp_doc + nullptr, // tp_traverse + nullptr, // tp_clear + nullptr, // tp_richcompare + 0, // tp_weaklistoffset + nullptr, // tp_iter + nullptr, // tp_iternext + nullptr, // tp_methods + nullptr, // tp_members + unknown_field::Getters, // tp_getset + nullptr, // tp_base + nullptr, // tp_dict + nullptr, // tp_descr_get + nullptr, // tp_descr_set + 0, // tp_dictoffset + nullptr, // tp_init +}; + +} // namespace python +} // namespace protobuf +} // namespace google
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h b/python/google/protobuf/pyext/unknown_field_set.h similarity index 63% copy from src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h copy to python/google/protobuf/pyext/unknown_field_set.h index 8086005..3fa764d 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h +++ b/python/google/protobuf/pyext/unknown_field_set.h
@@ -28,37 +28,51 @@ // (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: seongkim@google.com (Seong Beom Kim) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. +#ifndef GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELD_SET_H__ +#define GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELD_SET_H__ -#ifndef GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__ -#define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__ +#define PY_SSIZE_T_CLEAN +#include <Python.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <memory> +#include <set> + +#include <google/protobuf/pyext/message.h> namespace google { namespace protobuf { -namespace compiler { -namespace cpp { -class MessageSCCAnalyzer; +class UnknownField; +class UnknownFieldSet; -// Provides an abstract interface to optimize message layout -// by rearranging the fields of a message. -class MessageLayoutHelper { - public: - virtual ~MessageLayoutHelper() {} +namespace python { +struct CMessage; - virtual void OptimizeLayout(std::vector<const FieldDescriptor*>* fields, - const Options& options, - MessageSCCAnalyzer* scc_analyzer) = 0; +struct PyUnknownFieldSet { + PyObject_HEAD; + // If parent is nullptr, it is a top UnknownFieldSet. + PyUnknownFieldSet* parent; + + // Top UnknownFieldSet owns fields pointer. Sub UnknownFieldSet + // does not own fields pointer. + UnknownFieldSet* fields; }; -} // namespace cpp -} // namespace compiler +struct PyUnknownField { + PyObject_HEAD; + // Every Python PyUnknownField holds a reference to its parent + // PyUnknownFieldSet in order to keep it alive. + PyUnknownFieldSet* parent; + + // The UnknownField index in UnknownFieldSet. + Py_ssize_t index; +}; + +extern PyTypeObject PyUnknownFieldSet_Type; +extern PyTypeObject PyUnknownField_Type; + +} // namespace python } // namespace protobuf } // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__ +#endif // GOOGLE_PROTOBUF_PYTHON_CPP_UNKNOWN_FIELD_SET_H__
diff --git a/python/google/protobuf/text_format.py b/python/google/protobuf/text_format.py index 412385c..a6d8bcf 100644 --- a/python/google/protobuf/text_format.py +++ b/python/google/protobuf/text_format.py
@@ -53,6 +53,7 @@ from google.protobuf.internal import type_checkers from google.protobuf import descriptor from google.protobuf import text_encoding +from google.protobuf import unknown_fields # pylint: disable=g-import-not-at-top __all__ = ['MessageToString', 'Parse', 'PrintMessage', 'PrintField', @@ -136,8 +137,6 @@ Args: message: The protocol buffers message. as_utf8: Return unescaped Unicode for non-ASCII characters. - In Python 3 actual Unicode characters may appear as is in strings. - In Python 2 the return value will be valid UTF-8 rather than only ASCII. as_one_line: Don't introduce newlines between fields. use_short_repeated_primitives: Use short repeated format for primitives. pointy_brackets: If True, use angle brackets instead of curly braces for @@ -223,6 +222,36 @@ message_formatter=None, print_unknown_fields=False, force_colon=False): + """Convert the message to text format and write it to the out stream. + + Args: + message: The Message object to convert to text format. + out: A file handle to write the message to. + indent: The initial indent level for pretty print. + as_utf8: Return unescaped Unicode for non-ASCII characters. + as_one_line: Don't introduce newlines between fields. + use_short_repeated_primitives: Use short repeated format for primitives. + pointy_brackets: If True, use angle brackets instead of curly braces for + nesting. + use_index_order: If True, print fields of a proto message using the order + 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, 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. + use_field_number: If True, print field numbers instead of names. + descriptor_pool: A DescriptorPool used to resolve Any types. + 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. + 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. + """ printer = _Printer( out=out, indent=indent, as_utf8=as_utf8, as_one_line=as_one_line, @@ -347,8 +376,6 @@ out: To record the text format result. indent: The initial indent level for pretty print. as_utf8: Return unescaped Unicode for non-ASCII characters. - In Python 3 actual Unicode characters may appear as is in strings. - In Python 2 the return value will be valid UTF-8 rather than ASCII. as_one_line: Don't introduce newlines between fields. use_short_repeated_primitives: Use short repeated format for primitives. pointy_brackets: If True, use angle brackets instead of curly braces for @@ -454,12 +481,12 @@ self.PrintField(field, value) if self.print_unknown_fields: - self._PrintUnknownFields(message.UnknownFields()) + self._PrintUnknownFields(unknown_fields.UnknownFieldSet(message)) - def _PrintUnknownFields(self, unknown_fields): + def _PrintUnknownFields(self, unknown_field_set): """Print unknown fields.""" out = self.out - for field in unknown_fields: + for field in unknown_field_set: out.write(' ' * self.indent) out.write(str(field.field_number)) if field.wire_type == WIRETYPE_START_GROUP: @@ -859,7 +886,10 @@ expanded_any_end_token = '}' expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name, self.descriptor_pool) - if not expanded_any_sub_message: + # Direct comparison with None is used instead of implicit bool conversion + # to avoid false positives with falsy initial values, e.g. for + # google.protobuf.ListValue. + if expanded_any_sub_message is None: raise ParseError('Type %s not found in descriptor pool' % packed_type_name) while not tokenizer.TryConsume(expanded_any_end_token): @@ -1143,9 +1173,12 @@ # start with "{" or "<" which indicates the beginning of a message body. # If there is no ":" or there is a "{" or "<" after ":", this field has # to be a message or the input is ill-formed. - if tokenizer.TryConsume(':') and not tokenizer.LookingAt( - '{') and not tokenizer.LookingAt('<'): - _SkipFieldValue(tokenizer) + if tokenizer.TryConsume( + ':') and not tokenizer.LookingAt('{') and not tokenizer.LookingAt('<'): + if tokenizer.LookingAt('['): + _SkipRepeatedFieldValue(tokenizer) + else: + _SkipFieldValue(tokenizer) else: _SkipFieldMessage(tokenizer) @@ -1214,6 +1247,20 @@ raise ParseError('Invalid field value: ' + tokenizer.token) +def _SkipRepeatedFieldValue(tokenizer): + """Skips over a repeated field value. + + Args: + tokenizer: A tokenizer to parse the field value. + """ + tokenizer.Consume('[') + if not tokenizer.LookingAt(']'): + _SkipFieldValue(tokenizer) + while tokenizer.TryConsume(','): + _SkipFieldValue(tokenizer) + tokenizer.Consume(']') + + class Tokenizer(object): """Protocol buffer text representation tokenizer.
diff --git a/python/google/protobuf/unknown_fields.py b/python/google/protobuf/unknown_fields.py new file mode 100644 index 0000000..3bd8286 --- /dev/null +++ b/python/google/protobuf/unknown_fields.py
@@ -0,0 +1,120 @@ +# 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. + +"""Contains Unknown Fields APIs. + +Simple usage example: + unknown_field_set = UnknownFieldSet(message) + for unknown_field in unknown_field_set: + wire_type = unknown_field.wire_type + field_number = unknown_field.field_number + data = unknown_field.data +""" + + +from google.protobuf.internal import api_implementation + +if api_implementation._c_module is not None: # pylint: disable=protected-access + UnknownFieldSet = api_implementation._c_module.UnknownFieldSet # pylint: disable=protected-access +else: + from google.protobuf.internal import decoder # pylint: disable=g-import-not-at-top + from google.protobuf.internal import wire_format # pylint: disable=g-import-not-at-top + + class UnknownField: + """A parsed unknown field.""" + + # Disallows assignment to other attributes. + __slots__ = ['_field_number', '_wire_type', '_data'] + + def __init__(self, field_number, wire_type, data): + self._field_number = field_number + self._wire_type = wire_type + self._data = data + return + + @property + def field_number(self): + return self._field_number + + @property + def wire_type(self): + return self._wire_type + + @property + def data(self): + return self._data + + class UnknownFieldSet: + """UnknownField container.""" + + # Disallows assignment to other attributes. + __slots__ = ['_values'] + + def __init__(self, msg): + + def InternalAdd(field_number, wire_type, data): + unknown_field = UnknownField(field_number, wire_type, data) + self._values.append(unknown_field) + + self._values = [] + msg_des = msg.DESCRIPTOR + # pylint: disable=protected-access + unknown_fields = msg._unknown_fields + if (msg_des.has_options and + msg_des.GetOptions().message_set_wire_format): + local_decoder = decoder.UnknownMessageSetItemDecoder() + for _, buffer in unknown_fields: + (field_number, data) = local_decoder(memoryview(buffer)) + InternalAdd(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED, data) + else: + for tag_bytes, buffer in unknown_fields: + # pylint: disable=protected-access + (tag, _) = decoder._DecodeVarint(tag_bytes, 0) + field_number, wire_type = wire_format.UnpackTag(tag) + if field_number == 0: + raise RuntimeError('Field number 0 is illegal.') + (data, _) = decoder._DecodeUnknownField( + memoryview(buffer), 0, wire_type) + InternalAdd(field_number, wire_type, data) + + def __getitem__(self, index): + size = len(self._values) + if index < 0: + index += size + if index < 0 or index >= size: + raise IndexError('index %d out of range'.index) + + return self._values[index] + + def __len__(self): + return len(self._values) + + def __iter__(self): + return iter(self._values)
diff --git a/python/setup.py b/python/setup.py index 1274761..cbb9a59 100755 --- a/python/setup.py +++ b/python/setup.py
@@ -115,8 +115,11 @@ GenProto('google/protobuf/internal/factory_test1.proto', False) GenProto('google/protobuf/internal/factory_test2.proto', False) GenProto('google/protobuf/internal/file_options_test.proto', False) - GenProto('google/protobuf/internal/import_test_package/import_public.proto', False) - GenProto('google/protobuf/internal/import_test_package/import_public_nested.proto', False) + GenProto('google/protobuf/internal/import_test_package/import_public.proto', + False) + GenProto( + 'google/protobuf/internal/import_test_package/import_public_nested.proto', + False) GenProto('google/protobuf/internal/import_test_package/inner.proto', False) GenProto('google/protobuf/internal/import_test_package/outer.proto', False) GenProto('google/protobuf/internal/missing_enum_values.proto', False)
diff --git a/ruby/lib/google/protobuf/repeated_field.rb b/ruby/lib/google/protobuf/repeated_field.rb index bc9699f..13b9300 100644 --- a/ruby/lib/google/protobuf/repeated_field.rb +++ b/ruby/lib/google/protobuf/repeated_field.rb
@@ -79,12 +79,25 @@ def first(n=nil) - n ? self[0...n] : self[0] + if n.nil? + return self[0] + elsif n < 0 + raise ArgumentError, "negative array size" + else + return self[0...n] + end end def last(n=nil) - n ? self[(self.size-n-1)..-1] : self[-1] + if n.nil? + return self[-1] + elsif n < 0 + raise ArgumentError, "negative array size" + else + start = [self.size-n, 0].max + return self[start...self.size] + end end
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 bfe7ec3..c09fe92 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptor.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptor.java
@@ -35,6 +35,8 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.OneofDescriptor; +import java.util.HashMap; +import java.util.Map; import org.jruby.*; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; @@ -44,182 +46,186 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; -import java.util.HashMap; -import java.util.Map; - - @JRubyClass(name = "Descriptor", include = "Enumerable") public class RubyDescriptor extends RubyObject { - public static void createRubyDescriptor(Ruby runtime) { - RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); - RubyClass cDescriptor = protobuf.defineClassUnder("Descriptor", runtime.getObject(), new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + public static void createRubyDescriptor(Ruby runtime) { + RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cDescriptor = + protobuf.defineClassUnder( + "Descriptor", + runtime.getObject(), + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new RubyDescriptor(runtime, klazz); - } - }); - cDescriptor.includeModule(runtime.getEnumerable()); - cDescriptor.defineAnnotatedMethods(RubyDescriptor.class); - cFieldDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::FieldDescriptor"); - cOneofDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::OneofDescriptor"); + } + }); + cDescriptor.includeModule(runtime.getEnumerable()); + cDescriptor.defineAnnotatedMethods(RubyDescriptor.class); + cFieldDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::FieldDescriptor"); + cOneofDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::OneofDescriptor"); + } + + public RubyDescriptor(Ruby runtime, RubyClass klazz) { + super(runtime, klazz); + } + + /* + * call-seq: + * Descriptor.name => name + * + * Returns the name of this message type as a fully-qualified string (e.g., + * My.Package.MessageType). + */ + @JRubyMethod(name = "name") + public IRubyObject getName(ThreadContext context) { + return name; + } + + /* + * call-seq: + * Descriptor.lookup(name) => FieldDescriptor + * + * Returns the field descriptor for the field with the given name, if present, + * or nil if none. + */ + @JRubyMethod + public IRubyObject lookup(ThreadContext context, IRubyObject fieldName) { + return Helpers.nullToNil(fieldDescriptors.get(fieldName), context.nil); + } + + /* + * call-seq: + * Descriptor.msgclass => message_klass + * + * Returns the Ruby class created for this message type. Valid only once the + * message type has been added to a pool. + */ + @JRubyMethod + public IRubyObject msgclass(ThreadContext context) { + return klazz; + } + + /* + * call-seq: + * Descriptor.each(&block) + * + * Iterates over fields in this message type, yielding to the block on each one. + */ + @JRubyMethod + public IRubyObject each(ThreadContext context, Block block) { + for (Map.Entry<IRubyObject, RubyFieldDescriptor> entry : fieldDescriptors.entrySet()) { + block.yield(context, entry.getValue()); + } + return context.nil; + } + + /* + * call-seq: + * Descriptor.file_descriptor + * + * Returns the FileDescriptor object this message belongs to. + */ + @JRubyMethod(name = "file_descriptor") + public IRubyObject getFileDescriptor(ThreadContext context) { + return RubyFileDescriptor.getRubyFileDescriptor(context, descriptor); + } + + /* + * call-seq: + * Descriptor.each_oneof(&block) => nil + * + * Invokes the given block for each oneof in this message type, passing the + * corresponding OneofDescriptor. + */ + @JRubyMethod(name = "each_oneof") + public IRubyObject eachOneof(ThreadContext context, Block block) { + for (RubyOneofDescriptor oneofDescriptor : oneofDescriptors.values()) { + block.yieldSpecific(context, oneofDescriptor); + } + return context.nil; + } + + /* + * call-seq: + * Descriptor.lookup_oneof(name) => OneofDescriptor + * + * Returns the oneof descriptor for the oneof with the given name, if present, + * or nil if none. + */ + @JRubyMethod(name = "lookup_oneof") + public IRubyObject lookupOneof(ThreadContext context, IRubyObject name) { + return Helpers.nullToNil(oneofDescriptors.get(Utils.symToString(name)), context.nil); + } + + protected FieldDescriptor getField(String name) { + return descriptor.findFieldByName(name); + } + + protected void setDescriptor( + ThreadContext context, Descriptor descriptor, RubyDescriptorPool pool) { + Ruby runtime = context.runtime; + Map<FieldDescriptor, RubyFieldDescriptor> cache = new HashMap(); + this.descriptor = descriptor; + + // Populate the field caches + fieldDescriptors = new HashMap<IRubyObject, RubyFieldDescriptor>(); + oneofDescriptors = new HashMap<IRubyObject, RubyOneofDescriptor>(); + + for (FieldDescriptor fieldDescriptor : descriptor.getFields()) { + RubyFieldDescriptor fd = + (RubyFieldDescriptor) cFieldDescriptor.newInstance(context, Block.NULL_BLOCK); + fd.setDescriptor(context, fieldDescriptor, pool); + fieldDescriptors.put(runtime.newString(fieldDescriptor.getName()), fd); + cache.put(fieldDescriptor, fd); } - public RubyDescriptor(Ruby runtime, RubyClass klazz) { - super(runtime, klazz); + for (OneofDescriptor oneofDescriptor : descriptor.getRealOneofs()) { + RubyOneofDescriptor ood = + (RubyOneofDescriptor) cOneofDescriptor.newInstance(context, Block.NULL_BLOCK); + ood.setDescriptor(context, oneofDescriptor, cache); + oneofDescriptors.put(runtime.newString(oneofDescriptor.getName()), ood); } - /* - * call-seq: - * Descriptor.name => name - * - * Returns the name of this message type as a fully-qualified string (e.g., - * My.Package.MessageType). - */ - @JRubyMethod(name = "name") - public IRubyObject getName(ThreadContext context) { - return name; - } + // Make sure our class is built + this.klazz = buildClassFromDescriptor(context); + } - /* - * call-seq: - * Descriptor.lookup(name) => FieldDescriptor - * - * Returns the field descriptor for the field with the given name, if present, - * or nil if none. - */ - @JRubyMethod - public IRubyObject lookup(ThreadContext context, IRubyObject fieldName) { - return Helpers.nullToNil(fieldDescriptors.get(fieldName), context.nil); - } + protected void setName(IRubyObject name) { + this.name = name; + } - /* - * call-seq: - * Descriptor.msgclass => message_klass - * - * Returns the Ruby class created for this message type. Valid only once the - * message type has been added to a pool. - */ - @JRubyMethod - public IRubyObject msgclass(ThreadContext context) { - return klazz; - } + private RubyClass buildClassFromDescriptor(ThreadContext context) { + Ruby runtime = context.runtime; - /* - * call-seq: - * Descriptor.each(&block) - * - * Iterates over fields in this message type, yielding to the block on each one. - */ - @JRubyMethod - public IRubyObject each(ThreadContext context, Block block) { - for (Map.Entry<IRubyObject, RubyFieldDescriptor> entry : fieldDescriptors.entrySet()) { - block.yield(context, entry.getValue()); - } - return context.nil; - } - - /* - * call-seq: - * Descriptor.file_descriptor - * - * Returns the FileDescriptor object this message belongs to. - */ - @JRubyMethod(name = "file_descriptor") - public IRubyObject getFileDescriptor(ThreadContext context) { - return RubyFileDescriptor.getRubyFileDescriptor(context, descriptor); - } - - /* - * call-seq: - * Descriptor.each_oneof(&block) => nil - * - * Invokes the given block for each oneof in this message type, passing the - * corresponding OneofDescriptor. - */ - @JRubyMethod(name = "each_oneof") - public IRubyObject eachOneof(ThreadContext context, Block block) { - for (RubyOneofDescriptor oneofDescriptor : oneofDescriptors.values()) { - block.yieldSpecific(context, oneofDescriptor); - } - return context.nil; - } - - /* - * call-seq: - * Descriptor.lookup_oneof(name) => OneofDescriptor - * - * Returns the oneof descriptor for the oneof with the given name, if present, - * or nil if none. - */ - @JRubyMethod(name = "lookup_oneof") - public IRubyObject lookupOneof(ThreadContext context, IRubyObject name) { - return Helpers.nullToNil(oneofDescriptors.get(Utils.symToString(name)), context.nil); - } - - protected FieldDescriptor getField(String name) { - return descriptor.findFieldByName(name); - } - - protected void setDescriptor(ThreadContext context, Descriptor descriptor, RubyDescriptorPool pool) { - Ruby runtime = context.runtime; - Map<FieldDescriptor, RubyFieldDescriptor> cache = new HashMap(); - this.descriptor = descriptor; - - // Populate the field caches - fieldDescriptors = new HashMap<IRubyObject, RubyFieldDescriptor>(); - oneofDescriptors = new HashMap<IRubyObject, RubyOneofDescriptor>(); - - for (FieldDescriptor fieldDescriptor : descriptor.getFields()) { - RubyFieldDescriptor fd = (RubyFieldDescriptor) cFieldDescriptor.newInstance(context, Block.NULL_BLOCK); - fd.setDescriptor(context, fieldDescriptor, pool); - fieldDescriptors.put(runtime.newString(fieldDescriptor.getName()), fd); - cache.put(fieldDescriptor, fd); - } - - for (OneofDescriptor oneofDescriptor : descriptor.getRealOneofs()) { - RubyOneofDescriptor ood = (RubyOneofDescriptor) cOneofDescriptor.newInstance(context, Block.NULL_BLOCK); - ood.setDescriptor(context, oneofDescriptor, cache); - oneofDescriptors.put(runtime.newString(oneofDescriptor.getName()), ood); - } - - // Make sure our class is built - this.klazz = buildClassFromDescriptor(context); - } - - protected void setName(IRubyObject name) { - this.name = name; - } - - private RubyClass buildClassFromDescriptor(ThreadContext context) { - Ruby runtime = context.runtime; - - ObjectAllocator allocator = new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby runtime, RubyClass klazz) { - return new RubyMessage(runtime, klazz, descriptor); - } + ObjectAllocator allocator = + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new RubyMessage(runtime, klazz, descriptor); + } }; - // rb_define_class_id - RubyClass klass = RubyClass.newClass(runtime, runtime.getObject()); - klass.setAllocator(allocator); - klass.makeMetaClass(runtime.getObject().getMetaClass()); - klass.inherit(runtime.getObject()); - RubyModule messageExts = runtime.getClassFromPath("Google::Protobuf::MessageExts"); - klass.include(new IRubyObject[] {messageExts}); - klass.instance_variable_set(runtime.newString(Utils.DESCRIPTOR_INSTANCE_VAR), this); - klass.defineAnnotatedMethods(RubyMessage.class); + // rb_define_class_id + RubyClass klass = RubyClass.newClass(runtime, runtime.getObject()); + klass.setAllocator(allocator); + klass.makeMetaClass(runtime.getObject().getMetaClass()); + klass.inherit(runtime.getObject()); + RubyModule messageExts = runtime.getClassFromPath("Google::Protobuf::MessageExts"); + klass.include(new IRubyObject[] {messageExts}); + klass.instance_variable_set(runtime.newString(Utils.DESCRIPTOR_INSTANCE_VAR), this); + klass.defineAnnotatedMethods(RubyMessage.class); // Workaround for https://github.com/jruby/jruby/issues/7154 klass.searchMethod("respond_to?").setIsBuiltin(false); - return klass; - } + return klass; + } - private static RubyClass cFieldDescriptor; - private static RubyClass cOneofDescriptor; + private static RubyClass cFieldDescriptor; + private static RubyClass cOneofDescriptor; - private Descriptor descriptor; - private IRubyObject name; - private Map<IRubyObject, RubyFieldDescriptor> fieldDescriptors; - private Map<IRubyObject, RubyOneofDescriptor> oneofDescriptors; - private RubyClass klazz; + private Descriptor descriptor; + private IRubyObject name; + private Map<IRubyObject, RubyFieldDescriptor> fieldDescriptors; + private Map<IRubyObject, RubyOneofDescriptor> oneofDescriptors; + private RubyClass klazz; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptorPool.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptorPool.java index 6cdb341..d65b412 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptorPool.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyDescriptorPool.java
@@ -38,6 +38,10 @@ import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.InvalidProtocolBufferException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.jruby.*; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; @@ -45,136 +49,147 @@ import org.jruby.runtime.*; import org.jruby.runtime.builtin.IRubyObject; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - @JRubyClass(name = "DescriptorPool") public class RubyDescriptorPool extends RubyObject { - public static void createRubyDescriptorPool(Ruby runtime) { - RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); - RubyClass cDescriptorPool = protobuf.defineClassUnder("DescriptorPool", runtime.getObject(), new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + public static void createRubyDescriptorPool(Ruby runtime) { + RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cDescriptorPool = + protobuf.defineClassUnder( + "DescriptorPool", + runtime.getObject(), + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new RubyDescriptorPool(runtime, klazz); - } - }); + } + }); - cDescriptorPool.defineAnnotatedMethods(RubyDescriptorPool.class); - descriptorPool = (RubyDescriptorPool) cDescriptorPool.newInstance(runtime.getCurrentContext(), Block.NULL_BLOCK); - cDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::Descriptor"); - cEnumDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::EnumDescriptor"); + cDescriptorPool.defineAnnotatedMethods(RubyDescriptorPool.class); + descriptorPool = + (RubyDescriptorPool) + cDescriptorPool.newInstance(runtime.getCurrentContext(), Block.NULL_BLOCK); + cDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::Descriptor"); + cEnumDescriptor = (RubyClass) runtime.getClassFromPath("Google::Protobuf::EnumDescriptor"); + } + + public RubyDescriptorPool(Ruby runtime, RubyClass klazz) { + super(runtime, klazz); + this.fileDescriptors = new ArrayList<>(); + this.symtab = new HashMap<IRubyObject, IRubyObject>(); + } + + @JRubyMethod + public IRubyObject build(ThreadContext context, Block block) { + RubyClass cBuilder = + (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::Internal::Builder"); + RubyBasicObject ctx = (RubyBasicObject) cBuilder.newInstance(context, this, Block.NULL_BLOCK); + ctx.instance_eval(context, block); + ctx.callMethod(context, "build"); // Needs to be called to support the deprecated syntax + return context.nil; + } + + /* + * call-seq: + * DescriptorPool.lookup(name) => descriptor + * + * Finds a Descriptor or EnumDescriptor by name and returns it, or nil if none + * exists with the given name. + * + * This currently lazy loads the ruby descriptor objects as they are requested. + * This allows us to leave the heavy lifting to the java library + */ + @JRubyMethod + public IRubyObject lookup(ThreadContext context, IRubyObject name) { + return Helpers.nullToNil(symtab.get(name), context.nil); + } + + /* + * call-seq: + * DescriptorPool.generated_pool => descriptor_pool + * + * Class method that returns the global DescriptorPool. This is a singleton into + * which generated-code message and enum types are registered. The user may also + * register types in this pool for convenience so that they do not have to hold + * a reference to a private pool instance. + */ + @JRubyMethod(meta = true, name = "generated_pool") + public static IRubyObject generatedPool(ThreadContext context, IRubyObject recv) { + return descriptorPool; + } + + @JRubyMethod(required = 1) + public IRubyObject add_serialized_file(ThreadContext context, IRubyObject data) { + byte[] bin = data.convertToString().getBytes(); + try { + FileDescriptorProto.Builder builder = FileDescriptorProto.newBuilder().mergeFrom(bin); + registerFileDescriptor(context, builder); + } catch (InvalidProtocolBufferException e) { + throw RaiseException.from( + context.runtime, + (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::ParseError"), + e.getMessage()); + } + return context.nil; + } + + protected void registerFileDescriptor( + ThreadContext context, FileDescriptorProto.Builder builder) { + final FileDescriptor fd; + try { + fd = FileDescriptor.buildFrom(builder.build(), existingFileDescriptors()); + } catch (DescriptorValidationException e) { + throw context.runtime.newRuntimeError(e.getMessage()); } - public RubyDescriptorPool(Ruby runtime, RubyClass klazz) { - super(runtime, klazz); - this.fileDescriptors = new ArrayList<>(); - this.symtab = new HashMap<IRubyObject, IRubyObject>(); + String packageName = fd.getPackage(); + if (!packageName.isEmpty()) { + packageName = packageName + "."; } - @JRubyMethod - public IRubyObject build(ThreadContext context, Block block) { - RubyClass cBuilder = (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::Internal::Builder"); - RubyBasicObject ctx = (RubyBasicObject) cBuilder.newInstance(context, this, Block.NULL_BLOCK); - ctx.instance_eval(context, block); - ctx.callMethod(context, "build"); // Needs to be called to support the deprecated syntax - return context.nil; - } + // Need to make sure enums are registered first in case anything references them + for (EnumDescriptor ed : fd.getEnumTypes()) registerEnumDescriptor(context, ed, packageName); + for (Descriptor message : fd.getMessageTypes()) + registerDescriptor(context, message, packageName); - /* - * call-seq: - * DescriptorPool.lookup(name) => descriptor - * - * Finds a Descriptor or EnumDescriptor by name and returns it, or nil if none - * exists with the given name. - * - * This currently lazy loads the ruby descriptor objects as they are requested. - * This allows us to leave the heavy lifting to the java library - */ - @JRubyMethod - public IRubyObject lookup(ThreadContext context, IRubyObject name) { - return Helpers.nullToNil(symtab.get(name), context.nil); - } + // Mark this as a loaded file + fileDescriptors.add(fd); + } - /* - * call-seq: - * DescriptorPool.generated_pool => descriptor_pool - * - * Class method that returns the global DescriptorPool. This is a singleton into - * which generated-code message and enum types are registered. The user may also - * register types in this pool for convenience so that they do not have to hold - * a reference to a private pool instance. - */ - @JRubyMethod(meta = true, name = "generated_pool") - public static IRubyObject generatedPool(ThreadContext context, IRubyObject recv) { - return descriptorPool; - } + private void registerDescriptor(ThreadContext context, Descriptor descriptor, String parentPath) { + String fullName = parentPath + descriptor.getName(); + String fullPath = fullName + "."; + RubyString name = context.runtime.newString(fullName); - @JRubyMethod(required = 1) - public IRubyObject add_serialized_file (ThreadContext context, IRubyObject data ) { - byte[] bin = data.convertToString().getBytes(); - try { - FileDescriptorProto.Builder builder = FileDescriptorProto.newBuilder().mergeFrom(bin); - registerFileDescriptor(context, builder); - } catch (InvalidProtocolBufferException e) { - throw RaiseException.from(context.runtime, (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::ParseError"), e.getMessage()); - } - return context.nil; - } + RubyDescriptor des = (RubyDescriptor) cDescriptor.newInstance(context, Block.NULL_BLOCK); + des.setName(name); + des.setDescriptor(context, descriptor, this); + symtab.put(name, des); - protected void registerFileDescriptor(ThreadContext context, FileDescriptorProto.Builder builder) { - final FileDescriptor fd; - try { - fd = FileDescriptor.buildFrom(builder.build(), existingFileDescriptors()); - } catch (DescriptorValidationException e) { - throw context.runtime.newRuntimeError(e.getMessage()); - } + // Need to make sure enums are registered first in case anything references them + for (EnumDescriptor ed : descriptor.getEnumTypes()) + registerEnumDescriptor(context, ed, fullPath); + for (Descriptor message : descriptor.getNestedTypes()) + registerDescriptor(context, message, fullPath); + } - String packageName = fd.getPackage(); - if (!packageName.isEmpty()) { - packageName = packageName + "."; - } + private void registerEnumDescriptor( + ThreadContext context, EnumDescriptor descriptor, String parentPath) { + RubyString name = context.runtime.newString(parentPath + descriptor.getName()); + RubyEnumDescriptor des = + (RubyEnumDescriptor) cEnumDescriptor.newInstance(context, Block.NULL_BLOCK); + des.setName(name); + des.setDescriptor(context, descriptor); + symtab.put(name, des); + } - // Need to make sure enums are registered first in case anything references them - for (EnumDescriptor ed : fd.getEnumTypes()) registerEnumDescriptor(context, ed, packageName); - for (Descriptor message : fd.getMessageTypes()) registerDescriptor(context, message, packageName); + private FileDescriptor[] existingFileDescriptors() { + return fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]); + } - // Mark this as a loaded file - fileDescriptors.add(fd); - } + private static RubyClass cDescriptor; + private static RubyClass cEnumDescriptor; + private static RubyDescriptorPool descriptorPool; - private void registerDescriptor(ThreadContext context, Descriptor descriptor, String parentPath) { - String fullName = parentPath + descriptor.getName(); - String fullPath = fullName + "."; - RubyString name = context.runtime.newString(fullName); - - RubyDescriptor des = (RubyDescriptor) cDescriptor.newInstance(context, Block.NULL_BLOCK); - des.setName(name); - des.setDescriptor(context, descriptor, this); - symtab.put(name, des); - - // Need to make sure enums are registered first in case anything references them - for (EnumDescriptor ed : descriptor.getEnumTypes()) registerEnumDescriptor(context, ed, fullPath); - for (Descriptor message : descriptor.getNestedTypes()) registerDescriptor(context, message, fullPath); - } - - private void registerEnumDescriptor(ThreadContext context, EnumDescriptor descriptor, String parentPath) { - RubyString name = context.runtime.newString(parentPath + descriptor.getName()); - RubyEnumDescriptor des = (RubyEnumDescriptor) cEnumDescriptor.newInstance(context, Block.NULL_BLOCK); - des.setName(name); - des.setDescriptor(context, descriptor); - symtab.put(name, des); - } - - private FileDescriptor[] existingFileDescriptors() { - return fileDescriptors.toArray(new FileDescriptor[fileDescriptors.size()]); - } - - private static RubyClass cDescriptor; - private static RubyClass cEnumDescriptor; - private static RubyDescriptorPool descriptorPool; - - private List<FileDescriptor> fileDescriptors; - private Map<IRubyObject, IRubyObject> symtab; + private List<FileDescriptor> fileDescriptors; + private Map<IRubyObject, IRubyObject> symtab; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyEnum.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyEnum.java index 17525df..95d961e 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyEnum.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyEnum.java
@@ -38,41 +38,41 @@ import org.jruby.runtime.builtin.IRubyObject; public class RubyEnum { - /* - * call-seq: - * Enum.lookup(number) => name - * - * This module method, provided on each generated enum module, looks up an enum - * value by number and returns its name as a Ruby symbol, or nil if not found. - */ - @JRubyMethod(meta = true) - public static IRubyObject lookup(ThreadContext context, IRubyObject recv, IRubyObject number) { - RubyEnumDescriptor rubyEnumDescriptor = (RubyEnumDescriptor) getDescriptor(context, recv); - return rubyEnumDescriptor.numberToName(context, number); - } + /* + * call-seq: + * Enum.lookup(number) => name + * + * This module method, provided on each generated enum module, looks up an enum + * value by number and returns its name as a Ruby symbol, or nil if not found. + */ + @JRubyMethod(meta = true) + public static IRubyObject lookup(ThreadContext context, IRubyObject recv, IRubyObject number) { + RubyEnumDescriptor rubyEnumDescriptor = (RubyEnumDescriptor) getDescriptor(context, recv); + return rubyEnumDescriptor.numberToName(context, number); + } - /* - * call-seq: - * Enum.resolve(name) => number - * - * This module method, provided on each generated enum module, looks up an enum - * value by name (as a Ruby symbol) and returns its name, or nil if not found. - */ - @JRubyMethod(meta = true) - public static IRubyObject resolve(ThreadContext context, IRubyObject recv, IRubyObject name) { - RubyEnumDescriptor rubyEnumDescriptor = (RubyEnumDescriptor) getDescriptor(context, recv); - return rubyEnumDescriptor.nameToNumber(context, name); - } + /* + * call-seq: + * Enum.resolve(name) => number + * + * This module method, provided on each generated enum module, looks up an enum + * value by name (as a Ruby symbol) and returns its name, or nil if not found. + */ + @JRubyMethod(meta = true) + public static IRubyObject resolve(ThreadContext context, IRubyObject recv, IRubyObject name) { + RubyEnumDescriptor rubyEnumDescriptor = (RubyEnumDescriptor) getDescriptor(context, recv); + return rubyEnumDescriptor.nameToNumber(context, name); + } - /* - * call-seq: - * Enum.descriptor - * - * This module method, provided on each generated enum module, returns the - * EnumDescriptor corresponding to this enum type. - */ - @JRubyMethod(meta = true, name = "descriptor") - public static IRubyObject getDescriptor(ThreadContext context, IRubyObject recv) { - return ((RubyModule) recv).getInstanceVariable(Utils.DESCRIPTOR_INSTANCE_VAR); - } + /* + * call-seq: + * Enum.descriptor + * + * This module method, provided on each generated enum module, returns the + * EnumDescriptor corresponding to this enum type. + */ + @JRubyMethod(meta = true, name = "descriptor") + public static IRubyObject getDescriptor(ThreadContext context, IRubyObject recv) { + return ((RubyModule) recv).getInstanceVariable(Utils.DESCRIPTOR_INSTANCE_VAR); + } }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyEnumDescriptor.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyEnumDescriptor.java index 26f00db..6532867 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyEnumDescriptor.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyEnumDescriptor.java
@@ -39,8 +39,8 @@ import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.RubyModule; -import org.jruby.RubyObject; import org.jruby.RubyNumeric; +import org.jruby.RubyObject; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.Block; @@ -50,132 +50,147 @@ @JRubyClass(name = "EnumDescriptor", include = "Enumerable") public class RubyEnumDescriptor extends RubyObject { - public static void createRubyEnumDescriptor(Ruby runtime) { - RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); - RubyClass cEnumDescriptor = mProtobuf.defineClassUnder("EnumDescriptor", runtime.getObject(), new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + public static void createRubyEnumDescriptor(Ruby runtime) { + RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cEnumDescriptor = + mProtobuf.defineClassUnder( + "EnumDescriptor", + runtime.getObject(), + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new RubyEnumDescriptor(runtime, klazz); - } - }); - cEnumDescriptor.includeModule(runtime.getEnumerable()); - cEnumDescriptor.defineAnnotatedMethods(RubyEnumDescriptor.class); + } + }); + cEnumDescriptor.includeModule(runtime.getEnumerable()); + cEnumDescriptor.defineAnnotatedMethods(RubyEnumDescriptor.class); + } + + public RubyEnumDescriptor(Ruby runtime, RubyClass klazz) { + super(runtime, klazz); + } + + /* + * call-seq: + * EnumDescriptor.name => name + * + * Returns the name of this enum type. + */ + @JRubyMethod(name = "name") + public IRubyObject getName(ThreadContext context) { + return this.name; + } + + /* + * call-seq: + * EnumDescriptor.each(&block) + * + * Iterates over key => value mappings in this enum's definition, yielding to + * the block with (key, value) arguments for each one. + */ + @JRubyMethod + public IRubyObject each(ThreadContext context, Block block) { + Ruby runtime = context.runtime; + for (EnumValueDescriptor enumValueDescriptor : descriptor.getValues()) { + block.yield( + context, + runtime.newArray( + runtime.newSymbol(enumValueDescriptor.getName()), + runtime.newFixnum(enumValueDescriptor.getNumber()))); + } + return context.nil; + } + + /* + * call-seq: + * EnumDescriptor.enummodule => module + * + * Returns the Ruby module corresponding to this enum type. Cannot be called + * until the enum descriptor has been added to a pool. + */ + @JRubyMethod + public IRubyObject enummodule(ThreadContext context) { + return module; + } + + /* + * call-seq: + * EnumDescriptor.file_descriptor + * + * Returns the FileDescriptor object this enum belongs to. + */ + @JRubyMethod(name = "file_descriptor") + public IRubyObject getFileDescriptor(ThreadContext context) { + return RubyFileDescriptor.getRubyFileDescriptor(context, descriptor); + } + + public boolean isValidValue(ThreadContext context, IRubyObject value) { + EnumValueDescriptor enumValue; + + if (Utils.isRubyNum(value)) { + enumValue = descriptor.findValueByNumberCreatingIfUnknown(RubyNumeric.num2int(value)); + } else { + enumValue = descriptor.findValueByName(value.asJavaString()); } - public RubyEnumDescriptor(Ruby runtime, RubyClass klazz) { - super(runtime, klazz); + return enumValue != null; + } + + protected IRubyObject nameToNumber(ThreadContext context, IRubyObject name) { + EnumValueDescriptor value = descriptor.findValueByName(name.asJavaString()); + return value == null ? context.nil : context.runtime.newFixnum(value.getNumber()); + } + + protected IRubyObject numberToName(ThreadContext context, IRubyObject number) { + EnumValueDescriptor value = descriptor.findValueByNumber(RubyNumeric.num2int(number)); + return value == null ? context.nil : context.runtime.newSymbol(value.getName()); + } + + protected void setDescriptor(ThreadContext context, EnumDescriptor descriptor) { + this.descriptor = descriptor; + this.module = buildModuleFromDescriptor(context); + } + + protected void setName(IRubyObject name) { + this.name = name; + } + + private RubyModule buildModuleFromDescriptor(ThreadContext context) { + Ruby runtime = context.runtime; + + RubyModule enumModule = RubyModule.newModule(runtime); + boolean defaultValueRequiredButNotFound = + descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO3; + for (EnumValueDescriptor value : descriptor.getValues()) { + String name = value.getName(); + // Make sure its a valid constant name before trying to create it + if (Character.isUpperCase(name.codePointAt(0))) { + enumModule.defineConstant(name, runtime.newFixnum(value.getNumber())); + } else { + runtime + .getWarnings() + .warn( + "Enum value " + + name + + " does not start with an uppercase letter as is required for Ruby" + + " constants."); + } + if (value.getNumber() == 0) { + defaultValueRequiredButNotFound = false; + } } - /* - * call-seq: - * EnumDescriptor.name => name - * - * Returns the name of this enum type. - */ - @JRubyMethod(name = "name") - public IRubyObject getName(ThreadContext context) { - return this.name; + if (defaultValueRequiredButNotFound) { + throw Utils.createTypeError( + context, "Enum definition " + name + " does not contain a value for '0'"); } + enumModule.instance_variable_set(runtime.newString(Utils.DESCRIPTOR_INSTANCE_VAR), this); + enumModule.defineAnnotatedMethods(RubyEnum.class); + return enumModule; + } - /* - * call-seq: - * EnumDescriptor.each(&block) - * - * Iterates over key => value mappings in this enum's definition, yielding to - * the block with (key, value) arguments for each one. - */ - @JRubyMethod - public IRubyObject each(ThreadContext context, Block block) { - Ruby runtime = context.runtime; - for (EnumValueDescriptor enumValueDescriptor : descriptor.getValues()) { - block.yield(context, runtime.newArray(runtime.newSymbol(enumValueDescriptor.getName()), - runtime.newFixnum(enumValueDescriptor.getNumber()))); - } - return context.nil; - } - - /* - * call-seq: - * EnumDescriptor.enummodule => module - * - * Returns the Ruby module corresponding to this enum type. Cannot be called - * until the enum descriptor has been added to a pool. - */ - @JRubyMethod - public IRubyObject enummodule(ThreadContext context) { - return module; - } - - /* - * call-seq: - * EnumDescriptor.file_descriptor - * - * Returns the FileDescriptor object this enum belongs to. - */ - @JRubyMethod(name = "file_descriptor") - public IRubyObject getFileDescriptor(ThreadContext context) { - return RubyFileDescriptor.getRubyFileDescriptor(context, descriptor); - } - - public boolean isValidValue(ThreadContext context, IRubyObject value) { - EnumValueDescriptor enumValue; - - if (Utils.isRubyNum(value)) { - enumValue = descriptor.findValueByNumberCreatingIfUnknown(RubyNumeric.num2int(value)); - } else { - enumValue = descriptor.findValueByName(value.asJavaString()); - } - - return enumValue != null; - } - - protected IRubyObject nameToNumber(ThreadContext context, IRubyObject name) { - EnumValueDescriptor value = descriptor.findValueByName(name.asJavaString()); - return value == null ? context.nil : context.runtime.newFixnum(value.getNumber()); - } - - protected IRubyObject numberToName(ThreadContext context, IRubyObject number) { - EnumValueDescriptor value = descriptor.findValueByNumber(RubyNumeric.num2int(number)); - return value == null ? context.nil : context.runtime.newSymbol(value.getName()); - } - - protected void setDescriptor(ThreadContext context, EnumDescriptor descriptor) { - this.descriptor = descriptor; - this.module = buildModuleFromDescriptor(context); - } - - protected void setName(IRubyObject name) { - this.name = name; - } - - private RubyModule buildModuleFromDescriptor(ThreadContext context) { - Ruby runtime = context.runtime; - - RubyModule enumModule = RubyModule.newModule(runtime); - boolean defaultValueRequiredButNotFound = descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO3; - for (EnumValueDescriptor value : descriptor.getValues()) { - String name = value.getName(); - // Make sure its a valid constant name before trying to create it - if (Character.isUpperCase(name.codePointAt(0))) { - enumModule.defineConstant(name, runtime.newFixnum(value.getNumber())); - } else { - runtime.getWarnings().warn("Enum value " + name + " does not start with an uppercase letter as is required for Ruby constants."); - } - if (value.getNumber() == 0) { - defaultValueRequiredButNotFound = false; - } - } - - if (defaultValueRequiredButNotFound) { - throw Utils.createTypeError(context, "Enum definition " + name + " does not contain a value for '0'"); - } - enumModule.instance_variable_set(runtime.newString(Utils.DESCRIPTOR_INSTANCE_VAR), this); - enumModule.defineAnnotatedMethods(RubyEnum.class); - return enumModule; - } - - private EnumDescriptor descriptor; - private EnumDescriptorProto.Builder builder; - private IRubyObject name; - private RubyModule module; + private EnumDescriptor descriptor; + private EnumDescriptorProto.Builder builder; + private IRubyObject name; + private RubyModule module; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java index e9594d8..bc1fe0c 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyFieldDescriptor.java
@@ -43,228 +43,237 @@ @JRubyClass(name = "FieldDescriptor") public class RubyFieldDescriptor extends RubyObject { - public static void createRubyFieldDescriptor(Ruby runtime) { - RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); - RubyClass cFieldDescriptor = mProtobuf.defineClassUnder("FieldDescriptor", runtime.getObject(), new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + public static void createRubyFieldDescriptor(Ruby runtime) { + RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cFieldDescriptor = + mProtobuf.defineClassUnder( + "FieldDescriptor", + runtime.getObject(), + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new RubyFieldDescriptor(runtime, klazz); - } - }); - cFieldDescriptor.defineAnnotatedMethods(RubyFieldDescriptor.class); + } + }); + cFieldDescriptor.defineAnnotatedMethods(RubyFieldDescriptor.class); + } + + public RubyFieldDescriptor(Ruby runtime, RubyClass klazz) { + super(runtime, klazz); + } + + /* + * call-seq: + * FieldDescriptor.default => default + * + * Returns this field's default, as a Ruby object, or nil if not yet set. + */ + // VALUE FieldDescriptor_default(VALUE _self) { + // DEFINE_SELF(FieldDescriptor, self, _self); + // return layout_get_default(self->fielddef); + // } + + /* + * call-seq: + * FieldDescriptor.label => label + * + * Returns this field's label (i.e., plurality), as a Ruby symbol. + * + * Valid field labels are: + * :optional, :repeated + */ + @JRubyMethod(name = "label") + public IRubyObject getLabel(ThreadContext context) { + if (label == null) { + calculateLabel(context); } + return label; + } - public RubyFieldDescriptor(Ruby runtime, RubyClass klazz) { - super(runtime, klazz); + /* + * call-seq: + * FieldDescriptor.name => name + * + * Returns the name of this field as a Ruby String, or nil if it is not set. + */ + @JRubyMethod(name = "name") + public IRubyObject getName(ThreadContext context) { + return this.name; + } + + /* + * call-seq: + * FieldDescriptor.subtype => message_or_enum_descriptor + * + * Returns the message or enum descriptor corresponding to this field's type if + * it is a message or enum field, respectively, or nil otherwise. Cannot be + * called *until* the containing message type is added to a pool (and thus + * resolved). + */ + @JRubyMethod(name = "subtype") + public IRubyObject getSubtype(ThreadContext context) { + if (subtype == null) { + calculateSubtype(context); } + return subtype; + } - /* - * call-seq: - * FieldDescriptor.default => default - * - * Returns this field's default, as a Ruby object, or nil if not yet set. - */ - // VALUE FieldDescriptor_default(VALUE _self) { - // DEFINE_SELF(FieldDescriptor, self, _self); - // return layout_get_default(self->fielddef); - // } + /* + * call-seq: + * FieldDescriptor.type => type + * + * Returns this field's type, as a Ruby symbol, or nil if not yet set. + * + * Valid field types are: + * :int32, :int64, :uint32, :uint64, :float, :double, :bool, :string, + * :bytes, :message. + */ + @JRubyMethod(name = "type") + public IRubyObject getType(ThreadContext context) { + return Utils.fieldTypeToRuby(context, descriptor.getType()); + } - /* - * call-seq: - * FieldDescriptor.label => label - * - * Returns this field's label (i.e., plurality), as a Ruby symbol. - * - * Valid field labels are: - * :optional, :repeated - */ - @JRubyMethod(name = "label") - public IRubyObject getLabel(ThreadContext context) { - if (label == null) { - calculateLabel(context); - } - return label; + /* + * call-seq: + * FieldDescriptor.number => number + * + * Returns the tag number for this field. + */ + @JRubyMethod(name = "number") + public IRubyObject getNumber(ThreadContext context) { + return this.number; + } + + /* + * call-seq: + * FieldDescriptor.submsg_name => submsg_name + * + * Returns the name of the message or enum type corresponding to this field, if + * it is a message or enum field (respectively), or nil otherwise. This type + * name will be resolved within the context of the pool to which the containing + * message type is added. + */ + // VALUE FieldDescriptor_submsg_name(VALUE _self) { + // DEFINE_SELF(FieldDescriptor, self, _self); + // switch (upb_fielddef_type(self->fielddef)) { + // case UPB_TYPE_ENUM: + // return rb_str_new2( + // upb_enumdef_fullname(upb_fielddef_enumsubdef(self->fielddef))); + // case UPB_TYPE_MESSAGE: + // return rb_str_new2( + // upb_msgdef_fullname(upb_fielddef_msgsubdef(self->fielddef))); + // default: + // return Qnil; + // } + // } + /* + * call-seq: + * FieldDescriptor.submsg_name = submsg_name + * + * Sets the name of the message or enum type corresponding to this field, if it + * is a message or enum field (respectively). This type name will be resolved + * within the context of the pool to which the containing message type is added. + * Cannot be called on field that are not of message or enum type, or on fields + * that are part of a message type already added to a pool. + */ + // @JRubyMethod(name = "submsg_name=") + // public IRubyObject setSubmsgName(ThreadContext context, IRubyObject name) { + // this.builder.setTypeName("." + Utils.escapeIdentifier(name.asJavaString())); + // return context.runtime.getNil(); + // } + + /* + * call-seq: + * FieldDescriptor.clear(message) + * + * Clears the field from the message if it's set. + */ + @JRubyMethod(name = "clear") + public IRubyObject clearValue(ThreadContext context, IRubyObject message) { + return ((RubyMessage) message).clearField(context, descriptor); + } + + /* + * call-seq: + * FieldDescriptor.get(message) => value + * + * Returns the value set for this field on the given message. Raises an + * exception if message is of the wrong type. + */ + @JRubyMethod(name = "get") + public IRubyObject getValue(ThreadContext context, IRubyObject message) { + return ((RubyMessage) message).getField(context, descriptor); + } + + /* + * call-seq: + * FieldDescriptor.has?(message) => boolean + * + * Returns whether the value is set on the given message. Raises an + * exception when calling for fields that do not have presence. + */ + @JRubyMethod(name = "has?") + public IRubyObject has(ThreadContext context, IRubyObject message) { + return ((RubyMessage) message).hasField(context, descriptor); + } + + /* + * call-seq: + * FieldDescriptor.set(message, value) + * + * Sets the value corresponding to this field to the given value on the given + * message. Raises an exception if message is of the wrong type. Performs the + * ordinary type-checks for field setting. + */ + @JRubyMethod(name = "set") + public IRubyObject setValue(ThreadContext context, IRubyObject message, IRubyObject value) { + ((RubyMessage) message).setField(context, descriptor, value); + return context.nil; + } + + protected void setDescriptor( + ThreadContext context, FieldDescriptor descriptor, RubyDescriptorPool pool) { + if (descriptor.isRequired() + && descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO3) { + throw Utils.createTypeError( + context, + descriptor.getName() + + " is labeled required but required fields are unsupported in proto3"); } + this.descriptor = descriptor; + this.name = context.runtime.newString(descriptor.getName()); + this.pool = pool; + } - /* - * call-seq: - * FieldDescriptor.name => name - * - * Returns the name of this field as a Ruby String, or nil if it is not set. - */ - @JRubyMethod(name = "name") - public IRubyObject getName(ThreadContext context) { - return this.name; + private void calculateLabel(ThreadContext context) { + if (descriptor.isRepeated()) { + this.label = context.runtime.newSymbol("repeated"); + } else if (descriptor.isOptional()) { + this.label = context.runtime.newSymbol("optional"); + } else { + this.label = context.nil; } + } - /* - * call-seq: - * FieldDescriptor.subtype => message_or_enum_descriptor - * - * Returns the message or enum descriptor corresponding to this field's type if - * it is a message or enum field, respectively, or nil otherwise. Cannot be - * called *until* the containing message type is added to a pool (and thus - * resolved). - */ - @JRubyMethod(name = "subtype") - public IRubyObject getSubtype(ThreadContext context) { - if (subtype == null) { - calculateSubtype(context); - } - return subtype; + private void calculateSubtype(ThreadContext context) { + FieldDescriptor.Type fdType = descriptor.getType(); + if (fdType == FieldDescriptor.Type.MESSAGE) { + RubyString messageName = context.runtime.newString(descriptor.getMessageType().getFullName()); + this.subtype = pool.lookup(context, messageName); + } else if (fdType == FieldDescriptor.Type.ENUM) { + RubyString enumName = context.runtime.newString(descriptor.getEnumType().getFullName()); + this.subtype = pool.lookup(context, enumName); + } else { + this.subtype = context.nil; } + } - /* - * call-seq: - * FieldDescriptor.type => type - * - * Returns this field's type, as a Ruby symbol, or nil if not yet set. - * - * Valid field types are: - * :int32, :int64, :uint32, :uint64, :float, :double, :bool, :string, - * :bytes, :message. - */ - @JRubyMethod(name = "type") - public IRubyObject getType(ThreadContext context) { - return Utils.fieldTypeToRuby(context, descriptor.getType()); - } + private static final String DOT = "."; - /* - * call-seq: - * FieldDescriptor.number => number - * - * Returns the tag number for this field. - */ - @JRubyMethod(name = "number") - public IRubyObject getNumber(ThreadContext context) { - return this.number; - } - - /* - * call-seq: - * FieldDescriptor.submsg_name => submsg_name - * - * Returns the name of the message or enum type corresponding to this field, if - * it is a message or enum field (respectively), or nil otherwise. This type - * name will be resolved within the context of the pool to which the containing - * message type is added. - */ - // VALUE FieldDescriptor_submsg_name(VALUE _self) { - // DEFINE_SELF(FieldDescriptor, self, _self); - // switch (upb_fielddef_type(self->fielddef)) { - // case UPB_TYPE_ENUM: - // return rb_str_new2( - // upb_enumdef_fullname(upb_fielddef_enumsubdef(self->fielddef))); - // case UPB_TYPE_MESSAGE: - // return rb_str_new2( - // upb_msgdef_fullname(upb_fielddef_msgsubdef(self->fielddef))); - // default: - // return Qnil; - // } - // } - /* - * call-seq: - * FieldDescriptor.submsg_name = submsg_name - * - * Sets the name of the message or enum type corresponding to this field, if it - * is a message or enum field (respectively). This type name will be resolved - * within the context of the pool to which the containing message type is added. - * Cannot be called on field that are not of message or enum type, or on fields - * that are part of a message type already added to a pool. - */ - // @JRubyMethod(name = "submsg_name=") - // public IRubyObject setSubmsgName(ThreadContext context, IRubyObject name) { - // this.builder.setTypeName("." + Utils.escapeIdentifier(name.asJavaString())); - // return context.runtime.getNil(); - // } - - /* - * call-seq: - * FieldDescriptor.clear(message) - * - * Clears the field from the message if it's set. - */ - @JRubyMethod(name = "clear") - public IRubyObject clearValue(ThreadContext context, IRubyObject message) { - return ((RubyMessage) message).clearField(context, descriptor); - } - - /* - * call-seq: - * FieldDescriptor.get(message) => value - * - * Returns the value set for this field on the given message. Raises an - * exception if message is of the wrong type. - */ - @JRubyMethod(name = "get") - public IRubyObject getValue(ThreadContext context, IRubyObject message) { - return ((RubyMessage) message).getField(context, descriptor); - } - - /* - * call-seq: - * FieldDescriptor.has?(message) => boolean - * - * Returns whether the value is set on the given message. Raises an - * exception when calling for fields that do not have presence. - */ - @JRubyMethod(name = "has?") - public IRubyObject has(ThreadContext context, IRubyObject message) { - return ((RubyMessage) message).hasField(context, descriptor); - } - - /* - * call-seq: - * FieldDescriptor.set(message, value) - * - * Sets the value corresponding to this field to the given value on the given - * message. Raises an exception if message is of the wrong type. Performs the - * ordinary type-checks for field setting. - */ - @JRubyMethod(name = "set") - public IRubyObject setValue(ThreadContext context, IRubyObject message, IRubyObject value) { - ((RubyMessage) message).setField(context, descriptor, value); - return context.nil; - } - - protected void setDescriptor(ThreadContext context, FieldDescriptor descriptor, RubyDescriptorPool pool) { - if (descriptor.isRequired() && descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO3) { - throw Utils.createTypeError(context, descriptor.getName() + " is labeled required but required fields are unsupported in proto3"); - } - this.descriptor = descriptor; - this.name = context.runtime.newString(descriptor.getName()); - this.pool = pool; - } - - private void calculateLabel(ThreadContext context) { - if (descriptor.isRepeated()) { - this.label = context.runtime.newSymbol("repeated"); - } else if (descriptor.isOptional()) { - this.label = context.runtime.newSymbol("optional"); - } else { - this.label = context.nil; - } - } - - private void calculateSubtype(ThreadContext context) { - FieldDescriptor.Type fdType = descriptor.getType(); - if (fdType == FieldDescriptor.Type.MESSAGE) { - RubyString messageName = context.runtime.newString(descriptor.getMessageType().getFullName()); - this.subtype = pool.lookup(context, messageName); - } else if (fdType == FieldDescriptor.Type.ENUM) { - RubyString enumName = context.runtime.newString(descriptor.getEnumType().getFullName()); - this.subtype = pool.lookup(context, enumName); - } else { - this.subtype = context.nil; - } - } - - private static final String DOT = "."; - - private FieldDescriptor descriptor; - private IRubyObject name; - private IRubyObject label; - private IRubyObject number; - private IRubyObject subtype; - private RubyDescriptorPool pool; + private FieldDescriptor descriptor; + private IRubyObject name; + private IRubyObject label; + private IRubyObject number; + private IRubyObject subtype; + private RubyDescriptorPool pool; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyFileDescriptor.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyFileDescriptor.java index b3e1816..972510b 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyFileDescriptor.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyFileDescriptor.java
@@ -32,7 +32,6 @@ package com.google.protobuf.jruby; -import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.FileDescriptor.Syntax.*; import com.google.protobuf.Descriptors.GenericDescriptor; @@ -46,61 +45,67 @@ @JRubyClass(name = "FileDescriptor") public class RubyFileDescriptor extends RubyObject { - public static void createRubyFileDescriptor(Ruby runtime) { - RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); - cFileDescriptor = mProtobuf.defineClassUnder("FileDescriptor", runtime.getObject(), new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + public static void createRubyFileDescriptor(Ruby runtime) { + RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); + cFileDescriptor = + mProtobuf.defineClassUnder( + "FileDescriptor", + runtime.getObject(), + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new RubyFileDescriptor(runtime, klazz); - } - }); - cFileDescriptor.defineAnnotatedMethods(RubyFileDescriptor.class); + } + }); + cFileDescriptor.defineAnnotatedMethods(RubyFileDescriptor.class); + } + + public static RubyFileDescriptor getRubyFileDescriptor( + ThreadContext context, GenericDescriptor descriptor) { + RubyFileDescriptor rfd = + (RubyFileDescriptor) cFileDescriptor.newInstance(context, Block.NULL_BLOCK); + rfd.fileDescriptor = descriptor.getFile(); + return rfd; + } + + public RubyFileDescriptor(Ruby runtime, RubyClass klazz) { + super(runtime, klazz); + } + + /* + * call-seq: + * FileDescriptor.name => name + * + * Returns the name of the file. + */ + @JRubyMethod(name = "name") + public IRubyObject getName(ThreadContext context) { + String name = fileDescriptor.getName(); + return name == null ? context.nil : context.runtime.newString(name); + } + + /* + * call-seq: + * FileDescriptor.syntax => syntax + * + * Returns this file descriptors syntax. + * + * Valid syntax versions are: + * :proto2 or :proto3. + */ + @JRubyMethod(name = "syntax") + public IRubyObject getSyntax(ThreadContext context) { + switch (fileDescriptor.getSyntax()) { + case PROTO2: + return context.runtime.newSymbol("proto2"); + case PROTO3: + return context.runtime.newSymbol("proto3"); + default: + return context.nil; } + } - public static RubyFileDescriptor getRubyFileDescriptor(ThreadContext context, GenericDescriptor descriptor) { - RubyFileDescriptor rfd = (RubyFileDescriptor) cFileDescriptor.newInstance(context, Block.NULL_BLOCK); - rfd.fileDescriptor = descriptor.getFile(); - return rfd; - } + private static RubyClass cFileDescriptor; - public RubyFileDescriptor(Ruby runtime, RubyClass klazz) { - super(runtime, klazz); - } - - /* - * call-seq: - * FileDescriptor.name => name - * - * Returns the name of the file. - */ - @JRubyMethod(name = "name") - public IRubyObject getName(ThreadContext context) { - String name = fileDescriptor.getName(); - return name == null ? context.nil : context.runtime.newString(name); - } - - /* - * call-seq: - * FileDescriptor.syntax => syntax - * - * Returns this file descriptors syntax. - * - * Valid syntax versions are: - * :proto2 or :proto3. - */ - @JRubyMethod(name = "syntax") - public IRubyObject getSyntax(ThreadContext context) { - switch (fileDescriptor.getSyntax()) { - case PROTO2: - return context.runtime.newSymbol("proto2"); - case PROTO3: - return context.runtime.newSymbol("proto3"); - default: - return context.nil; - } - } - - private static RubyClass cFileDescriptor; - - private FileDescriptor fileDescriptor; + private FileDescriptor fileDescriptor; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java index 7956eeb..8727b13 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyMap.java
@@ -34,6 +34,13 @@ import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.DynamicMessage; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.jruby.*; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; @@ -43,432 +50,438 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; -import java.nio.ByteBuffer; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - @JRubyClass(name = "Map", include = "Enumerable") public class RubyMap extends RubyObject { - public static void createRubyMap(Ruby runtime) { - RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); - RubyClass cMap = protobuf.defineClassUnder("Map", runtime.getObject(), new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby ruby, RubyClass rubyClass) { + public static void createRubyMap(Ruby runtime) { + RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cMap = + protobuf.defineClassUnder( + "Map", + runtime.getObject(), + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby ruby, RubyClass rubyClass) { return new RubyMap(ruby, rubyClass); + } + }); + cMap.includeModule(runtime.getEnumerable()); + cMap.defineAnnotatedMethods(RubyMap.class); + } + + public RubyMap(Ruby ruby, RubyClass rubyClass) { + super(ruby, rubyClass); + } + + /* + * call-seq: + * Map.new(key_type, value_type, value_typeclass = nil, init_hashmap = {}) + * => new map + * + * Allocates a new Map container. This constructor may be called with 2, 3, or 4 + * arguments. The first two arguments are always present and are symbols (taking + * on the same values as field-type symbols in message descriptors) that + * indicate the type of the map key and value fields. + * + * The supported key types are: :int32, :int64, :uint32, :uint64, :fixed32, + * :fixed64, :sfixed32, :sfixed64, :sint32, :sint64, :bool, :string, :bytes. + * + * The supported value types are: :int32, :int64, :uint32, :uint64, :fixed32, + * :fixed64, :sfixed32, :sfixed64, :sint32, :sint64, :bool, :string, :bytes, + * :enum, :message. + * + * The third argument, value_typeclass, must be present if value_type is :enum + * or :message. As in RepeatedField#new, this argument must be a message class + * (for :message) or enum module (for :enum). + * + * The last argument, if present, provides initial content for map. Note that + * this may be an ordinary Ruby hashmap or another Map instance with identical + * key and value types. Also note that this argument may be present whether or + * not value_typeclass is present (and it is unambiguously separate from + * value_typeclass because value_typeclass's presence is strictly determined by + * value_type). The contents of this initial hashmap or Map instance are + * shallow-copied into the new Map: the original map is unmodified, but + * references to underlying objects will be shared if the value type is a + * message type. + */ + @JRubyMethod(required = 2, optional = 2) + public IRubyObject initialize(ThreadContext context, IRubyObject[] args) { + this.table = new HashMap<IRubyObject, IRubyObject>(); + this.keyType = Utils.rubyToFieldType(args[0]); + this.valueType = Utils.rubyToFieldType(args[1]); + + switch (keyType) { + case STRING: + case BYTES: + this.keyTypeIsString = true; + break; + case INT32: + case INT64: + case SINT32: + case SINT64: + case UINT32: + case UINT64: + case FIXED32: + case FIXED64: + case SFIXED32: + case SFIXED64: + case BOOL: + // These are OK. + break; + default: + throw context.runtime.newArgumentError("Invalid key type for map."); + } + + int initValueArg = 2; + if (needTypeclass(this.valueType) && args.length > 2) { + this.valueTypeClass = args[2]; + Utils.validateTypeClass(context, this.valueType, this.valueTypeClass); + initValueArg = 3; + } else { + this.valueTypeClass = context.runtime.getNilClass(); + } + + if (args.length > initValueArg) { + mergeIntoSelf(context, args[initValueArg]); + } + return this; + } + + /* + * call-seq: + * Map.[]=(key, value) => value + * + * Inserts or overwrites the value at the given key with the given new value. + * Throws an exception if the key type is incorrect. Returns the new value that + * was just inserted. + */ + @JRubyMethod(name = "[]=") + public IRubyObject indexSet(ThreadContext context, IRubyObject key, IRubyObject value) { + checkFrozen(); + + /* + * String types for keys return a different error than + * other types for keys, so deal with them specifically first + */ + if (keyTypeIsString && !(key instanceof RubySymbol || key instanceof RubyString)) { + throw Utils.createTypeError(context, "Expected string for map key"); + } + key = Utils.checkType(context, keyType, "key", key, (RubyModule) valueTypeClass); + value = Utils.checkType(context, valueType, "value", value, (RubyModule) valueTypeClass); + IRubyObject symbol; + if (valueType == FieldDescriptor.Type.ENUM + && Utils.isRubyNum(value) + && !(symbol = RubyEnum.lookup(context, valueTypeClass, value)).isNil()) { + value = symbol; + } + this.table.put(key, value); + return value; + } + + /* + * call-seq: + * Map.[](key) => value + * + * Accesses the element at the given key. Throws an exception if the key type is + * incorrect. Returns nil when the key is not present in the map. + */ + @JRubyMethod(name = "[]") + public IRubyObject index(ThreadContext context, IRubyObject key) { + key = Utils.symToString(key); + return Helpers.nullToNil(table.get(key), context.nil); + } + + /* + * call-seq: + * Map.==(other) => boolean + * + * Compares this map to another. Maps are equal if they have identical key sets, + * and for each key, the values in both maps compare equal. Elements are + * compared as per normal Ruby semantics, by calling their :== methods (or + * performing a more efficient comparison for primitive types). + * + * Maps with dissimilar key types or value types/typeclasses are never equal, + * even if value comparison (for example, between integers and floats) would + * have otherwise indicated that every element has equal value. + */ + @JRubyMethod(name = "==") + public IRubyObject eq(ThreadContext context, IRubyObject _other) { + if (_other instanceof RubyHash) return singleLevelHash(context).op_equal(context, _other); + RubyMap other = (RubyMap) _other; + if (this == other) return context.runtime.getTrue(); + if (!typeCompatible(other) || this.table.size() != other.table.size()) + return context.runtime.getFalse(); + for (IRubyObject key : table.keySet()) { + if (!other.table.containsKey(key)) return context.runtime.getFalse(); + if (!other.table.get(key).equals(table.get(key))) return context.runtime.getFalse(); + } + return context.runtime.getTrue(); + } + + /* + * call-seq: + * Map.inspect => string + * + * Returns a string representing this map's elements. It will be formatted as + * "{key => value, key => value, ...}", with each key and value string + * representation computed by its own #inspect method. + */ + @JRubyMethod + public IRubyObject inspect() { + return singleLevelHash(getRuntime().getCurrentContext()).inspect(); + } + + /* + * call-seq: + * Map.hash => hash_value + * + * Returns a hash value based on this map's contents. + */ + @JRubyMethod + public IRubyObject hash(ThreadContext context) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (IRubyObject key : table.keySet()) { + digest.update((byte) key.hashCode()); + digest.update((byte) table.get(key).hashCode()); + } + return context.runtime.newFixnum(ByteBuffer.wrap(digest.digest()).getLong()); + } catch (NoSuchAlgorithmException ignore) { + return context.runtime.newFixnum(System.identityHashCode(table)); + } + } + + /* + * call-seq: + * Map.keys => [list_of_keys] + * + * Returns the list of keys contained in the map, in unspecified order. + */ + @JRubyMethod + public IRubyObject keys(ThreadContext context) { + return RubyArray.newArray(context.runtime, table.keySet()); + } + + /* + * call-seq: + * Map.values => [list_of_values] + * + * Returns the list of values contained in the map, in unspecified order. + */ + @JRubyMethod + public IRubyObject values(ThreadContext context) { + return RubyArray.newArray(context.runtime, table.values()); + } + + /* + * call-seq: + * Map.clear + * + * Removes all entries from the map. + */ + @JRubyMethod + public IRubyObject clear(ThreadContext context) { + checkFrozen(); + table.clear(); + return context.nil; + } + + /* + * call-seq: + * Map.each(&block) + * + * Invokes &block on each |key, value| pair in the map, in unspecified order. + * Note that Map also includes Enumerable; map thus acts like a normal Ruby + * sequence. + */ + @JRubyMethod + public IRubyObject each(ThreadContext context, Block block) { + for (IRubyObject key : table.keySet()) { + block.yieldSpecific(context, key, table.get(key)); + } + return context.nil; + } + + /* + * call-seq: + * Map.delete(key) => old_value + * + * Deletes the value at the given key, if any, returning either the old value or + * nil if none was present. Throws an exception if the key is of the wrong type. + */ + @JRubyMethod + public IRubyObject delete(ThreadContext context, IRubyObject key) { + checkFrozen(); + return table.remove(key); + } + + /* + * call-seq: + * Map.has_key?(key) => bool + * + * Returns true if the given key is present in the map. Throws an exception if + * the key has the wrong type. + */ + @JRubyMethod(name = "has_key?") + public IRubyObject hasKey(ThreadContext context, IRubyObject key) { + return this.table.containsKey(key) ? context.runtime.getTrue() : context.runtime.getFalse(); + } + + /* + * call-seq: + * Map.length + * + * Returns the number of entries (key-value pairs) in the map. + */ + @JRubyMethod(name = {"length", "size"}) + public IRubyObject length(ThreadContext context) { + return context.runtime.newFixnum(this.table.size()); + } + + /* + * call-seq: + * Map.dup => new_map + * + * Duplicates this map with a shallow copy. References to all non-primitive + * element objects (e.g., submessages) are shared. + */ + @JRubyMethod + public IRubyObject dup(ThreadContext context) { + RubyMap newMap = newThisType(context); + for (Map.Entry<IRubyObject, IRubyObject> entry : table.entrySet()) { + newMap.table.put(entry.getKey(), entry.getValue()); + } + return newMap; + } + + @JRubyMethod(name = "to_h") + public RubyHash toHash(ThreadContext context) { + Map<IRubyObject, IRubyObject> mapForHash = new HashMap(); + + table.forEach( + (key, value) -> { + if (!value.isNil()) { + if (value.respondsTo("to_h")) { + value = Helpers.invoke(context, value, "to_h"); + } else if (value.respondsTo("to_a")) { + value = Helpers.invoke(context, value, "to_a"); } - }); - cMap.includeModule(runtime.getEnumerable()); - cMap.defineAnnotatedMethods(RubyMap.class); - } - - public RubyMap(Ruby ruby, RubyClass rubyClass) { - super(ruby, rubyClass); - } - - /* - * call-seq: - * Map.new(key_type, value_type, value_typeclass = nil, init_hashmap = {}) - * => new map - * - * Allocates a new Map container. This constructor may be called with 2, 3, or 4 - * arguments. The first two arguments are always present and are symbols (taking - * on the same values as field-type symbols in message descriptors) that - * indicate the type of the map key and value fields. - * - * The supported key types are: :int32, :int64, :uint32, :uint64, :fixed32, - * :fixed64, :sfixed32, :sfixed64, :sint32, :sint64, :bool, :string, :bytes. - * - * The supported value types are: :int32, :int64, :uint32, :uint64, :fixed32, - * :fixed64, :sfixed32, :sfixed64, :sint32, :sint64, :bool, :string, :bytes, - * :enum, :message. - * - * The third argument, value_typeclass, must be present if value_type is :enum - * or :message. As in RepeatedField#new, this argument must be a message class - * (for :message) or enum module (for :enum). - * - * The last argument, if present, provides initial content for map. Note that - * this may be an ordinary Ruby hashmap or another Map instance with identical - * key and value types. Also note that this argument may be present whether or - * not value_typeclass is present (and it is unambiguously separate from - * value_typeclass because value_typeclass's presence is strictly determined by - * value_type). The contents of this initial hashmap or Map instance are - * shallow-copied into the new Map: the original map is unmodified, but - * references to underlying objects will be shared if the value type is a - * message type. - */ - @JRubyMethod(required = 2, optional = 2) - public IRubyObject initialize(ThreadContext context, IRubyObject[] args) { - this.table = new HashMap<IRubyObject, IRubyObject>(); - this.keyType = Utils.rubyToFieldType(args[0]); - this.valueType = Utils.rubyToFieldType(args[1]); - - switch(keyType) { - case STRING: - case BYTES: - this.keyTypeIsString = true; - break; - case INT32: - case INT64: - case SINT32: - case SINT64: - case UINT32: - case UINT64: - case FIXED32: - case FIXED64: - case SFIXED32: - case SFIXED64: - case BOOL: - // These are OK. - break; - default: - throw context.runtime.newArgumentError("Invalid key type for map."); - } - - int initValueArg = 2; - if (needTypeclass(this.valueType) && args.length > 2) { - this.valueTypeClass = args[2]; - Utils.validateTypeClass(context, this.valueType, this.valueTypeClass); - initValueArg = 3; - } else { - this.valueTypeClass = context.runtime.getNilClass(); - } - - if (args.length > initValueArg) { - mergeIntoSelf(context, args[initValueArg]); - } - return this; - } - - /* - * call-seq: - * Map.[]=(key, value) => value - * - * Inserts or overwrites the value at the given key with the given new value. - * Throws an exception if the key type is incorrect. Returns the new value that - * was just inserted. - */ - @JRubyMethod(name = "[]=") - public IRubyObject indexSet(ThreadContext context, IRubyObject key, IRubyObject value) { - checkFrozen(); - - /* - * String types for keys return a different error than - * other types for keys, so deal with them specifically first - */ - if (keyTypeIsString && !(key instanceof RubySymbol || key instanceof RubyString)) { - throw Utils.createTypeError(context, "Expected string for map key"); - } - key = Utils.checkType(context, keyType, "key", key, (RubyModule) valueTypeClass); - value = Utils.checkType(context, valueType, "value", value, (RubyModule) valueTypeClass); - IRubyObject symbol; - if (valueType == FieldDescriptor.Type.ENUM && - Utils.isRubyNum(value) && - ! (symbol = RubyEnum.lookup(context, valueTypeClass, value)).isNil()) { - value = symbol; - } - this.table.put(key, value); - return value; - } - - /* - * call-seq: - * Map.[](key) => value - * - * Accesses the element at the given key. Throws an exception if the key type is - * incorrect. Returns nil when the key is not present in the map. - */ - @JRubyMethod(name = "[]") - public IRubyObject index(ThreadContext context, IRubyObject key) { - key = Utils.symToString(key); - return Helpers.nullToNil(table.get(key), context.nil); - } - - /* - * call-seq: - * Map.==(other) => boolean - * - * Compares this map to another. Maps are equal if they have identical key sets, - * and for each key, the values in both maps compare equal. Elements are - * compared as per normal Ruby semantics, by calling their :== methods (or - * performing a more efficient comparison for primitive types). - * - * Maps with dissimilar key types or value types/typeclasses are never equal, - * even if value comparison (for example, between integers and floats) would - * have otherwise indicated that every element has equal value. - */ - @JRubyMethod(name = "==") - public IRubyObject eq(ThreadContext context, IRubyObject _other) { - if (_other instanceof RubyHash) - return singleLevelHash(context).op_equal(context, _other); - RubyMap other = (RubyMap) _other; - if (this == other) return context.runtime.getTrue(); - if (!typeCompatible(other) || this.table.size() != other.table.size()) - return context.runtime.getFalse(); - for (IRubyObject key : table.keySet()) { - if (! other.table.containsKey(key)) - return context.runtime.getFalse(); - if (! other.table.get(key).equals(table.get(key))) - return context.runtime.getFalse(); - } - return context.runtime.getTrue(); - } - - /* - * call-seq: - * Map.inspect => string - * - * Returns a string representing this map's elements. It will be formatted as - * "{key => value, key => value, ...}", with each key and value string - * representation computed by its own #inspect method. - */ - @JRubyMethod - public IRubyObject inspect() { - return singleLevelHash(getRuntime().getCurrentContext()).inspect(); - } - - /* - * call-seq: - * Map.hash => hash_value - * - * Returns a hash value based on this map's contents. - */ - @JRubyMethod - public IRubyObject hash(ThreadContext context) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - for (IRubyObject key : table.keySet()) { - digest.update((byte) key.hashCode()); - digest.update((byte) table.get(key).hashCode()); - } - return context.runtime.newFixnum(ByteBuffer.wrap(digest.digest()).getLong()); - } catch (NoSuchAlgorithmException ignore) { - return context.runtime.newFixnum(System.identityHashCode(table)); - } - } - - /* - * call-seq: - * Map.keys => [list_of_keys] - * - * Returns the list of keys contained in the map, in unspecified order. - */ - @JRubyMethod - public IRubyObject keys(ThreadContext context) { - return RubyArray.newArray(context.runtime, table.keySet()); - } - - /* - * call-seq: - * Map.values => [list_of_values] - * - * Returns the list of values contained in the map, in unspecified order. - */ - @JRubyMethod - public IRubyObject values(ThreadContext context) { - return RubyArray.newArray(context.runtime, table.values()); - } - - /* - * call-seq: - * Map.clear - * - * Removes all entries from the map. - */ - @JRubyMethod - public IRubyObject clear(ThreadContext context) { - checkFrozen(); - table.clear(); - return context.nil; - } - - /* - * call-seq: - * Map.each(&block) - * - * Invokes &block on each |key, value| pair in the map, in unspecified order. - * Note that Map also includes Enumerable; map thus acts like a normal Ruby - * sequence. - */ - @JRubyMethod - public IRubyObject each(ThreadContext context, Block block) { - for (IRubyObject key : table.keySet()) { - block.yieldSpecific(context, key, table.get(key)); - } - return context.nil; - } - - /* - * call-seq: - * Map.delete(key) => old_value - * - * Deletes the value at the given key, if any, returning either the old value or - * nil if none was present. Throws an exception if the key is of the wrong type. - */ - @JRubyMethod - public IRubyObject delete(ThreadContext context, IRubyObject key) { - checkFrozen(); - return table.remove(key); - } - - /* - * call-seq: - * Map.has_key?(key) => bool - * - * Returns true if the given key is present in the map. Throws an exception if - * the key has the wrong type. - */ - @JRubyMethod(name = "has_key?") - public IRubyObject hasKey(ThreadContext context, IRubyObject key) { - return this.table.containsKey(key) ? context.runtime.getTrue() : context.runtime.getFalse(); - } - - /* - * call-seq: - * Map.length - * - * Returns the number of entries (key-value pairs) in the map. - */ - @JRubyMethod(name = {"length", "size"}) - public IRubyObject length(ThreadContext context) { - return context.runtime.newFixnum(this.table.size()); - } - - /* - * call-seq: - * Map.dup => new_map - * - * Duplicates this map with a shallow copy. References to all non-primitive - * element objects (e.g., submessages) are shared. - */ - @JRubyMethod - public IRubyObject dup(ThreadContext context) { - RubyMap newMap = newThisType(context); - for (Map.Entry<IRubyObject, IRubyObject> entry : table.entrySet()) { - newMap.table.put(entry.getKey(), entry.getValue()); - } - return newMap; - } - - @JRubyMethod(name = "to_h") - public RubyHash toHash(ThreadContext context) { - Map<IRubyObject, IRubyObject> mapForHash = new HashMap(); - - table.forEach((key, value) -> { - if (!value.isNil()) { - if (value.respondsTo("to_h")) { - value = Helpers.invoke(context, value, "to_h"); - } else if (value.respondsTo("to_a")) { - value = Helpers.invoke(context, value, "to_a"); - } - mapForHash.put(key, value); - } + mapForHash.put(key, value); + } }); - return RubyHash.newHash(context.runtime, mapForHash, context.nil); - } + return RubyHash.newHash(context.runtime, mapForHash, context.nil); + } - // Used by Google::Protobuf.deep_copy but not exposed directly. - protected IRubyObject deepCopy(ThreadContext context) { - RubyMap newMap = newThisType(context); - switch (valueType) { - case MESSAGE: - for (IRubyObject key : table.keySet()) { - RubyMessage message = (RubyMessage) table.get(key); - newMap.table.put(key.dup(), message.deepCopy(context)); - } - break; - default: - for (IRubyObject key : table.keySet()) { - newMap.table.put(key.dup(), table.get(key).dup()); - } - } - return newMap; - } - - protected List<DynamicMessage> build(ThreadContext context, RubyDescriptor descriptor, int depth, int recursionLimit) { - List<DynamicMessage> list = new ArrayList<DynamicMessage>(); - RubyClass rubyClass = (RubyClass) descriptor.msgclass(context); - FieldDescriptor keyField = descriptor.getField("key"); - FieldDescriptor valueField = descriptor.getField("value"); + // Used by Google::Protobuf.deep_copy but not exposed directly. + protected IRubyObject deepCopy(ThreadContext context) { + RubyMap newMap = newThisType(context); + switch (valueType) { + case MESSAGE: for (IRubyObject key : table.keySet()) { - RubyMessage mapMessage = (RubyMessage) rubyClass.newInstance(context, Block.NULL_BLOCK); - mapMessage.setField(context, keyField, key); - mapMessage.setField(context, valueField, table.get(key)); - list.add(mapMessage.build(context, depth + 1, recursionLimit)); + RubyMessage message = (RubyMessage) table.get(key); + newMap.table.put(key.dup(), message.deepCopy(context)); } - return list; + break; + default: + for (IRubyObject key : table.keySet()) { + newMap.table.put(key.dup(), table.get(key).dup()); + } } + return newMap; + } - protected RubyMap mergeIntoSelf(final ThreadContext context, IRubyObject hashmap) { - if (hashmap instanceof RubyHash) { - ((RubyHash) hashmap).visitAll(context, new RubyHash.Visitor() { + protected List<DynamicMessage> build( + ThreadContext context, RubyDescriptor descriptor, int depth, int recursionLimit) { + List<DynamicMessage> list = new ArrayList<DynamicMessage>(); + RubyClass rubyClass = (RubyClass) descriptor.msgclass(context); + FieldDescriptor keyField = descriptor.getField("key"); + FieldDescriptor valueField = descriptor.getField("value"); + for (IRubyObject key : table.keySet()) { + RubyMessage mapMessage = (RubyMessage) rubyClass.newInstance(context, Block.NULL_BLOCK); + mapMessage.setField(context, keyField, key); + mapMessage.setField(context, valueField, table.get(key)); + list.add(mapMessage.build(context, depth + 1, recursionLimit)); + } + return list; + } + + protected RubyMap mergeIntoSelf(final ThreadContext context, IRubyObject hashmap) { + if (hashmap instanceof RubyHash) { + ((RubyHash) hashmap) + .visitAll( + context, + new RubyHash.Visitor() { @Override public void visit(IRubyObject key, IRubyObject val) { - if (val instanceof RubyHash && !valueTypeClass.isNil()) { - val = ((RubyClass) valueTypeClass).newInstance(context, val, Block.NULL_BLOCK); - } - indexSet(context, key, val); + if (val instanceof RubyHash && !valueTypeClass.isNil()) { + val = ((RubyClass) valueTypeClass).newInstance(context, val, Block.NULL_BLOCK); + } + indexSet(context, key, val); } - }, null); - } else if (hashmap instanceof RubyMap) { - RubyMap other = (RubyMap) hashmap; - if (!typeCompatible(other)) { - throw Utils.createTypeError(context, "Attempt to merge Map with mismatching types"); - } - } else { - throw Utils.createTypeError(context, "Unknown type merging into Map"); - } - return this; + }, + null); + } else if (hashmap instanceof RubyMap) { + RubyMap other = (RubyMap) hashmap; + if (!typeCompatible(other)) { + throw Utils.createTypeError(context, "Attempt to merge Map with mismatching types"); + } + } else { + throw Utils.createTypeError(context, "Unknown type merging into Map"); } + return this; + } - protected boolean typeCompatible(RubyMap other) { - return this.keyType == other.keyType && - this.valueType == other.valueType && - this.valueTypeClass == other.valueTypeClass; + protected boolean typeCompatible(RubyMap other) { + return this.keyType == other.keyType + && this.valueType == other.valueType + && this.valueTypeClass == other.valueTypeClass; + } + + private RubyMap newThisType(ThreadContext context) { + RubyMap newMap; + if (needTypeclass(valueType)) { + newMap = + (RubyMap) + metaClass.newInstance( + context, + Utils.fieldTypeToRuby(context, keyType), + Utils.fieldTypeToRuby(context, valueType), + valueTypeClass, + Block.NULL_BLOCK); + } else { + newMap = + (RubyMap) + metaClass.newInstance( + context, + Utils.fieldTypeToRuby(context, keyType), + Utils.fieldTypeToRuby(context, valueType), + Block.NULL_BLOCK); } + newMap.table = new HashMap<IRubyObject, IRubyObject>(); + return newMap; + } - private RubyMap newThisType(ThreadContext context) { - RubyMap newMap; - if (needTypeclass(valueType)) { - newMap = (RubyMap) metaClass.newInstance(context, - Utils.fieldTypeToRuby(context, keyType), - Utils.fieldTypeToRuby(context, valueType), - valueTypeClass, Block.NULL_BLOCK); - } else { - newMap = (RubyMap) metaClass.newInstance(context, - Utils.fieldTypeToRuby(context, keyType), - Utils.fieldTypeToRuby(context, valueType), - Block.NULL_BLOCK); - } - newMap.table = new HashMap<IRubyObject, IRubyObject>(); - return newMap; + /* + * toHash calls toHash on values, for some camparisons we only need + * a hash with the original objects still as values + */ + private RubyHash singleLevelHash(ThreadContext context) { + return RubyHash.newHash(context.runtime, table, context.nil); + } + + private boolean needTypeclass(FieldDescriptor.Type type) { + switch (type) { + case MESSAGE: + case ENUM: + return true; + default: + return false; } + } - /* - * toHash calls toHash on values, for some camparisons we only need - * a hash with the original objects still as values - */ - private RubyHash singleLevelHash(ThreadContext context) { - return RubyHash.newHash(context.runtime, table, context.nil); - } - - private boolean needTypeclass(FieldDescriptor.Type type) { - switch(type) { - case MESSAGE: - case ENUM: - return true; - default: - return false; - } - } - - private FieldDescriptor.Type keyType; - private FieldDescriptor.Type valueType; - private IRubyObject valueTypeClass; - private Map<IRubyObject, IRubyObject> table; - private boolean keyTypeIsString = false; + private FieldDescriptor.Type keyType; + private FieldDescriptor.Type valueType; + private IRubyObject valueTypeClass; + private Map<IRubyObject, IRubyObject> table; + private boolean keyTypeIsString = false; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java index 2167f15..1e949a5 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyMessage.java
@@ -32,19 +32,25 @@ package com.google.protobuf.jruby; +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedInputStream; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.OneofDescriptor; -import com.google.protobuf.ByteString; -import com.google.protobuf.CodedInputStream; import com.google.protobuf.DynamicMessage; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.google.protobuf.UnknownFieldSet; import com.google.protobuf.util.JsonFormat; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.jruby.*; import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; @@ -54,1297 +60,1406 @@ import org.jruby.runtime.builtin.IRubyObject; import org.jruby.util.ByteList; -import java.nio.ByteBuffer; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class RubyMessage extends RubyObject { - private final String DEFAULT_VALUE = "google.protobuf.FieldDescriptorProto.default_value"; - private final String TYPE = "type"; + private final String DEFAULT_VALUE = "google.protobuf.FieldDescriptorProto.default_value"; + private final String TYPE = "type"; - public RubyMessage(Ruby runtime, RubyClass klazz, Descriptor descriptor) { - super(runtime, klazz); + public RubyMessage(Ruby runtime, RubyClass klazz, Descriptor descriptor) { + super(runtime, klazz); - this.descriptor = descriptor; - this.cRepeatedField = (RubyClass) runtime.getClassFromPath("Google::Protobuf::RepeatedField"); - this.cMap = (RubyClass) runtime.getClassFromPath("Google::Protobuf::Map"); - this.builder = DynamicMessage.newBuilder(descriptor); - this.fields = new HashMap<FieldDescriptor, IRubyObject>(); - this.oneofCases = new HashMap<OneofDescriptor, FieldDescriptor>(); - this.proto3 = descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO3; - } + this.descriptor = descriptor; + this.cRepeatedField = (RubyClass) runtime.getClassFromPath("Google::Protobuf::RepeatedField"); + this.cMap = (RubyClass) runtime.getClassFromPath("Google::Protobuf::Map"); + this.builder = DynamicMessage.newBuilder(descriptor); + this.fields = new HashMap<FieldDescriptor, IRubyObject>(); + this.oneofCases = new HashMap<OneofDescriptor, FieldDescriptor>(); + this.proto3 = descriptor.getFile().getSyntax() == FileDescriptor.Syntax.PROTO3; + } - /* - * call-seq: - * Message.new(kwargs) => new_message - * - * Creates a new instance of the given message class. Keyword arguments may be - * provided with keywords corresponding to field names. - * - * Note that no literal Message class exists. Only concrete classes per message - * type exist, as provided by the #msgclass method on Descriptors after they - * have been added to a pool. The method definitions described here on the - * Message class are provided on each concrete message class. - */ - @JRubyMethod(optional = 1) - public IRubyObject initialize(final ThreadContext context, IRubyObject[] args) { - final Ruby runtime = context.runtime; - if (args.length == 1) { - if (!(args[0] instanceof RubyHash)) { - throw runtime.newArgumentError("expected Hash arguments."); - } - RubyHash hash = args[0].convertToHash(); - hash.visitAll(context, new RubyHash.Visitor() { - @Override - public void visit(IRubyObject key, IRubyObject value) { - if (!(key instanceof RubySymbol) && !(key instanceof RubyString)) { - throw Utils.createTypeError(context, - "Expected string or symbols as hash keys in initialization map."); - } - final FieldDescriptor fieldDescriptor = findField(context, key, ignoreUnknownFieldsOnInit); + /* + * call-seq: + * Message.new(kwargs) => new_message + * + * Creates a new instance of the given message class. Keyword arguments may be + * provided with keywords corresponding to field names. + * + * Note that no literal Message class exists. Only concrete classes per message + * type exist, as provided by the #msgclass method on Descriptors after they + * have been added to a pool. The method definitions described here on the + * Message class are provided on each concrete message class. + */ + @JRubyMethod(optional = 1) + public IRubyObject initialize(final ThreadContext context, IRubyObject[] args) { + final Ruby runtime = context.runtime; + if (args.length == 1) { + if (!(args[0] instanceof RubyHash)) { + throw runtime.newArgumentError("expected Hash arguments."); + } + RubyHash hash = args[0].convertToHash(); + hash.visitAll( + context, + new RubyHash.Visitor() { + @Override + public void visit(IRubyObject key, IRubyObject value) { + if (!(key instanceof RubySymbol) && !(key instanceof RubyString)) { + throw Utils.createTypeError( + context, "Expected string or symbols as hash keys in initialization map."); + } + final FieldDescriptor fieldDescriptor = + findField(context, key, ignoreUnknownFieldsOnInit); - if (value == null || value.isNil()) return; + if (value == null || value.isNil()) return; - if (fieldDescriptor.isMapField()) { - if (!(value instanceof RubyHash)) - throw runtime.newArgumentError("Expected Hash object as initializer value for map field '" + key.asJavaString() + "' (given " + value.getMetaClass() + ")."); + if (fieldDescriptor.isMapField()) { + if (!(value instanceof RubyHash)) + throw runtime.newArgumentError( + "Expected Hash object as initializer value for map field '" + + key.asJavaString() + + "' (given " + + value.getMetaClass() + + ")."); - final RubyMap map = newMapForField(context, fieldDescriptor); - map.mergeIntoSelf(context, value); - fields.put(fieldDescriptor, map); - } else if (fieldDescriptor.isRepeated()) { - if (!(value instanceof RubyArray)) - throw runtime.newArgumentError("Expected array as initializer value for repeated field '" + key.asJavaString() + "' (given " + value.getMetaClass() + ")."); - fields.put(fieldDescriptor, rubyToRepeatedField(context, fieldDescriptor, value)); - } else { - OneofDescriptor oneof = fieldDescriptor.getContainingOneof(); - if (oneof != null) { - oneofCases.put(oneof, fieldDescriptor); - } - - if (value instanceof RubyHash && fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE) { - RubyDescriptor descriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); - RubyClass typeClass = (RubyClass) descriptor.msgclass(context); - value = (IRubyObject) typeClass.newInstance(context, value, Block.NULL_BLOCK); - fields.put(fieldDescriptor, value); - } else { - indexSet(context, key, value); - } - - } - } - }, null); - } - return this; - } - - /* - * call-seq: - * Message.[]=(index, value) - * - * Sets a field's value by field name. The provided field name should be a - * string. - */ - @JRubyMethod(name = "[]=") - public IRubyObject indexSet(ThreadContext context, IRubyObject fieldName, IRubyObject value) { - FieldDescriptor fieldDescriptor = findField(context, fieldName); - return setFieldInternal(context, fieldDescriptor, value); - } - - /* - * call-seq: - * Message.[](index) => value - * - * Accesses a field's value by field name. The provided field name should be a - * string. - */ - @JRubyMethod(name = "[]") - public IRubyObject index(ThreadContext context, IRubyObject fieldName) { - FieldDescriptor fieldDescriptor = findField(context, fieldName); - return getFieldInternal(context, fieldDescriptor); - } - - /* - * call-seq: - * Message.inspect => string - * - * Returns a human-readable string representing this message. It will be - * formatted as "<MessageType: field1: value1, field2: value2, ...>". Each - * field's value is represented according to its own #inspect method. - */ - @JRubyMethod(name = {"inspect", "to_s"}) - public IRubyObject inspect() { - ThreadContext context = getRuntime().getCurrentContext(); - String cname = metaClass.getName(); - String colon = ": "; - String comma = ", "; - StringBuilder sb = new StringBuilder("<"); - boolean addComma = false; - - sb.append(cname).append(colon); - - for (FieldDescriptor fd : descriptor.getFields()) { - if (fd.hasPresence() && !fields.containsKey(fd)) { - continue; - } - if (addComma) { - sb.append(comma); - } else { - addComma = true; - } - - sb.append(fd.getName()).append(colon); - - IRubyObject value = getFieldInternal(context, fd); - if (value instanceof RubyBoolean) { - // Booleans don't implement internal "inspect" methods so have to call handle them manually - sb.append(value.isTrue() ? "true" : "false"); - } else { - sb.append(value.inspect()); - } - } - sb.append(">"); - - return context.runtime.newString(sb.toString()); - } - - /* - * call-seq: - * Message.hash => hash_value - * - * Returns a hash value that represents this message's field values. - */ - @JRubyMethod - public IRubyObject hash(ThreadContext context) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - for (FieldDescriptor fd : descriptor.getFields()) { - digest.update((byte) getFieldInternal(context, fd).hashCode()); - } - return context.runtime.newFixnum(ByteBuffer.wrap(digest.digest()).getLong()); - } catch (NoSuchAlgorithmException ignore) { - return context.runtime.newFixnum(System.identityHashCode(this)); - } - } - - /* - * call-seq: - * Message.==(other) => boolean - * - * Performs a deep comparison of this message with another. Messages are equal - * if they have the same type and if each field is equal according to the :== - * method's semantics (a more efficient comparison may actually be done if the - * field is of a primitive type). - */ - @JRubyMethod(name = {"==", "eql?"}) - public IRubyObject eq(ThreadContext context, IRubyObject other) { - Ruby runtime = context.runtime; - if (!(other instanceof RubyMessage)) - return runtime.getFalse(); - RubyMessage message = (RubyMessage) other; - if (descriptor != message.descriptor) { - return runtime.getFalse(); - } - - for (FieldDescriptor fdef : descriptor.getFields()) { - IRubyObject thisVal = getFieldInternal(context, fdef); - IRubyObject thatVal = message.getFieldInternal(context, fdef); - IRubyObject ret = thisVal.callMethod(context, "==", thatVal); - if (!ret.isTrue()) { - return runtime.getFalse(); - } - } - return runtime.getTrue(); - } - - /* - * call-seq: - * Message.respond_to?(method_name, search_private_and_protected) => boolean - * - * Parallels method_missing, returning true when this object implements a method with the given - * method_name. - */ - @JRubyMethod(name="respond_to?", required = 1, optional = 1) - public IRubyObject respondTo(ThreadContext context, IRubyObject [] args) { - String methodName = args[0].asJavaString(); - if (descriptor.findFieldByName(methodName) != null) { - return context.runtime.getTrue(); - } - RubyDescriptor rubyDescriptor = (RubyDescriptor) getDescriptor(context, metaClass); - IRubyObject oneofDescriptor = rubyDescriptor.lookupOneof(context, args[0]); - if (!oneofDescriptor.isNil()) { - return context.runtime.getTrue(); - } - if (methodName.startsWith(CLEAR_PREFIX)) { - String strippedMethodName = methodName.substring(6); - oneofDescriptor = rubyDescriptor.lookupOneof(context, context.runtime.newSymbol(strippedMethodName)); - if (!oneofDescriptor.isNil()) { - return context.runtime.getTrue(); - } - - if (descriptor.findFieldByName(strippedMethodName) != null) { - return context.runtime.getTrue(); - } - } - if (methodName.startsWith(HAS_PREFIX) && methodName.endsWith(QUESTION_MARK)) { - String strippedMethodName = methodName.substring(4, methodName.length() - 1); - FieldDescriptor fieldDescriptor = descriptor.findFieldByName(strippedMethodName); - if (fieldDescriptor != null && - (!proto3 || fieldDescriptor.getContainingOneof() == null || fieldDescriptor - .getContainingOneof().isSynthetic()) && - fieldDescriptor.hasPresence()) { - return context.runtime.getTrue(); - } - oneofDescriptor = rubyDescriptor.lookupOneof(context, RubyString.newString(context.runtime, strippedMethodName)); - if (!oneofDescriptor.isNil()) { - return context.runtime.getTrue(); - } - } - if (methodName.endsWith(AS_VALUE_SUFFIX)) { - FieldDescriptor fieldDescriptor = descriptor.findFieldByName( - methodName.substring(0, methodName.length() - 9)); - if (fieldDescriptor != null && isWrappable(fieldDescriptor)) { - return context.runtime.getTrue(); - } - } - if (methodName.endsWith(CONST_SUFFIX)) { - FieldDescriptor fieldDescriptor = descriptor.findFieldByName( - methodName.substring(0, methodName.length() - 6)); - if (fieldDescriptor != null) { - if (fieldDescriptor.getType() == FieldDescriptor.Type.ENUM) { - return context.runtime.getTrue(); - } - } - } - if (methodName.endsWith(Utils.EQUAL_SIGN)) { - String strippedMethodName = methodName.substring(0, methodName.length() - 1); - FieldDescriptor fieldDescriptor = descriptor.findFieldByName(strippedMethodName); - if (fieldDescriptor != null) { - return context.runtime.getTrue(); - } - if (strippedMethodName.endsWith(AS_VALUE_SUFFIX)) { - strippedMethodName = methodName.substring(0, strippedMethodName.length() - 9); - fieldDescriptor = descriptor.findFieldByName(strippedMethodName); - if (fieldDescriptor != null && isWrappable(fieldDescriptor)) { - return context.runtime.getTrue(); - } - } - } - boolean includePrivate = false; - if (args.length == 2) { - includePrivate = context.runtime.getTrue().equals(args[1]); - } - return metaClass.respondsToMethod(methodName, includePrivate) ? context.runtime.getTrue() : context.runtime.getFalse(); - } - - /* - * call-seq: - * Message.method_missing(*args) - * - * Provides accessors and setters and methods to clear and check for presence of - * message fields according to their field names. - * - * For any field whose name does not conflict with a built-in method, an - * accessor is provided with the same name as the field, and a setter is - * provided with the name of the field plus the '=' suffix. Thus, given a - * message instance 'msg' with field 'foo', the following code is valid: - * - * msg.foo = 42 - * puts msg.foo - * - * This method also provides read-only accessors for oneofs. If a oneof exists - * with name 'my_oneof', then msg.my_oneof will return a Ruby symbol equal to - * the name of the field in that oneof that is currently set, or nil if none. - * - * It also provides methods of the form 'clear_fieldname' to clear the value - * of the field 'fieldname'. For basic data types, this will set the default - * value of the field. - * - * Additionally, it provides methods of the form 'has_fieldname?', which returns - * true if the field 'fieldname' is set in the message object, else false. For - * 'proto3' syntax, calling this for a basic type field will result in an error. - */ - @JRubyMethod(name = "method_missing", rest = true) - public IRubyObject methodMissing(ThreadContext context, IRubyObject[] args) { - Ruby runtime = context.runtime; - String methodName = args[0].asJavaString(); - RubyDescriptor rubyDescriptor = (RubyDescriptor) getDescriptor(context, metaClass); - - if (args.length == 1) { - // If we find a Oneof return it's name (use lookupOneof because it has an index) - IRubyObject oneofDescriptor = rubyDescriptor.lookupOneof(context, args[0]); - - if (!oneofDescriptor.isNil()) { - RubyOneofDescriptor rubyOneofDescriptor = (RubyOneofDescriptor) oneofDescriptor; - OneofDescriptor ood = rubyOneofDescriptor.getDescriptor(); - - // Check to see if we set this through ruby - FieldDescriptor fieldDescriptor = oneofCases.get(ood); - - if (fieldDescriptor == null) { - // See if we set this from decoding a message - fieldDescriptor = builder.getOneofFieldDescriptor(ood); - - if (fieldDescriptor == null) { - return context.nil; - } else { - // Cache it so we don't need to do multiple checks next time - oneofCases.put(ood, fieldDescriptor); - return runtime.newSymbol(fieldDescriptor.getName()); - } - } else { - return runtime.newSymbol(fieldDescriptor.getName()); - } - } - - // If we find a field return its value - FieldDescriptor fieldDescriptor = descriptor.findFieldByName(methodName); - - if (fieldDescriptor != null) { - return getFieldInternal(context, fieldDescriptor); - } - - if (methodName.startsWith(CLEAR_PREFIX)) { - methodName = methodName.substring(6); - oneofDescriptor = rubyDescriptor.lookupOneof(context, runtime.newSymbol(methodName)); - if (!oneofDescriptor.isNil()) { - fieldDescriptor = oneofCases.get(((RubyOneofDescriptor) oneofDescriptor).getDescriptor()); - if (fieldDescriptor == null) { - // Clearing an already cleared oneof; return here to avoid NoMethodError. - return context.nil; - } - } - - if (fieldDescriptor == null) { - fieldDescriptor = descriptor.findFieldByName(methodName); - } - - if (fieldDescriptor != null) { - return clearFieldInternal(context, fieldDescriptor); - } - - } else if (methodName.startsWith(HAS_PREFIX) && methodName.endsWith(QUESTION_MARK)) { - methodName = methodName.substring(4, methodName.length() - 1); // Trim "has_" and "?" off the field name - oneofDescriptor = rubyDescriptor.lookupOneof(context, runtime.newSymbol(methodName)); - if (!oneofDescriptor.isNil()) { - RubyOneofDescriptor rubyOneofDescriptor = (RubyOneofDescriptor) oneofDescriptor; - return oneofCases.containsKey(rubyOneofDescriptor.getDescriptor()) ? runtime.getTrue() : runtime.getFalse(); - } - - fieldDescriptor = descriptor.findFieldByName(methodName); - - if (fieldDescriptor != null && - (!proto3 || fieldDescriptor.getContainingOneof() == null || fieldDescriptor - .getContainingOneof().isSynthetic()) && - fieldDescriptor.hasPresence()) { - return fields.containsKey(fieldDescriptor) ? runtime.getTrue() - : runtime.getFalse(); - } - - } else if (methodName.endsWith(AS_VALUE_SUFFIX)) { - methodName = methodName.substring(0, methodName.length() - 9); - fieldDescriptor = descriptor.findFieldByName(methodName); - - if (fieldDescriptor != null && isWrappable(fieldDescriptor)) { - IRubyObject value = getFieldInternal(context, fieldDescriptor); - - if (!value.isNil() && value instanceof RubyMessage) { - return ((RubyMessage) value).index(context, runtime.newString("value")); - } - - return value; - } - - } else if (methodName.endsWith(CONST_SUFFIX)) { - methodName = methodName.substring(0, methodName.length() - 6); - fieldDescriptor = descriptor.findFieldByName(methodName); - if (fieldDescriptor != null && fieldDescriptor.getType() == FieldDescriptor.Type.ENUM) { - IRubyObject enumValue = getFieldInternal(context, fieldDescriptor); - - if (!enumValue.isNil()) { - EnumDescriptor enumDescriptor = fieldDescriptor.getEnumType(); - if (enumValue instanceof RubyRepeatedField) { - RubyArray values = (RubyArray) ((RubyRepeatedField) enumValue).toArray(context); - RubyArray retValues = runtime.newArray(values.getLength()); - for (int i = 0; i < values.getLength(); i++) { - String val = values.eltInternal(i).toString(); - retValues.store((long) i, runtime.newFixnum(enumDescriptor.findValueByName(val).getNumber())); - } - return retValues; - } - - return runtime.newFixnum(enumDescriptor.findValueByName(enumValue.asJavaString()).getNumber()); - } - } - } - - } else if (args.length == 2 && methodName.endsWith(Utils.EQUAL_SIGN)) { - - methodName = methodName.substring(0, methodName.length() - 1); // Trim equals sign - FieldDescriptor fieldDescriptor = descriptor.findFieldByName(methodName); - if (fieldDescriptor != null) { - return setFieldInternal(context, fieldDescriptor, args[1]); - } - - IRubyObject oneofDescriptor = rubyDescriptor.lookupOneof(context, RubyString.newString(context.runtime, methodName)); - if (!oneofDescriptor.isNil()) { - throw runtime.newRuntimeError("Oneof accessors are read-only."); - } - - if (methodName.endsWith(AS_VALUE_SUFFIX)) { - methodName = methodName.substring(0, methodName.length() - 9); - - fieldDescriptor = descriptor.findFieldByName(methodName); - - if (fieldDescriptor != null && isWrappable(fieldDescriptor)) { - if (args[1].isNil()) { - return setFieldInternal(context, fieldDescriptor, args[1]); - } - - RubyClass typeClass = (RubyClass) ((RubyDescriptor) getDescriptorForField(context, fieldDescriptor)).msgclass(context); - RubyMessage msg = (RubyMessage) typeClass.newInstance(context, Block.NULL_BLOCK); - msg.indexSet(context, runtime.newString("value"), args[1]); - return setFieldInternal(context, fieldDescriptor, msg); - } - } - - } - - return Helpers.invokeSuper(context, this, metaClass, "method_missing", args, Block.NULL_BLOCK); - } - - /** - * call-seq: - * Message.dup => new_message - * Performs a shallow copy of this message and returns the new copy. - */ - @JRubyMethod - public IRubyObject dup(ThreadContext context) { - RubyMessage dup = (RubyMessage) metaClass.newInstance(context, Block.NULL_BLOCK); - for (FieldDescriptor fieldDescriptor : this.descriptor.getFields()) { - if (fieldDescriptor.isRepeated()) { - dup.fields.put(fieldDescriptor, this.getRepeatedField(context, fieldDescriptor)); - } else if (fields.containsKey(fieldDescriptor)) { - dup.setFieldInternal(context, fieldDescriptor, fields.get(fieldDescriptor)); - } else if (this.builder.hasField(fieldDescriptor)) { - dup.fields.put(fieldDescriptor, wrapField(context, fieldDescriptor, this.builder.getField(fieldDescriptor))); - } - } - return dup; - } - - /* - * call-seq: - * Message.descriptor => descriptor - * - * Class method that returns the Descriptor instance corresponding to this - * message class's type. - */ - @JRubyMethod(name = "descriptor", meta = true) - public static IRubyObject getDescriptor(ThreadContext context, IRubyObject recv) { - return ((RubyClass) recv).getInstanceVariable(Utils.DESCRIPTOR_INSTANCE_VAR); - } - - /* - * call-seq: - * MessageClass.encode(msg, options = {}) => bytes - * - * Encodes the given message object to its serialized form in protocol buffers - * wire format. - * @param options [Hash] options for the encoder - * recursion_limit: set to maximum encoding depth for message (default is 64) - */ - @JRubyMethod(required = 1, optional = 1, meta = true) - public static IRubyObject encode(ThreadContext context, IRubyObject recv, IRubyObject[] args) { - if (recv != args[0].getMetaClass()) { - throw context.runtime.newArgumentError("Tried to encode a " + args[0].getMetaClass() + " message with " + recv); - } - RubyMessage message = (RubyMessage) args[0]; - int recursionLimitInt = SINK_MAXIMUM_NESTING; - - if (args.length > 1) { - RubyHash options = (RubyHash) args[1]; - IRubyObject recursionLimit = options.fastARef(context.runtime.newSymbol("recursion_limit")); - - if (recursionLimit != null) { - recursionLimitInt = ((RubyNumeric) recursionLimit).getIntValue(); - } - } - return context.runtime.newString(new ByteList(message.build(context, 0, recursionLimitInt).toByteArray())); - } - - /* - * call-seq: - * MessageClass.decode(data, options = {}) => message - * - * Decodes the given data (as a string containing bytes in protocol buffers wire - * format) under the interpretation given by this message class's definition - * and returns a message object with the corresponding field values. - * @param options [Hash] options for the decoder - * recursion_limit: set to maximum decoding depth for message (default is 100) - */ - @JRubyMethod(required = 1, optional = 1, meta = true) - public static IRubyObject decode(ThreadContext context, IRubyObject recv, IRubyObject[] args) { - IRubyObject data = args[0]; - byte[] bin = data.convertToString().getBytes(); - CodedInputStream input = CodedInputStream.newInstance(bin); - RubyMessage ret = (RubyMessage) ((RubyClass) recv).newInstance(context, Block.NULL_BLOCK); - - if (args.length == 2) { - if (!(args[1] instanceof RubyHash)) { - throw context.runtime.newArgumentError("Expected hash arguments."); - } - - IRubyObject recursionLimit = ((RubyHash) args[1]).fastARef(context.runtime.newSymbol("recursion_limit")); - if (recursionLimit != null) { - input.setRecursionLimit(((RubyNumeric) recursionLimit).getIntValue()); - } - } - - try { - ret.builder.mergeFrom(input); - } catch (Exception e) { - throw RaiseException.from(context.runtime, (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::ParseError"), e.getMessage()); - } - - if (!ret.proto3) { - // Need to reset unknown values in repeated enum fields - ret.builder.getUnknownFields().asMap().forEach((i, values) -> { - FieldDescriptor fd = ret.builder.getDescriptorForType().findFieldByNumber(i); - if (fd != null && fd.isRepeated() && fd.getType() == FieldDescriptor.Type.ENUM) { - EnumDescriptor ed = fd.getEnumType(); - values.getVarintList().forEach(value -> { - ret.builder.addRepeatedField(fd, ed.findValueByNumberCreatingIfUnknown(value.intValue())); - }); - } - }); - } - - return ret; - } - - /* - * call-seq: - * MessageClass.encode_json(msg, options = {}) => json_string - * - * Encodes the given message object into its serialized JSON representation. - * @param options [Hash] options for the decoder - * preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase) - * emit_defaults: set true to emit 0/false values (default is to omit them) - */ - @JRubyMethod(name = "encode_json", required = 1, optional = 1, meta = true) - public static IRubyObject encodeJson(ThreadContext context, IRubyObject recv, IRubyObject[] args) { - Ruby runtime = context.runtime; - RubyMessage message = (RubyMessage) args[0]; - JsonFormat.Printer printer = JsonFormat.printer().omittingInsignificantWhitespace(); - String result; - - if (args.length > 1) { - RubyHash options; - if (args[1] instanceof RubyHash) { - options = (RubyHash) args[1]; - } else if (args[1].respondsTo("to_h")) { - options = (RubyHash) args[1].callMethod(context, "to_h"); - } else { - throw runtime.newArgumentError("Expected hash arguments."); - } - - IRubyObject emitDefaults = options.fastARef(runtime.newSymbol("emit_defaults")); - IRubyObject preserveNames = options.fastARef(runtime.newSymbol("preserve_proto_fieldnames")); - - if (emitDefaults != null && emitDefaults.isTrue()) { - printer = printer.includingDefaultValueFields(); - } - - if (preserveNames != null && preserveNames.isTrue()) { - printer = printer.preservingProtoFieldNames(); - } - } - printer = printer.usingTypeRegistry(JsonFormat.TypeRegistry.newBuilder().add(message.descriptor).build()); - - try { - result = printer.print(message.build(context, 0, SINK_MAXIMUM_NESTING)); - } catch (InvalidProtocolBufferException e) { - throw runtime.newRuntimeError(e.getMessage()); - } catch (IllegalArgumentException e) { - throw createParseError(context, e.getMessage()); - } - - return runtime.newString(result); - } - - /* - * call-seq: - * MessageClass.decode_json(data, options = {}) => message - * - * Decodes the given data (as a string containing bytes in protocol buffers wire - * format) under the interpretation given by this message class's definition - * and returns a message object with the corresponding field values. - * - * @param options [Hash] options for the decoder - * ignore_unknown_fields: set true to ignore unknown fields (default is to - * raise an error) - */ - @JRubyMethod(name = "decode_json", required = 1, optional = 1, meta = true) - public static IRubyObject decodeJson(ThreadContext context, IRubyObject recv, IRubyObject[] args) { - Ruby runtime = context.runtime; - boolean ignoreUnknownFields = false; - IRubyObject data = args[0]; - JsonFormat.Parser parser = JsonFormat.parser(); - - if (args.length == 2) { - if (!(args[1] instanceof RubyHash)) { - throw runtime.newArgumentError("Expected hash arguments."); - } - - IRubyObject ignoreSetting = ((RubyHash) args[1]).fastARef(runtime.newSymbol("ignore_unknown_fields")); - if (ignoreSetting != null && ignoreSetting.isTrue()) { - parser = parser.ignoringUnknownFields(); - } - } - - if (!(data instanceof RubyString)) { - throw runtime.newArgumentError("Expected string for JSON data."); - } - - RubyMessage ret = (RubyMessage) ((RubyClass) recv).newInstance(context, Block.NULL_BLOCK); - parser = parser.usingTypeRegistry(JsonFormat.TypeRegistry.newBuilder().add(ret.descriptor).build()); - - try { - parser.merge(data.asJavaString(), ret.builder); - } catch(InvalidProtocolBufferException e) { - throw createParseError(context, e.getMessage().replace("Cannot find", "No such")); - } - - if (isWrapper(ret.descriptor)) { - throw runtime.newRuntimeError("Parsing a wrapper type from JSON at the top level does not work."); - } - - return ret; - } - - @JRubyMethod(name = "to_h") - public IRubyObject toHash(ThreadContext context) { - Ruby runtime = context.runtime; - RubyHash ret = RubyHash.newHash(runtime); - for (FieldDescriptor fdef : this.descriptor.getFields()) { - IRubyObject value = getFieldInternal(context, fdef, proto3); - - if (!value.isNil()) { - if (fdef.isRepeated() && !fdef.isMapField()) { - if (!proto3 && ((RubyRepeatedField) value).size() == 0) continue; // Don't output empty repeated fields for proto2 - if (fdef.getType() != FieldDescriptor.Type.MESSAGE) { - value = Helpers.invoke(context, value, "to_a"); - } else { - RubyArray ary = value.convertToArray(); - for (int i = 0; i < ary.size(); i++) { - IRubyObject submsg = Helpers.invoke(context, ary.eltInternal(i), "to_h"); - ary.eltInternalSet(i, submsg); - } - - value = ary.to_ary(); - } - } else if (value.respondsTo("to_h")) { - value = Helpers.invoke(context, value, "to_h"); - } else if (value.respondsTo("to_a")) { - value = Helpers.invoke(context, value, "to_a"); - } - } - if (proto3 || !value.isNil()) { - ret.fastASet(runtime.newSymbol(fdef.getName()), value); - } - } - return ret; - } - - protected DynamicMessage build(ThreadContext context, int depth, int recursionLimit) { - if (depth >= recursionLimit) { - throw context.runtime.newRuntimeError("Recursion limit exceeded during encoding."); - } - - RubySymbol typeBytesSymbol = RubySymbol.newSymbol(context.runtime, "TYPE_BYTES"); - - // Handle the typical case where the fields.keySet contain the fieldDescriptors - for (FieldDescriptor fieldDescriptor : fields.keySet()) { - IRubyObject value = fields.get(fieldDescriptor); - - if (value instanceof RubyMap) { - builder.clearField(fieldDescriptor); - RubyDescriptor mapDescriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); - for (DynamicMessage kv : ((RubyMap) value).build(context, mapDescriptor, depth, recursionLimit)) { - builder.addRepeatedField(fieldDescriptor, kv); - } - - } else if (value instanceof RubyRepeatedField) { - RubyRepeatedField repeatedField = (RubyRepeatedField) value; - - builder.clearField(fieldDescriptor); - for (int i = 0; i < repeatedField.size(); i++) { - Object item = convert(context, fieldDescriptor, repeatedField.get(i), depth, recursionLimit, - /*isDefaultValueForBytes*/ false); - builder.addRepeatedField(fieldDescriptor, item); - } - - } else if (!value.isNil()) { - /** - * Detect the special case where default_value strings are provided for byte fields. - * If so, disable normal string encoding behavior within convert. - * For a more detailed explanation of other possible workarounds, see the comments - * above {@code com.google.protobuf.Internal#stringDefaultValue() - * stringDefaultValue}. - */ - boolean isDefaultStringForBytes = false; - if (DEFAULT_VALUE.equals(fieldDescriptor.getFullName())) { - FieldDescriptor enumFieldDescriptorForType = - this.builder.getDescriptorForType().findFieldByName(TYPE); - if (typeBytesSymbol.equals(fields.get(enumFieldDescriptorForType))) { - isDefaultStringForBytes = true; - } - } - builder.setField(fieldDescriptor, convert(context, fieldDescriptor, value, depth, recursionLimit, isDefaultStringForBytes)); - } - } - - // Handle cases where {@code fields} doesn't contain the value until after getFieldInternal - // is called - typical of a deserialized message. Skip non-maps and descriptors that already - // have an entry in {@code fields}. - for (FieldDescriptor fieldDescriptor : descriptor.getFields()) { - if (!fieldDescriptor.isMapField()) { - continue; - } - IRubyObject value = fields.get(fieldDescriptor); - if (value!=null) { - continue; - } - value = getFieldInternal(context, fieldDescriptor); - if (value instanceof RubyMap) { - builder.clearField(fieldDescriptor); - RubyDescriptor mapDescriptor = (RubyDescriptor) getDescriptorForField(context, - fieldDescriptor); - for (DynamicMessage kv : ((RubyMap) value).build(context, mapDescriptor, depth, recursionLimit)) { - builder.addRepeatedField(fieldDescriptor, kv); - } - } - } - return builder.build(); - } - - // Internal use only, called by Google::Protobuf.deep_copy - protected IRubyObject deepCopy(ThreadContext context) { - RubyMessage copy = (RubyMessage) metaClass.newInstance(context, Block.NULL_BLOCK); - for (FieldDescriptor fdef : descriptor.getFields()) { - if (fdef.isRepeated()) { - copy.fields.put(fdef, this.getRepeatedField(context, fdef).deepCopy(context)); - } else if (fields.containsKey(fdef)) { - copy.setFieldInternal(context, fdef, fields.get(fdef)); - } else if (builder.hasField(fdef)) { - copy.fields.put(fdef, wrapField(context, fdef, builder.getField(fdef))); - } - } - return copy; - } - - protected IRubyObject clearField(ThreadContext context, FieldDescriptor fieldDescriptor) { - validateMessageType(context, fieldDescriptor, "clear"); - return clearFieldInternal(context, fieldDescriptor); - } - - protected void discardUnknownFields(ThreadContext context) { - discardUnknownFields(context, builder); - } - - protected IRubyObject getField(ThreadContext context, FieldDescriptor fieldDescriptor) { - validateMessageType(context, fieldDescriptor, "get"); - return getFieldInternal(context, fieldDescriptor); - } - - protected IRubyObject hasField(ThreadContext context, FieldDescriptor fieldDescriptor) { - validateMessageType(context, fieldDescriptor, "has?"); - if (!fieldDescriptor.hasPresence()) { - throw context.runtime.newArgumentError("does not track presence"); - } - return fields.containsKey(fieldDescriptor) ? context.runtime.getTrue() : context.runtime.getFalse(); - } - - protected IRubyObject setField(ThreadContext context, FieldDescriptor fieldDescriptor, IRubyObject value) { - validateMessageType(context, fieldDescriptor, "set"); - return setFieldInternal(context, fieldDescriptor, value); - } - - private RubyRepeatedField getRepeatedField(ThreadContext context, FieldDescriptor fieldDescriptor) { - if (fields.containsKey(fieldDescriptor)) { - return (RubyRepeatedField) fields.get(fieldDescriptor); - } - int count = this.builder.getRepeatedFieldCount(fieldDescriptor); - RubyRepeatedField ret = repeatedFieldForFieldDescriptor(context, fieldDescriptor); - for (int i = 0; i < count; i++) { - ret.push(context, new IRubyObject[] {wrapField(context, fieldDescriptor, this.builder.getRepeatedField(fieldDescriptor, i))}); - } - fields.put(fieldDescriptor, ret); - return ret; - } - - private IRubyObject buildFrom(ThreadContext context, DynamicMessage dynamicMessage) { - this.builder.mergeFrom(dynamicMessage); - return this; - } - - private IRubyObject clearFieldInternal(ThreadContext context, FieldDescriptor fieldDescriptor) { - OneofDescriptor ood = fieldDescriptor.getContainingOneof(); - if (ood != null) oneofCases.remove(ood); - fields.remove(fieldDescriptor); - builder.clearField(fieldDescriptor); - return context.nil; - } - - private void discardUnknownFields(ThreadContext context, Message.Builder messageBuilder) { - messageBuilder.setUnknownFields(UnknownFieldSet.getDefaultInstance()); - messageBuilder.getAllFields().forEach((fd, value) -> { - if (fd.getType() == FieldDescriptor.Type.MESSAGE) { - if (fd.isRepeated()) { - messageBuilder.clearField(fd); - ((List) value).forEach((val) -> { - Message.Builder submessageBuilder = ((DynamicMessage) val).toBuilder(); - discardUnknownFields(context, submessageBuilder); - messageBuilder.addRepeatedField(fd, submessageBuilder.build()); - }); - } else { - Message.Builder submessageBuilder = ((DynamicMessage) value).toBuilder(); - discardUnknownFields(context, submessageBuilder); - messageBuilder.setField(fd, submessageBuilder.build()); - } - } - }); - } - - private FieldDescriptor findField(ThreadContext context, IRubyObject fieldName) { - return findField(context, fieldName, false); - } - - private FieldDescriptor findField(ThreadContext context, IRubyObject fieldName, boolean ignoreUnknownField) { - String nameStr = fieldName.asJavaString(); - FieldDescriptor ret = this.descriptor.findFieldByName(nameStr); - if (ret == null && !ignoreUnknownField) { - throw context.runtime.newArgumentError("field " + fieldName.asJavaString() + " is not found"); - } - return ret; - } - - // convert a ruby object to protobuf type, skip type check since it is checked on the way in - private Object convert(ThreadContext context, - FieldDescriptor fieldDescriptor, - IRubyObject value, int depth, int recursionLimit, - boolean isDefaultStringForBytes) { - Object val = null; - switch (fieldDescriptor.getType()) { - case INT32: - case SFIXED32: - case SINT32: - val = RubyNumeric.num2int(value); - break; - case INT64: - case SFIXED64: - case SINT64: - val = RubyNumeric.num2long(value); - break; - case FIXED32: - case UINT32: - val = Utils.num2uint(value); - break; - case FIXED64: - case UINT64: - val = Utils.num2ulong(context.runtime, value); - break; - case FLOAT: - val = (float) RubyNumeric.num2dbl(value); - break; - case DOUBLE: - val = (double) RubyNumeric.num2dbl(value); - break; - case BOOL: - val = value.isTrue(); - break; - case BYTES: - val = ByteString.copyFrom(((RubyString) value).getBytes()); - break; - case STRING: - if (isDefaultStringForBytes) { - val = ((RubyString) value).getByteList().toString(); - } else { - val = value.asJavaString(); - } - break; - case MESSAGE: - val = ((RubyMessage) value).build(context, depth + 1, recursionLimit); - break; - case ENUM: - EnumDescriptor enumDescriptor = fieldDescriptor.getEnumType(); - if (Utils.isRubyNum(value)) { - val = enumDescriptor.findValueByNumberCreatingIfUnknown(RubyNumeric.num2int(value)); - } else { - val = enumDescriptor.findValueByName(value.asJavaString()); - } - break; - default: - break; - } - - return val; - } - - private static RaiseException createParseError(ThreadContext context, String message) { - if (parseErrorClass == null) { - parseErrorClass = (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::ParseError"); - } - return RaiseException.from(context.runtime, parseErrorClass, message); - } - - private IRubyObject wrapField(ThreadContext context, FieldDescriptor fieldDescriptor, Object value) { - return wrapField(context, fieldDescriptor, value, false); - } - - private IRubyObject wrapField(ThreadContext context, FieldDescriptor fieldDescriptor, Object value, boolean encodeBytes) { - if (value == null) { - return context.runtime.getNil(); - } - Ruby runtime = context.runtime; - - switch (fieldDescriptor.getType()) { - case INT32: - case INT64: - case FIXED32: - case SINT32: - case FIXED64: - case SINT64: - case SFIXED64: - case SFIXED32: - case UINT32: - case UINT64: - case FLOAT: - case DOUBLE: - case BOOL: - case BYTES: - case STRING: - return Utils.wrapPrimaryValue(context, fieldDescriptor.getType(), value, encodeBytes); - case MESSAGE: - RubyClass typeClass = (RubyClass) ((RubyDescriptor) getDescriptorForField(context, fieldDescriptor)).msgclass(context); - RubyMessage msg = (RubyMessage) typeClass.newInstance(context, Block.NULL_BLOCK); - return msg.buildFrom(context, (DynamicMessage) value); - case ENUM: - EnumValueDescriptor enumValueDescriptor = (EnumValueDescriptor) value; - if (enumValueDescriptor.getIndex() == -1) { // UNKNOWN ENUM VALUE - return runtime.newFixnum(enumValueDescriptor.getNumber()); - } - return runtime.newSymbol(enumValueDescriptor.getName()); - default: - return runtime.newString(value.toString()); - } - } - - private RubyRepeatedField repeatedFieldForFieldDescriptor(ThreadContext context, FieldDescriptor fieldDescriptor) { - IRubyObject typeClass = context.runtime.getNilClass(); - IRubyObject descriptor = getDescriptorForField(context, fieldDescriptor); - FieldDescriptor.Type type = fieldDescriptor.getType(); - - if (type == FieldDescriptor.Type.MESSAGE) { - typeClass = ((RubyDescriptor) descriptor).msgclass(context); - - } else if (type == FieldDescriptor.Type.ENUM) { - typeClass = ((RubyEnumDescriptor) descriptor).enummodule(context); - } - - RubyRepeatedField field = new RubyRepeatedField(context.runtime, cRepeatedField, type, typeClass); - field.setName(fieldDescriptor.getName()); - - return field; - } - - private IRubyObject getFieldInternal(ThreadContext context, FieldDescriptor fieldDescriptor) { - return getFieldInternal(context, fieldDescriptor, true); - } - - private IRubyObject getFieldInternal(ThreadContext context, FieldDescriptor fieldDescriptor, - boolean returnDefaults) { - OneofDescriptor oneofDescriptor = fieldDescriptor.getContainingOneof(); - if (oneofDescriptor != null) { - if (oneofCases.get(oneofDescriptor) == fieldDescriptor) { - IRubyObject value = fields.get(fieldDescriptor); - if (value == null) { - FieldDescriptor oneofCase = builder.getOneofFieldDescriptor(oneofDescriptor); - if (oneofCase != null) { - Object builderValue = builder.getField(oneofCase); - if (builderValue != null) { - boolean encodeBytes = oneofCase.hasDefaultValue() && builderValue.equals(oneofCase.getDefaultValue()); - value = wrapField(context, oneofCase, builderValue, encodeBytes); - } - } - if (value == null) { - return context.nil; - } else { - return value; - } - } else { - return value; - } - } else { - FieldDescriptor oneofCase = builder.getOneofFieldDescriptor(oneofDescriptor); - if (oneofCase != fieldDescriptor) { - if (fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE - || !returnDefaults) { - return context.nil; - } else { - return wrapField(context, fieldDescriptor, - fieldDescriptor.getDefaultValue(), true); - } - } - if (returnDefaults || builder.hasField(fieldDescriptor)) { - Object rawValue = builder.getField(oneofCase); - boolean encodeBytes = oneofCase.hasDefaultValue() && rawValue.equals(oneofCase.getDefaultValue()); - IRubyObject value = wrapField(context, oneofCase, rawValue, encodeBytes); - fields.put(fieldDescriptor, value); - return value; - } else { - return context.nil; - } - } - } - - if (fieldDescriptor.isMapField()) { - RubyMap map = (RubyMap) fields.get(fieldDescriptor); - if (map == null) { - map = newMapForField(context, fieldDescriptor); - int mapSize = this.builder.getRepeatedFieldCount(fieldDescriptor); - FieldDescriptor keyField = fieldDescriptor.getMessageType().findFieldByNumber(1); - FieldDescriptor valueField = fieldDescriptor.getMessageType().findFieldByNumber(2); - RubyDescriptor kvDescriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); - RubyClass kvClass = (RubyClass) kvDescriptor.msgclass(context); - for (int i = 0; i < mapSize; i++) { - RubyMessage kvMessage = (RubyMessage) kvClass.newInstance(context, Block.NULL_BLOCK); - DynamicMessage message = (DynamicMessage) this.builder.getRepeatedField(fieldDescriptor, i); - kvMessage.buildFrom(context, message); - map.indexSet(context, kvMessage.getField(context, keyField), kvMessage.getField(context, valueField)); - } + final RubyMap map = newMapForField(context, fieldDescriptor); + map.mergeIntoSelf(context, value); fields.put(fieldDescriptor, map); - } - return map; - } - - if (fieldDescriptor.isRepeated()) { - return getRepeatedField(context, fieldDescriptor); - } - - if (fieldDescriptor.getType() != FieldDescriptor.Type.MESSAGE || - builder.hasField(fieldDescriptor) || fields.containsKey(fieldDescriptor)) { - if (fields.containsKey(fieldDescriptor)) { - return fields.get(fieldDescriptor); - } else if (returnDefaults || builder.hasField(fieldDescriptor)) { - Object rawValue = builder.getField(fieldDescriptor); - boolean encodeBytes = fieldDescriptor.hasDefaultValue() && rawValue.equals(fieldDescriptor.getDefaultValue()); - IRubyObject value = wrapField(context, fieldDescriptor, rawValue, encodeBytes); - if (builder.hasField(fieldDescriptor)) { - fields.put(fieldDescriptor, value); - } - return value; - } - } - return context.nil; - } - - private IRubyObject setFieldInternal(ThreadContext context, FieldDescriptor fieldDescriptor, IRubyObject value) { - testFrozen("can't modify frozen " + getMetaClass()); - - if (fieldDescriptor.isMapField()) { - if (!(value instanceof RubyMap)) { - throw Utils.createTypeError(context, "Expected Map instance"); - } - RubyMap thisMap = (RubyMap) getFieldInternal(context, fieldDescriptor); - thisMap.mergeIntoSelf(context, value); - - } else if (fieldDescriptor.isRepeated()) { - if (value instanceof RubyRepeatedField) { - fields.put(fieldDescriptor, value); - } else { - throw Utils.createTypeError(context, "Expected repeated field array"); - } - - } else { - boolean addValue = true; - FieldDescriptor.Type fieldType = fieldDescriptor.getType(); - OneofDescriptor oneofDescriptor = fieldDescriptor.getContainingOneof(); - - // Determine the typeclass, if any - IRubyObject typeClass = context.runtime.getObject(); - if (fieldType == FieldDescriptor.Type.MESSAGE) { - typeClass = ((RubyDescriptor) getDescriptorForField(context, fieldDescriptor)).msgclass(context); - if (value.isNil()){ - addValue = false; - } - } else if (fieldType == FieldDescriptor.Type.ENUM) { - typeClass = ((RubyEnumDescriptor) getDescriptorForField(context, fieldDescriptor)).enummodule(context); - value = enumToSymbol(context, fieldDescriptor.getEnumType(), value); - } - - if (oneofDescriptor != null) { - FieldDescriptor oneofCase = oneofCases.get(oneofDescriptor); - - // Remove the existing field if we are setting a different field in the Oneof - if (oneofCase != null && oneofCase != fieldDescriptor) { - fields.remove(oneofCase); + } else if (fieldDescriptor.isRepeated()) { + if (!(value instanceof RubyArray)) + throw runtime.newArgumentError( + "Expected array as initializer value for repeated field '" + + key.asJavaString() + + "' (given " + + value.getMetaClass() + + ")."); + fields.put(fieldDescriptor, rubyToRepeatedField(context, fieldDescriptor, value)); + } else { + OneofDescriptor oneof = fieldDescriptor.getContainingOneof(); + if (oneof != null) { + oneofCases.put(oneof, fieldDescriptor); } - // Keep track of what Oneofs are set - if (value.isNil()) { - oneofCases.remove(oneofDescriptor); - if (!oneofDescriptor.isSynthetic()) { - addValue = false; - } + if (value instanceof RubyHash + && fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE) { + RubyDescriptor descriptor = + (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); + RubyClass typeClass = (RubyClass) descriptor.msgclass(context); + value = (IRubyObject) typeClass.newInstance(context, value, Block.NULL_BLOCK); + fields.put(fieldDescriptor, value); } else { - oneofCases.put(oneofDescriptor, fieldDescriptor); + indexSet(context, key, value); } + } } + }, + null); + } + return this; + } - if (addValue) { - value = Utils.checkType(context, fieldType, fieldDescriptor.getName(), value, (RubyModule) typeClass); - fields.put(fieldDescriptor, value); - } else { - fields.remove(fieldDescriptor); - } - } - return context.nil; + /* + * call-seq: + * Message.[]=(index, value) + * + * Sets a field's value by field name. The provided field name should be a + * string. + */ + @JRubyMethod(name = "[]=") + public IRubyObject indexSet(ThreadContext context, IRubyObject fieldName, IRubyObject value) { + FieldDescriptor fieldDescriptor = findField(context, fieldName); + return setFieldInternal(context, fieldDescriptor, value); + } + + /* + * call-seq: + * Message.[](index) => value + * + * Accesses a field's value by field name. The provided field name should be a + * string. + */ + @JRubyMethod(name = "[]") + public IRubyObject index(ThreadContext context, IRubyObject fieldName) { + FieldDescriptor fieldDescriptor = findField(context, fieldName); + return getFieldInternal(context, fieldDescriptor); + } + + /* + * call-seq: + * Message.inspect => string + * + * Returns a human-readable string representing this message. It will be + * formatted as "<MessageType: field1: value1, field2: value2, ...>". Each + * field's value is represented according to its own #inspect method. + */ + @JRubyMethod(name = {"inspect", "to_s"}) + public IRubyObject inspect() { + ThreadContext context = getRuntime().getCurrentContext(); + String cname = metaClass.getName(); + String colon = ": "; + String comma = ", "; + StringBuilder sb = new StringBuilder("<"); + boolean addComma = false; + + sb.append(cname).append(colon); + + for (FieldDescriptor fd : descriptor.getFields()) { + if (fd.hasPresence() && !fields.containsKey(fd)) { + continue; + } + if (addComma) { + sb.append(comma); + } else { + addComma = true; + } + + sb.append(fd.getName()).append(colon); + + IRubyObject value = getFieldInternal(context, fd); + if (value instanceof RubyBoolean) { + // Booleans don't implement internal "inspect" methods so have to call handle them manually + sb.append(value.isTrue() ? "true" : "false"); + } else { + sb.append(value.inspect()); + } + } + sb.append(">"); + + return context.runtime.newString(sb.toString()); + } + + /* + * call-seq: + * Message.hash => hash_value + * + * Returns a hash value that represents this message's field values. + */ + @JRubyMethod + public IRubyObject hash(ThreadContext context) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (FieldDescriptor fd : descriptor.getFields()) { + digest.update((byte) getFieldInternal(context, fd).hashCode()); + } + return context.runtime.newFixnum(ByteBuffer.wrap(digest.digest()).getLong()); + } catch (NoSuchAlgorithmException ignore) { + return context.runtime.newFixnum(System.identityHashCode(this)); + } + } + + /* + * call-seq: + * Message.==(other) => boolean + * + * Performs a deep comparison of this message with another. Messages are equal + * if they have the same type and if each field is equal according to the :== + * method's semantics (a more efficient comparison may actually be done if the + * field is of a primitive type). + */ + @JRubyMethod(name = {"==", "eql?"}) + public IRubyObject eq(ThreadContext context, IRubyObject other) { + Ruby runtime = context.runtime; + if (!(other instanceof RubyMessage)) return runtime.getFalse(); + RubyMessage message = (RubyMessage) other; + if (descriptor != message.descriptor) { + return runtime.getFalse(); } - private IRubyObject getDescriptorForField(ThreadContext context, FieldDescriptor fieldDescriptor) { - RubyDescriptor thisRbDescriptor = (RubyDescriptor) getDescriptor(context, metaClass); - RubyFieldDescriptor fd = (RubyFieldDescriptor) thisRbDescriptor.lookup(context, context.runtime.newString(fieldDescriptor.getName())); - return fd.getSubtype(context); + for (FieldDescriptor fdef : descriptor.getFields()) { + IRubyObject thisVal = getFieldInternal(context, fdef); + IRubyObject thatVal = message.getFieldInternal(context, fdef); + IRubyObject ret = thisVal.callMethod(context, "==", thatVal); + if (!ret.isTrue()) { + return runtime.getFalse(); + } } + return runtime.getTrue(); + } - private IRubyObject enumToSymbol(ThreadContext context, EnumDescriptor enumDescriptor, IRubyObject value) { - if (value instanceof RubySymbol) { - return (RubySymbol) value; - } else if (Utils.isRubyNum(value)) { - EnumValueDescriptor enumValue = enumDescriptor.findValueByNumberCreatingIfUnknown(RubyNumeric.num2int(value)); - if (enumValue.getIndex() != -1) { - return context.runtime.newSymbol(enumValue.getName()); - } else { - return value; - } - } else if (value instanceof RubyString) { - return ((RubyString) value).intern(); - } - - return context.runtime.newSymbol("UNKNOWN"); + /* + * call-seq: + * Message.respond_to?(method_name, search_private_and_protected) => boolean + * + * Parallels method_missing, returning true when this object implements a method with the given + * method_name. + */ + @JRubyMethod(name = "respond_to?", required = 1, optional = 1) + public IRubyObject respondTo(ThreadContext context, IRubyObject[] args) { + String methodName = args[0].asJavaString(); + if (descriptor.findFieldByName(methodName) != null) { + return context.runtime.getTrue(); } - - private RubyRepeatedField rubyToRepeatedField(ThreadContext context, - FieldDescriptor fieldDescriptor, IRubyObject value) { - RubyArray arr = value.convertToArray(); - RubyRepeatedField repeatedField = repeatedFieldForFieldDescriptor(context, fieldDescriptor); - IRubyObject[] values = new IRubyObject[arr.size()]; - FieldDescriptor.Type fieldType = fieldDescriptor.getType(); - - RubyModule typeClass = null; - if (fieldType == FieldDescriptor.Type.MESSAGE) { - RubyDescriptor descriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); - typeClass = (RubyModule) descriptor.msgclass(context); - } else if (fieldType == FieldDescriptor.Type.ENUM) { - RubyEnumDescriptor enumDescriptor = (RubyEnumDescriptor) getDescriptorForField(context, fieldDescriptor); - typeClass = (RubyModule) enumDescriptor.enummodule(context); - } - - for (int i = 0; i < arr.size(); i++) { - IRubyObject item = arr.eltInternal(i); - if (item.isNil()) { - throw Utils.createTypeError(context, "nil message not allowed here."); - } - if (item instanceof RubyHash && typeClass != null) { - values[i] = ((RubyClass) typeClass).newInstance(context, item, Block.NULL_BLOCK); - } else { - if (fieldType == FieldDescriptor.Type.ENUM) { - item = enumToSymbol(context, fieldDescriptor.getEnumType(), item); - } - - values[i] = item; - } - } - repeatedField.push(context, values); - - return repeatedField; + RubyDescriptor rubyDescriptor = (RubyDescriptor) getDescriptor(context, metaClass); + IRubyObject oneofDescriptor = rubyDescriptor.lookupOneof(context, args[0]); + if (!oneofDescriptor.isNil()) { + return context.runtime.getTrue(); } + if (methodName.startsWith(CLEAR_PREFIX)) { + String strippedMethodName = methodName.substring(6); + oneofDescriptor = + rubyDescriptor.lookupOneof(context, context.runtime.newSymbol(strippedMethodName)); + if (!oneofDescriptor.isNil()) { + return context.runtime.getTrue(); + } - private RubyMap newMapForField(ThreadContext context, FieldDescriptor fieldDescriptor) { - RubyDescriptor mapDescriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); - FieldDescriptor keyField = fieldDescriptor.getMessageType().findFieldByNumber(1); - FieldDescriptor valueField = fieldDescriptor.getMessageType().findFieldByNumber(2); - IRubyObject keyType = RubySymbol.newSymbol(context.runtime, keyField.getType().name()); - IRubyObject valueType = RubySymbol.newSymbol(context.runtime, valueField.getType().name()); + if (descriptor.findFieldByName(strippedMethodName) != null) { + return context.runtime.getTrue(); + } + } + if (methodName.startsWith(HAS_PREFIX) && methodName.endsWith(QUESTION_MARK)) { + String strippedMethodName = methodName.substring(4, methodName.length() - 1); + FieldDescriptor fieldDescriptor = descriptor.findFieldByName(strippedMethodName); + if (fieldDescriptor != null + && (!proto3 + || fieldDescriptor.getContainingOneof() == null + || fieldDescriptor.getContainingOneof().isSynthetic()) + && fieldDescriptor.hasPresence()) { + return context.runtime.getTrue(); + } + oneofDescriptor = + rubyDescriptor.lookupOneof( + context, RubyString.newString(context.runtime, strippedMethodName)); + if (!oneofDescriptor.isNil()) { + return context.runtime.getTrue(); + } + } + if (methodName.endsWith(AS_VALUE_SUFFIX)) { + FieldDescriptor fieldDescriptor = + descriptor.findFieldByName(methodName.substring(0, methodName.length() - 9)); + if (fieldDescriptor != null && isWrappable(fieldDescriptor)) { + return context.runtime.getTrue(); + } + } + if (methodName.endsWith(CONST_SUFFIX)) { + FieldDescriptor fieldDescriptor = + descriptor.findFieldByName(methodName.substring(0, methodName.length() - 6)); + if (fieldDescriptor != null) { + if (fieldDescriptor.getType() == FieldDescriptor.Type.ENUM) { + return context.runtime.getTrue(); + } + } + } + if (methodName.endsWith(Utils.EQUAL_SIGN)) { + String strippedMethodName = methodName.substring(0, methodName.length() - 1); + FieldDescriptor fieldDescriptor = descriptor.findFieldByName(strippedMethodName); + if (fieldDescriptor != null) { + return context.runtime.getTrue(); + } + if (strippedMethodName.endsWith(AS_VALUE_SUFFIX)) { + strippedMethodName = methodName.substring(0, strippedMethodName.length() - 9); + fieldDescriptor = descriptor.findFieldByName(strippedMethodName); + if (fieldDescriptor != null && isWrappable(fieldDescriptor)) { + return context.runtime.getTrue(); + } + } + } + boolean includePrivate = false; + if (args.length == 2) { + includePrivate = context.runtime.getTrue().equals(args[1]); + } + return metaClass.respondsToMethod(methodName, includePrivate) + ? context.runtime.getTrue() + : context.runtime.getFalse(); + } - if (valueField.getType() == FieldDescriptor.Type.MESSAGE) { - RubyFieldDescriptor rubyFieldDescriptor = (RubyFieldDescriptor) mapDescriptor.lookup(context, - context.runtime.newString("value")); - RubyDescriptor rubyDescriptor = (RubyDescriptor) rubyFieldDescriptor.getSubtype(context); - return (RubyMap) cMap.newInstance(context, keyType, valueType, - rubyDescriptor.msgclass(context), Block.NULL_BLOCK); + /* + * call-seq: + * Message.method_missing(*args) + * + * Provides accessors and setters and methods to clear and check for presence of + * message fields according to their field names. + * + * For any field whose name does not conflict with a built-in method, an + * accessor is provided with the same name as the field, and a setter is + * provided with the name of the field plus the '=' suffix. Thus, given a + * message instance 'msg' with field 'foo', the following code is valid: + * + * msg.foo = 42 + * puts msg.foo + * + * This method also provides read-only accessors for oneofs. If a oneof exists + * with name 'my_oneof', then msg.my_oneof will return a Ruby symbol equal to + * the name of the field in that oneof that is currently set, or nil if none. + * + * It also provides methods of the form 'clear_fieldname' to clear the value + * of the field 'fieldname'. For basic data types, this will set the default + * value of the field. + * + * Additionally, it provides methods of the form 'has_fieldname?', which returns + * true if the field 'fieldname' is set in the message object, else false. For + * 'proto3' syntax, calling this for a basic type field will result in an error. + */ + @JRubyMethod(name = "method_missing", rest = true) + public IRubyObject methodMissing(ThreadContext context, IRubyObject[] args) { + Ruby runtime = context.runtime; + String methodName = args[0].asJavaString(); + RubyDescriptor rubyDescriptor = (RubyDescriptor) getDescriptor(context, metaClass); - } else if (valueField.getType() == FieldDescriptor.Type.ENUM) { - RubyFieldDescriptor rubyFieldDescriptor = (RubyFieldDescriptor) mapDescriptor.lookup(context, - context.runtime.newString("value")); - RubyEnumDescriptor rubyEnumDescriptor = (RubyEnumDescriptor) rubyFieldDescriptor.getSubtype(context); - return (RubyMap) cMap.newInstance(context, keyType, valueType, - rubyEnumDescriptor.enummodule(context), Block.NULL_BLOCK); + if (args.length == 1) { + // If we find a Oneof return it's name (use lookupOneof because it has an index) + IRubyObject oneofDescriptor = rubyDescriptor.lookupOneof(context, args[0]); + if (!oneofDescriptor.isNil()) { + RubyOneofDescriptor rubyOneofDescriptor = (RubyOneofDescriptor) oneofDescriptor; + OneofDescriptor ood = rubyOneofDescriptor.getDescriptor(); + + // Check to see if we set this through ruby + FieldDescriptor fieldDescriptor = oneofCases.get(ood); + + if (fieldDescriptor == null) { + // See if we set this from decoding a message + fieldDescriptor = builder.getOneofFieldDescriptor(ood); + + if (fieldDescriptor == null) { + return context.nil; + } else { + // Cache it so we don't need to do multiple checks next time + oneofCases.put(ood, fieldDescriptor); + return runtime.newSymbol(fieldDescriptor.getName()); + } } else { - return (RubyMap) cMap.newInstance(context, keyType, valueType, Block.NULL_BLOCK); + return runtime.newSymbol(fieldDescriptor.getName()); } - } + } - private boolean isWrappable(FieldDescriptor fieldDescriptor) { - if (fieldDescriptor.getType() != FieldDescriptor.Type.MESSAGE) return false; + // If we find a field return its value + FieldDescriptor fieldDescriptor = descriptor.findFieldByName(methodName); - return isWrapper(fieldDescriptor.getMessageType()); - } + if (fieldDescriptor != null) { + return getFieldInternal(context, fieldDescriptor); + } - private static boolean isWrapper(Descriptor messageDescriptor) { - switch(messageDescriptor.getFullName()) { - case "google.protobuf.DoubleValue": - case "google.protobuf.FloatValue": - case "google.protobuf.Int64Value": - case "google.protobuf.UInt64Value": - case "google.protobuf.Int32Value": - case "google.protobuf.UInt32Value": - case "google.protobuf.BoolValue": - case "google.protobuf.StringValue": - case "google.protobuf.BytesValue": - return true; - default: - return false; + if (methodName.startsWith(CLEAR_PREFIX)) { + methodName = methodName.substring(6); + oneofDescriptor = rubyDescriptor.lookupOneof(context, runtime.newSymbol(methodName)); + if (!oneofDescriptor.isNil()) { + fieldDescriptor = oneofCases.get(((RubyOneofDescriptor) oneofDescriptor).getDescriptor()); + if (fieldDescriptor == null) { + // Clearing an already cleared oneof; return here to avoid NoMethodError. + return context.nil; + } + } + + if (fieldDescriptor == null) { + fieldDescriptor = descriptor.findFieldByName(methodName); + } + + if (fieldDescriptor != null) { + return clearFieldInternal(context, fieldDescriptor); + } + + } else if (methodName.startsWith(HAS_PREFIX) && methodName.endsWith(QUESTION_MARK)) { + methodName = + methodName.substring( + 4, methodName.length() - 1); // Trim "has_" and "?" off the field name + oneofDescriptor = rubyDescriptor.lookupOneof(context, runtime.newSymbol(methodName)); + if (!oneofDescriptor.isNil()) { + RubyOneofDescriptor rubyOneofDescriptor = (RubyOneofDescriptor) oneofDescriptor; + return oneofCases.containsKey(rubyOneofDescriptor.getDescriptor()) + ? runtime.getTrue() + : runtime.getFalse(); + } + + fieldDescriptor = descriptor.findFieldByName(methodName); + + if (fieldDescriptor != null + && (!proto3 + || fieldDescriptor.getContainingOneof() == null + || fieldDescriptor.getContainingOneof().isSynthetic()) + && fieldDescriptor.hasPresence()) { + return fields.containsKey(fieldDescriptor) ? runtime.getTrue() : runtime.getFalse(); + } + + } else if (methodName.endsWith(AS_VALUE_SUFFIX)) { + methodName = methodName.substring(0, methodName.length() - 9); + fieldDescriptor = descriptor.findFieldByName(methodName); + + if (fieldDescriptor != null && isWrappable(fieldDescriptor)) { + IRubyObject value = getFieldInternal(context, fieldDescriptor); + + if (!value.isNil() && value instanceof RubyMessage) { + return ((RubyMessage) value).index(context, runtime.newString("value")); + } + + return value; + } + + } else if (methodName.endsWith(CONST_SUFFIX)) { + methodName = methodName.substring(0, methodName.length() - 6); + fieldDescriptor = descriptor.findFieldByName(methodName); + if (fieldDescriptor != null && fieldDescriptor.getType() == FieldDescriptor.Type.ENUM) { + IRubyObject enumValue = getFieldInternal(context, fieldDescriptor); + + if (!enumValue.isNil()) { + EnumDescriptor enumDescriptor = fieldDescriptor.getEnumType(); + if (enumValue instanceof RubyRepeatedField) { + RubyArray values = (RubyArray) ((RubyRepeatedField) enumValue).toArray(context); + RubyArray retValues = runtime.newArray(values.getLength()); + for (int i = 0; i < values.getLength(); i++) { + String val = values.eltInternal(i).toString(); + retValues.store( + (long) i, runtime.newFixnum(enumDescriptor.findValueByName(val).getNumber())); + } + return retValues; + } + + return runtime.newFixnum( + enumDescriptor.findValueByName(enumValue.asJavaString()).getNumber()); + } + } + } + + } else if (args.length == 2 && methodName.endsWith(Utils.EQUAL_SIGN)) { + + methodName = methodName.substring(0, methodName.length() - 1); // Trim equals sign + FieldDescriptor fieldDescriptor = descriptor.findFieldByName(methodName); + if (fieldDescriptor != null) { + return setFieldInternal(context, fieldDescriptor, args[1]); + } + + IRubyObject oneofDescriptor = + rubyDescriptor.lookupOneof(context, RubyString.newString(context.runtime, methodName)); + if (!oneofDescriptor.isNil()) { + throw runtime.newRuntimeError("Oneof accessors are read-only."); + } + + if (methodName.endsWith(AS_VALUE_SUFFIX)) { + methodName = methodName.substring(0, methodName.length() - 9); + + fieldDescriptor = descriptor.findFieldByName(methodName); + + if (fieldDescriptor != null && isWrappable(fieldDescriptor)) { + if (args[1].isNil()) { + return setFieldInternal(context, fieldDescriptor, args[1]); + } + + RubyClass typeClass = + (RubyClass) + ((RubyDescriptor) getDescriptorForField(context, fieldDescriptor)) + .msgclass(context); + RubyMessage msg = (RubyMessage) typeClass.newInstance(context, Block.NULL_BLOCK); + msg.indexSet(context, runtime.newString("value"), args[1]); + return setFieldInternal(context, fieldDescriptor, msg); + } } } - private void validateMessageType(ThreadContext context, FieldDescriptor fieldDescriptor, String methodName) { - if (descriptor != fieldDescriptor.getContainingType()) { - throw Utils.createTypeError(context, methodName + " method called on wrong message type"); - } + return Helpers.invokeSuper(context, this, metaClass, "method_missing", args, Block.NULL_BLOCK); + } + + /** + * call-seq: Message.dup => new_message Performs a shallow copy of this message and returns the + * new copy. + */ + @JRubyMethod + public IRubyObject dup(ThreadContext context) { + RubyMessage dup = (RubyMessage) metaClass.newInstance(context, Block.NULL_BLOCK); + for (FieldDescriptor fieldDescriptor : this.descriptor.getFields()) { + if (fieldDescriptor.isRepeated()) { + dup.fields.put(fieldDescriptor, this.getRepeatedField(context, fieldDescriptor)); + } else if (fields.containsKey(fieldDescriptor)) { + dup.setFieldInternal(context, fieldDescriptor, fields.get(fieldDescriptor)); + } else if (this.builder.hasField(fieldDescriptor)) { + dup.fields.put( + fieldDescriptor, + wrapField(context, fieldDescriptor, this.builder.getField(fieldDescriptor))); + } + } + return dup; + } + + /* + * call-seq: + * Message.descriptor => descriptor + * + * Class method that returns the Descriptor instance corresponding to this + * message class's type. + */ + @JRubyMethod(name = "descriptor", meta = true) + public static IRubyObject getDescriptor(ThreadContext context, IRubyObject recv) { + return ((RubyClass) recv).getInstanceVariable(Utils.DESCRIPTOR_INSTANCE_VAR); + } + + /* + * call-seq: + * MessageClass.encode(msg, options = {}) => bytes + * + * Encodes the given message object to its serialized form in protocol buffers + * wire format. + * @param options [Hash] options for the encoder + * recursion_limit: set to maximum encoding depth for message (default is 64) + */ + @JRubyMethod(required = 1, optional = 1, meta = true) + public static IRubyObject encode(ThreadContext context, IRubyObject recv, IRubyObject[] args) { + if (recv != args[0].getMetaClass()) { + throw context.runtime.newArgumentError( + "Tried to encode a " + args[0].getMetaClass() + " message with " + recv); + } + RubyMessage message = (RubyMessage) args[0]; + int recursionLimitInt = SINK_MAXIMUM_NESTING; + + if (args.length > 1) { + RubyHash options = (RubyHash) args[1]; + IRubyObject recursionLimit = options.fastARef(context.runtime.newSymbol("recursion_limit")); + + if (recursionLimit != null) { + recursionLimitInt = ((RubyNumeric) recursionLimit).getIntValue(); + } + } + return context.runtime.newString( + new ByteList(message.build(context, 0, recursionLimitInt).toByteArray())); + } + + /* + * call-seq: + * MessageClass.decode(data, options = {}) => message + * + * Decodes the given data (as a string containing bytes in protocol buffers wire + * format) under the interpretation given by this message class's definition + * and returns a message object with the corresponding field values. + * @param options [Hash] options for the decoder + * recursion_limit: set to maximum decoding depth for message (default is 100) + */ + @JRubyMethod(required = 1, optional = 1, meta = true) + public static IRubyObject decode(ThreadContext context, IRubyObject recv, IRubyObject[] args) { + IRubyObject data = args[0]; + byte[] bin = data.convertToString().getBytes(); + CodedInputStream input = CodedInputStream.newInstance(bin); + RubyMessage ret = (RubyMessage) ((RubyClass) recv).newInstance(context, Block.NULL_BLOCK); + + if (args.length == 2) { + if (!(args[1] instanceof RubyHash)) { + throw context.runtime.newArgumentError("Expected hash arguments."); + } + + IRubyObject recursionLimit = + ((RubyHash) args[1]).fastARef(context.runtime.newSymbol("recursion_limit")); + if (recursionLimit != null) { + input.setRecursionLimit(((RubyNumeric) recursionLimit).getIntValue()); + } } - private static RubyClass parseErrorClass; + try { + ret.builder.mergeFrom(input); + } catch (Exception e) { + throw RaiseException.from( + context.runtime, + (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::ParseError"), + e.getMessage()); + } - private static final String AS_VALUE_SUFFIX = "_as_value"; - private static final String CLEAR_PREFIX = "clear_"; - private static final String CONST_SUFFIX = "_const"; - private static final String HAS_PREFIX = "has_"; - private static final String QUESTION_MARK = "?"; - private static final int SINK_MAXIMUM_NESTING = 64; + if (!ret.proto3) { + // Need to reset unknown values in repeated enum fields + ret.builder + .getUnknownFields() + .asMap() + .forEach( + (i, values) -> { + FieldDescriptor fd = ret.builder.getDescriptorForType().findFieldByNumber(i); + if (fd != null && fd.isRepeated() && fd.getType() == FieldDescriptor.Type.ENUM) { + EnumDescriptor ed = fd.getEnumType(); + values + .getVarintList() + .forEach( + value -> { + ret.builder.addRepeatedField( + fd, ed.findValueByNumberCreatingIfUnknown(value.intValue())); + }); + } + }); + } - private Descriptor descriptor; - private DynamicMessage.Builder builder; - private Map<FieldDescriptor, IRubyObject> fields; - private Map<OneofDescriptor, FieldDescriptor> oneofCases; - private RubyClass cRepeatedField; - private RubyClass cMap; - private boolean ignoreUnknownFieldsOnInit = false; - private boolean proto3; + return ret; + } + + /* + * call-seq: + * MessageClass.encode_json(msg, options = {}) => json_string + * + * Encodes the given message object into its serialized JSON representation. + * @param options [Hash] options for the decoder + * preserve_proto_fieldnames: set true to use original fieldnames (default is to camelCase) + * emit_defaults: set true to emit 0/false values (default is to omit them) + */ + @JRubyMethod(name = "encode_json", required = 1, optional = 1, meta = true) + public static IRubyObject encodeJson( + ThreadContext context, IRubyObject recv, IRubyObject[] args) { + Ruby runtime = context.runtime; + RubyMessage message = (RubyMessage) args[0]; + JsonFormat.Printer printer = JsonFormat.printer().omittingInsignificantWhitespace(); + String result; + + if (args.length > 1) { + RubyHash options; + if (args[1] instanceof RubyHash) { + options = (RubyHash) args[1]; + } else if (args[1].respondsTo("to_h")) { + options = (RubyHash) args[1].callMethod(context, "to_h"); + } else { + throw runtime.newArgumentError("Expected hash arguments."); + } + + IRubyObject emitDefaults = options.fastARef(runtime.newSymbol("emit_defaults")); + IRubyObject preserveNames = options.fastARef(runtime.newSymbol("preserve_proto_fieldnames")); + + if (emitDefaults != null && emitDefaults.isTrue()) { + printer = printer.includingDefaultValueFields(); + } + + if (preserveNames != null && preserveNames.isTrue()) { + printer = printer.preservingProtoFieldNames(); + } + } + printer = + printer.usingTypeRegistry( + JsonFormat.TypeRegistry.newBuilder().add(message.descriptor).build()); + + try { + result = printer.print(message.build(context, 0, SINK_MAXIMUM_NESTING)); + } catch (InvalidProtocolBufferException e) { + throw runtime.newRuntimeError(e.getMessage()); + } catch (IllegalArgumentException e) { + throw createParseError(context, e.getMessage()); + } + + return runtime.newString(result); + } + + /* + * call-seq: + * MessageClass.decode_json(data, options = {}) => message + * + * Decodes the given data (as a string containing bytes in protocol buffers wire + * format) under the interpretation given by this message class's definition + * and returns a message object with the corresponding field values. + * + * @param options [Hash] options for the decoder + * ignore_unknown_fields: set true to ignore unknown fields (default is to + * raise an error) + */ + @JRubyMethod(name = "decode_json", required = 1, optional = 1, meta = true) + public static IRubyObject decodeJson( + ThreadContext context, IRubyObject recv, IRubyObject[] args) { + Ruby runtime = context.runtime; + boolean ignoreUnknownFields = false; + IRubyObject data = args[0]; + JsonFormat.Parser parser = JsonFormat.parser(); + + if (args.length == 2) { + if (!(args[1] instanceof RubyHash)) { + throw runtime.newArgumentError("Expected hash arguments."); + } + + IRubyObject ignoreSetting = + ((RubyHash) args[1]).fastARef(runtime.newSymbol("ignore_unknown_fields")); + if (ignoreSetting != null && ignoreSetting.isTrue()) { + parser = parser.ignoringUnknownFields(); + } + } + + if (!(data instanceof RubyString)) { + throw runtime.newArgumentError("Expected string for JSON data."); + } + + RubyMessage ret = (RubyMessage) ((RubyClass) recv).newInstance(context, Block.NULL_BLOCK); + parser = + parser.usingTypeRegistry(JsonFormat.TypeRegistry.newBuilder().add(ret.descriptor).build()); + + try { + parser.merge(data.asJavaString(), ret.builder); + } catch (InvalidProtocolBufferException e) { + throw createParseError(context, e.getMessage().replace("Cannot find", "No such")); + } + + if (isWrapper(ret.descriptor)) { + throw runtime.newRuntimeError( + "Parsing a wrapper type from JSON at the top level does not work."); + } + + return ret; + } + + @JRubyMethod(name = "to_h") + public IRubyObject toHash(ThreadContext context) { + Ruby runtime = context.runtime; + RubyHash ret = RubyHash.newHash(runtime); + for (FieldDescriptor fdef : this.descriptor.getFields()) { + IRubyObject value = getFieldInternal(context, fdef, proto3); + + if (!value.isNil()) { + if (fdef.isRepeated() && !fdef.isMapField()) { + if (!proto3 && ((RubyRepeatedField) value).size() == 0) + continue; // Don't output empty repeated fields for proto2 + if (fdef.getType() != FieldDescriptor.Type.MESSAGE) { + value = Helpers.invoke(context, value, "to_a"); + } else { + RubyArray ary = value.convertToArray(); + for (int i = 0; i < ary.size(); i++) { + IRubyObject submsg = Helpers.invoke(context, ary.eltInternal(i), "to_h"); + ary.eltInternalSet(i, submsg); + } + + value = ary.to_ary(); + } + } else if (value.respondsTo("to_h")) { + value = Helpers.invoke(context, value, "to_h"); + } else if (value.respondsTo("to_a")) { + value = Helpers.invoke(context, value, "to_a"); + } + } + if (proto3 || !value.isNil()) { + ret.fastASet(runtime.newSymbol(fdef.getName()), value); + } + } + return ret; + } + + protected DynamicMessage build(ThreadContext context, int depth, int recursionLimit) { + if (depth >= recursionLimit) { + throw context.runtime.newRuntimeError("Recursion limit exceeded during encoding."); + } + + RubySymbol typeBytesSymbol = RubySymbol.newSymbol(context.runtime, "TYPE_BYTES"); + + // Handle the typical case where the fields.keySet contain the fieldDescriptors + for (FieldDescriptor fieldDescriptor : fields.keySet()) { + IRubyObject value = fields.get(fieldDescriptor); + + if (value instanceof RubyMap) { + builder.clearField(fieldDescriptor); + RubyDescriptor mapDescriptor = + (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); + for (DynamicMessage kv : + ((RubyMap) value).build(context, mapDescriptor, depth, recursionLimit)) { + builder.addRepeatedField(fieldDescriptor, kv); + } + + } else if (value instanceof RubyRepeatedField) { + RubyRepeatedField repeatedField = (RubyRepeatedField) value; + + builder.clearField(fieldDescriptor); + for (int i = 0; i < repeatedField.size(); i++) { + Object item = + convert( + context, + fieldDescriptor, + repeatedField.get(i), + depth, + recursionLimit, + /*isDefaultValueForBytes*/ false); + builder.addRepeatedField(fieldDescriptor, item); + } + + } else if (!value.isNil()) { + /** + * Detect the special case where default_value strings are provided for byte fields. If so, + * disable normal string encoding behavior within convert. For a more detailed explanation + * of other possible workarounds, see the comments above {@code + * com.google.protobuf.Internal#stringDefaultValue() stringDefaultValue}. + */ + boolean isDefaultStringForBytes = false; + if (DEFAULT_VALUE.equals(fieldDescriptor.getFullName())) { + FieldDescriptor enumFieldDescriptorForType = + this.builder.getDescriptorForType().findFieldByName(TYPE); + if (typeBytesSymbol.equals(fields.get(enumFieldDescriptorForType))) { + isDefaultStringForBytes = true; + } + } + } + builder.setField( + fieldDescriptor, + convert( + context, fieldDescriptor, value, depth, recursionLimit, isDefaultStringForBytes)); + } + } + + // Handle cases where {@code fields} doesn't contain the value until after getFieldInternal + // is called - typical of a deserialized message. Skip non-maps and descriptors that already + // have an entry in {@code fields}. + for (FieldDescriptor fieldDescriptor : descriptor.getFields()) { + if (!fieldDescriptor.isMapField()) { + continue; + } + IRubyObject value = fields.get(fieldDescriptor); + if (value != null) { + continue; + } + value = getFieldInternal(context, fieldDescriptor); + if (value instanceof RubyMap) { + builder.clearField(fieldDescriptor); + RubyDescriptor mapDescriptor = + (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); + for (DynamicMessage kv : + ((RubyMap) value).build(context, mapDescriptor, depth, recursionLimit)) { + builder.addRepeatedField(fieldDescriptor, kv); + } + } + } + return builder.build(); + } + + // Internal use only, called by Google::Protobuf.deep_copy + protected IRubyObject deepCopy(ThreadContext context) { + RubyMessage copy = (RubyMessage) metaClass.newInstance(context, Block.NULL_BLOCK); + for (FieldDescriptor fdef : descriptor.getFields()) { + if (fdef.isRepeated()) { + copy.fields.put(fdef, this.getRepeatedField(context, fdef).deepCopy(context)); + } else if (fields.containsKey(fdef)) { + copy.setFieldInternal(context, fdef, fields.get(fdef)); + } else if (builder.hasField(fdef)) { + copy.fields.put(fdef, wrapField(context, fdef, builder.getField(fdef))); + } + } + return copy; + } + + protected IRubyObject clearField(ThreadContext context, FieldDescriptor fieldDescriptor) { + validateMessageType(context, fieldDescriptor, "clear"); + return clearFieldInternal(context, fieldDescriptor); + } + + protected void discardUnknownFields(ThreadContext context) { + discardUnknownFields(context, builder); + } + + protected IRubyObject getField(ThreadContext context, FieldDescriptor fieldDescriptor) { + validateMessageType(context, fieldDescriptor, "get"); + return getFieldInternal(context, fieldDescriptor); + } + + protected IRubyObject hasField(ThreadContext context, FieldDescriptor fieldDescriptor) { + validateMessageType(context, fieldDescriptor, "has?"); + if (!fieldDescriptor.hasPresence()) { + throw context.runtime.newArgumentError("does not track presence"); + } + return fields.containsKey(fieldDescriptor) + ? context.runtime.getTrue() + : context.runtime.getFalse(); + } + + protected IRubyObject setField( + ThreadContext context, FieldDescriptor fieldDescriptor, IRubyObject value) { + validateMessageType(context, fieldDescriptor, "set"); + return setFieldInternal(context, fieldDescriptor, value); + } + + private RubyRepeatedField getRepeatedField( + ThreadContext context, FieldDescriptor fieldDescriptor) { + if (fields.containsKey(fieldDescriptor)) { + return (RubyRepeatedField) fields.get(fieldDescriptor); + } + int count = this.builder.getRepeatedFieldCount(fieldDescriptor); + RubyRepeatedField ret = repeatedFieldForFieldDescriptor(context, fieldDescriptor); + for (int i = 0; i < count; i++) { + ret.push( + context, + new IRubyObject[] { + wrapField(context, fieldDescriptor, this.builder.getRepeatedField(fieldDescriptor, i)) + }); + } + fields.put(fieldDescriptor, ret); + return ret; + } + + private IRubyObject buildFrom(ThreadContext context, DynamicMessage dynamicMessage) { + this.builder.mergeFrom(dynamicMessage); + return this; + } + + private IRubyObject clearFieldInternal(ThreadContext context, FieldDescriptor fieldDescriptor) { + OneofDescriptor ood = fieldDescriptor.getContainingOneof(); + if (ood != null) oneofCases.remove(ood); + fields.remove(fieldDescriptor); + builder.clearField(fieldDescriptor); + return context.nil; + } + + private void discardUnknownFields(ThreadContext context, Message.Builder messageBuilder) { + messageBuilder.setUnknownFields(UnknownFieldSet.getDefaultInstance()); + messageBuilder + .getAllFields() + .forEach( + (fd, value) -> { + if (fd.getType() == FieldDescriptor.Type.MESSAGE) { + if (fd.isRepeated()) { + messageBuilder.clearField(fd); + ((List) value) + .forEach( + (val) -> { + Message.Builder submessageBuilder = ((DynamicMessage) val).toBuilder(); + discardUnknownFields(context, submessageBuilder); + messageBuilder.addRepeatedField(fd, submessageBuilder.build()); + }); + } else { + Message.Builder submessageBuilder = ((DynamicMessage) value).toBuilder(); + discardUnknownFields(context, submessageBuilder); + messageBuilder.setField(fd, submessageBuilder.build()); + } + } + }); + } + + private FieldDescriptor findField(ThreadContext context, IRubyObject fieldName) { + return findField(context, fieldName, false); + } + + private FieldDescriptor findField( + ThreadContext context, IRubyObject fieldName, boolean ignoreUnknownField) { + String nameStr = fieldName.asJavaString(); + FieldDescriptor ret = this.descriptor.findFieldByName(nameStr); + if (ret == null && !ignoreUnknownField) { + throw context.runtime.newArgumentError("field " + fieldName.asJavaString() + " is not found"); + } + return ret; + } + + // convert a ruby object to protobuf type, skip type check since it is checked on the way in + private Object convert( + ThreadContext context, + FieldDescriptor fieldDescriptor, + IRubyObject value, + int depth, + int recursionLimit, + boolean isDefaultStringForBytes) { + Object val = null; + switch (fieldDescriptor.getType()) { + case INT32: + case SFIXED32: + case SINT32: + val = RubyNumeric.num2int(value); + break; + case INT64: + case SFIXED64: + case SINT64: + val = RubyNumeric.num2long(value); + break; + case FIXED32: + case UINT32: + val = Utils.num2uint(value); + break; + case FIXED64: + case UINT64: + val = Utils.num2ulong(context.runtime, value); + break; + case FLOAT: + val = (float) RubyNumeric.num2dbl(value); + break; + case DOUBLE: + val = (double) RubyNumeric.num2dbl(value); + break; + case BOOL: + val = value.isTrue(); + break; + case BYTES: + val = ByteString.copyFrom(((RubyString) value).getBytes()); + break; + case STRING: + if (isDefaultStringForBytes) { + val = ((RubyString) value).getByteList().toString(); + } else { + val = value.asJavaString(); + } + break; + case MESSAGE: + val = ((RubyMessage) value).build(context, depth + 1, recursionLimit); + break; + case ENUM: + EnumDescriptor enumDescriptor = fieldDescriptor.getEnumType(); + if (Utils.isRubyNum(value)) { + val = enumDescriptor.findValueByNumberCreatingIfUnknown(RubyNumeric.num2int(value)); + } else { + val = enumDescriptor.findValueByName(value.asJavaString()); + } + break; + default: + break; + } + + return val; + } + + private static RaiseException createParseError(ThreadContext context, String message) { + if (parseErrorClass == null) { + parseErrorClass = + (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::ParseError"); + } + return RaiseException.from(context.runtime, parseErrorClass, message); + } + + private IRubyObject wrapField( + ThreadContext context, FieldDescriptor fieldDescriptor, Object value) { + return wrapField(context, fieldDescriptor, value, false); + } + + private IRubyObject wrapField( + ThreadContext context, FieldDescriptor fieldDescriptor, Object value, boolean encodeBytes) { + if (value == null) { + return context.runtime.getNil(); + } + Ruby runtime = context.runtime; + + switch (fieldDescriptor.getType()) { + case INT32: + case INT64: + case FIXED32: + case SINT32: + case FIXED64: + case SINT64: + case SFIXED64: + case SFIXED32: + case UINT32: + case UINT64: + case FLOAT: + case DOUBLE: + case BOOL: + case BYTES: + case STRING: + return Utils.wrapPrimaryValue(context, fieldDescriptor.getType(), value, encodeBytes); + case MESSAGE: + RubyClass typeClass = + (RubyClass) + ((RubyDescriptor) getDescriptorForField(context, fieldDescriptor)) + .msgclass(context); + RubyMessage msg = (RubyMessage) typeClass.newInstance(context, Block.NULL_BLOCK); + return msg.buildFrom(context, (DynamicMessage) value); + case ENUM: + EnumValueDescriptor enumValueDescriptor = (EnumValueDescriptor) value; + if (enumValueDescriptor.getIndex() == -1) { // UNKNOWN ENUM VALUE + return runtime.newFixnum(enumValueDescriptor.getNumber()); + } + return runtime.newSymbol(enumValueDescriptor.getName()); + default: + return runtime.newString(value.toString()); + } + } + + private RubyRepeatedField repeatedFieldForFieldDescriptor( + ThreadContext context, FieldDescriptor fieldDescriptor) { + IRubyObject typeClass = context.runtime.getNilClass(); + IRubyObject descriptor = getDescriptorForField(context, fieldDescriptor); + FieldDescriptor.Type type = fieldDescriptor.getType(); + + if (type == FieldDescriptor.Type.MESSAGE) { + typeClass = ((RubyDescriptor) descriptor).msgclass(context); + + } else if (type == FieldDescriptor.Type.ENUM) { + typeClass = ((RubyEnumDescriptor) descriptor).enummodule(context); + } + + RubyRepeatedField field = + new RubyRepeatedField(context.runtime, cRepeatedField, type, typeClass); + field.setName(fieldDescriptor.getName()); + + return field; + } + + private IRubyObject getFieldInternal(ThreadContext context, FieldDescriptor fieldDescriptor) { + return getFieldInternal(context, fieldDescriptor, true); + } + + private IRubyObject getFieldInternal( + ThreadContext context, FieldDescriptor fieldDescriptor, boolean returnDefaults) { + OneofDescriptor oneofDescriptor = fieldDescriptor.getContainingOneof(); + if (oneofDescriptor != null) { + if (oneofCases.get(oneofDescriptor) == fieldDescriptor) { + IRubyObject value = fields.get(fieldDescriptor); + if (value == null) { + FieldDescriptor oneofCase = builder.getOneofFieldDescriptor(oneofDescriptor); + if (oneofCase != null) { + Object builderValue = builder.getField(oneofCase); + if (builderValue != null) { + boolean encodeBytes = + oneofCase.hasDefaultValue() && builderValue.equals(oneofCase.getDefaultValue()); + value = wrapField(context, oneofCase, builderValue, encodeBytes); + } + } + if (value == null) { + return context.nil; + } else { + return value; + } + } else { + return value; + } + } else { + FieldDescriptor oneofCase = builder.getOneofFieldDescriptor(oneofDescriptor); + if (oneofCase != fieldDescriptor) { + if (fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE || !returnDefaults) { + return context.nil; + } else { + return wrapField(context, fieldDescriptor, fieldDescriptor.getDefaultValue(), true); + } + } + if (returnDefaults || builder.hasField(fieldDescriptor)) { + Object rawValue = builder.getField(oneofCase); + boolean encodeBytes = + oneofCase.hasDefaultValue() && rawValue.equals(oneofCase.getDefaultValue()); + IRubyObject value = wrapField(context, oneofCase, rawValue, encodeBytes); + fields.put(fieldDescriptor, value); + return value; + } else { + return context.nil; + } + } + } + + if (fieldDescriptor.isMapField()) { + RubyMap map = (RubyMap) fields.get(fieldDescriptor); + if (map == null) { + map = newMapForField(context, fieldDescriptor); + int mapSize = this.builder.getRepeatedFieldCount(fieldDescriptor); + FieldDescriptor keyField = fieldDescriptor.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = fieldDescriptor.getMessageType().findFieldByNumber(2); + RubyDescriptor kvDescriptor = + (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); + RubyClass kvClass = (RubyClass) kvDescriptor.msgclass(context); + for (int i = 0; i < mapSize; i++) { + RubyMessage kvMessage = (RubyMessage) kvClass.newInstance(context, Block.NULL_BLOCK); + DynamicMessage message = + (DynamicMessage) this.builder.getRepeatedField(fieldDescriptor, i); + kvMessage.buildFrom(context, message); + map.indexSet( + context, + kvMessage.getField(context, keyField), + kvMessage.getField(context, valueField)); + } + fields.put(fieldDescriptor, map); + } + return map; + } + + if (fieldDescriptor.isRepeated()) { + return getRepeatedField(context, fieldDescriptor); + } + + if (fieldDescriptor.getType() != FieldDescriptor.Type.MESSAGE + || builder.hasField(fieldDescriptor) + || fields.containsKey(fieldDescriptor)) { + if (fields.containsKey(fieldDescriptor)) { + return fields.get(fieldDescriptor); + } else if (returnDefaults || builder.hasField(fieldDescriptor)) { + Object rawValue = builder.getField(fieldDescriptor); + boolean encodeBytes = + fieldDescriptor.hasDefaultValue() && rawValue.equals(fieldDescriptor.getDefaultValue()); + IRubyObject value = wrapField(context, fieldDescriptor, rawValue, encodeBytes); + if (builder.hasField(fieldDescriptor)) { + fields.put(fieldDescriptor, value); + } + return value; + } + } + return context.nil; + } + + private IRubyObject setFieldInternal( + ThreadContext context, FieldDescriptor fieldDescriptor, IRubyObject value) { + testFrozen("can't modify frozen " + getMetaClass()); + + if (fieldDescriptor.isMapField()) { + if (!(value instanceof RubyMap)) { + throw Utils.createTypeError(context, "Expected Map instance"); + } + RubyMap thisMap = (RubyMap) getFieldInternal(context, fieldDescriptor); + thisMap.mergeIntoSelf(context, value); + + } else if (fieldDescriptor.isRepeated()) { + if (value instanceof RubyRepeatedField) { + fields.put(fieldDescriptor, value); + } else { + throw Utils.createTypeError(context, "Expected repeated field array"); + } + + } else { + boolean addValue = true; + FieldDescriptor.Type fieldType = fieldDescriptor.getType(); + OneofDescriptor oneofDescriptor = fieldDescriptor.getContainingOneof(); + + // Determine the typeclass, if any + IRubyObject typeClass = context.runtime.getObject(); + if (fieldType == FieldDescriptor.Type.MESSAGE) { + typeClass = + ((RubyDescriptor) getDescriptorForField(context, fieldDescriptor)).msgclass(context); + if (value.isNil()) { + addValue = false; + } + } else if (fieldType == FieldDescriptor.Type.ENUM) { + typeClass = + ((RubyEnumDescriptor) getDescriptorForField(context, fieldDescriptor)) + .enummodule(context); + value = enumToSymbol(context, fieldDescriptor.getEnumType(), value); + } + + if (oneofDescriptor != null) { + FieldDescriptor oneofCase = oneofCases.get(oneofDescriptor); + + // Remove the existing field if we are setting a different field in the Oneof + if (oneofCase != null && oneofCase != fieldDescriptor) { + fields.remove(oneofCase); + } + + // Keep track of what Oneofs are set + if (value.isNil()) { + oneofCases.remove(oneofDescriptor); + if (!oneofDescriptor.isSynthetic()) { + addValue = false; + } + } else { + oneofCases.put(oneofDescriptor, fieldDescriptor); + } + } + + if (addValue) { + value = + Utils.checkType( + context, fieldType, fieldDescriptor.getName(), value, (RubyModule) typeClass); + fields.put(fieldDescriptor, value); + } else { + fields.remove(fieldDescriptor); + } + } + return context.nil; + } + + private IRubyObject getDescriptorForField( + ThreadContext context, FieldDescriptor fieldDescriptor) { + RubyDescriptor thisRbDescriptor = (RubyDescriptor) getDescriptor(context, metaClass); + RubyFieldDescriptor fd = + (RubyFieldDescriptor) + thisRbDescriptor.lookup(context, context.runtime.newString(fieldDescriptor.getName())); + return fd.getSubtype(context); + } + + private IRubyObject enumToSymbol( + ThreadContext context, EnumDescriptor enumDescriptor, IRubyObject value) { + if (value instanceof RubySymbol) { + return (RubySymbol) value; + } else if (Utils.isRubyNum(value)) { + EnumValueDescriptor enumValue = + enumDescriptor.findValueByNumberCreatingIfUnknown(RubyNumeric.num2int(value)); + if (enumValue.getIndex() != -1) { + return context.runtime.newSymbol(enumValue.getName()); + } else { + return value; + } + } else if (value instanceof RubyString) { + return ((RubyString) value).intern(); + } + + return context.runtime.newSymbol("UNKNOWN"); + } + + private RubyRepeatedField rubyToRepeatedField( + ThreadContext context, FieldDescriptor fieldDescriptor, IRubyObject value) { + RubyArray arr = value.convertToArray(); + RubyRepeatedField repeatedField = repeatedFieldForFieldDescriptor(context, fieldDescriptor); + IRubyObject[] values = new IRubyObject[arr.size()]; + FieldDescriptor.Type fieldType = fieldDescriptor.getType(); + + RubyModule typeClass = null; + if (fieldType == FieldDescriptor.Type.MESSAGE) { + RubyDescriptor descriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); + typeClass = (RubyModule) descriptor.msgclass(context); + } else if (fieldType == FieldDescriptor.Type.ENUM) { + RubyEnumDescriptor enumDescriptor = + (RubyEnumDescriptor) getDescriptorForField(context, fieldDescriptor); + typeClass = (RubyModule) enumDescriptor.enummodule(context); + } + + for (int i = 0; i < arr.size(); i++) { + IRubyObject item = arr.eltInternal(i); + if (item.isNil()) { + throw Utils.createTypeError(context, "nil message not allowed here."); + } + if (item instanceof RubyHash && typeClass != null) { + values[i] = ((RubyClass) typeClass).newInstance(context, item, Block.NULL_BLOCK); + } else { + if (fieldType == FieldDescriptor.Type.ENUM) { + item = enumToSymbol(context, fieldDescriptor.getEnumType(), item); + } + + values[i] = item; + } + } + repeatedField.push(context, values); + + return repeatedField; + } + + private RubyMap newMapForField(ThreadContext context, FieldDescriptor fieldDescriptor) { + RubyDescriptor mapDescriptor = (RubyDescriptor) getDescriptorForField(context, fieldDescriptor); + FieldDescriptor keyField = fieldDescriptor.getMessageType().findFieldByNumber(1); + FieldDescriptor valueField = fieldDescriptor.getMessageType().findFieldByNumber(2); + IRubyObject keyType = RubySymbol.newSymbol(context.runtime, keyField.getType().name()); + IRubyObject valueType = RubySymbol.newSymbol(context.runtime, valueField.getType().name()); + + if (valueField.getType() == FieldDescriptor.Type.MESSAGE) { + RubyFieldDescriptor rubyFieldDescriptor = + (RubyFieldDescriptor) mapDescriptor.lookup(context, context.runtime.newString("value")); + RubyDescriptor rubyDescriptor = (RubyDescriptor) rubyFieldDescriptor.getSubtype(context); + return (RubyMap) + cMap.newInstance( + context, keyType, valueType, rubyDescriptor.msgclass(context), Block.NULL_BLOCK); + + } else if (valueField.getType() == FieldDescriptor.Type.ENUM) { + RubyFieldDescriptor rubyFieldDescriptor = + (RubyFieldDescriptor) mapDescriptor.lookup(context, context.runtime.newString("value")); + RubyEnumDescriptor rubyEnumDescriptor = + (RubyEnumDescriptor) rubyFieldDescriptor.getSubtype(context); + return (RubyMap) + cMap.newInstance( + context, + keyType, + valueType, + rubyEnumDescriptor.enummodule(context), + Block.NULL_BLOCK); + + } else { + return (RubyMap) cMap.newInstance(context, keyType, valueType, Block.NULL_BLOCK); + } + } + + private boolean isWrappable(FieldDescriptor fieldDescriptor) { + if (fieldDescriptor.getType() != FieldDescriptor.Type.MESSAGE) return false; + + return isWrapper(fieldDescriptor.getMessageType()); + } + + private static boolean isWrapper(Descriptor messageDescriptor) { + switch (messageDescriptor.getFullName()) { + case "google.protobuf.DoubleValue": + case "google.protobuf.FloatValue": + case "google.protobuf.Int64Value": + case "google.protobuf.UInt64Value": + case "google.protobuf.Int32Value": + case "google.protobuf.UInt32Value": + case "google.protobuf.BoolValue": + case "google.protobuf.StringValue": + case "google.protobuf.BytesValue": + return true; + default: + return false; + } + } + + private void validateMessageType( + ThreadContext context, FieldDescriptor fieldDescriptor, String methodName) { + if (descriptor != fieldDescriptor.getContainingType()) { + throw Utils.createTypeError(context, methodName + " method called on wrong message type"); + } + } + + private static RubyClass parseErrorClass; + + private static final String AS_VALUE_SUFFIX = "_as_value"; + private static final String CLEAR_PREFIX = "clear_"; + private static final String CONST_SUFFIX = "_const"; + private static final String HAS_PREFIX = "has_"; + private static final String QUESTION_MARK = "?"; + private static final int SINK_MAXIMUM_NESTING = 64; + + private Descriptor descriptor; + private DynamicMessage.Builder builder; + private Map<FieldDescriptor, IRubyObject> fields; + private Map<OneofDescriptor, FieldDescriptor> oneofCases; + private RubyClass cRepeatedField; + private RubyClass cMap; + private boolean ignoreUnknownFieldsOnInit = false; + private boolean proto3; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyOneofDescriptor.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyOneofDescriptor.java index 6f2ebdb..5ade98b 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyOneofDescriptor.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyOneofDescriptor.java
@@ -2,6 +2,10 @@ import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.OneofDescriptor; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.RubyModule; @@ -13,74 +17,76 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; - @JRubyClass(name = "OneofDescriptor", include = "Enumerable") public class RubyOneofDescriptor extends RubyObject { - public static void createRubyOneofDescriptor(Ruby runtime) { - RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); - RubyClass cRubyOneofDescriptor = protobuf.defineClassUnder("OneofDescriptor", runtime.getObject(), new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby ruby, RubyClass rubyClass) { + public static void createRubyOneofDescriptor(Ruby runtime) { + RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cRubyOneofDescriptor = + protobuf.defineClassUnder( + "OneofDescriptor", + runtime.getObject(), + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby ruby, RubyClass rubyClass) { return new RubyOneofDescriptor(ruby, rubyClass); - } - }); - cRubyOneofDescriptor.defineAnnotatedMethods(RubyOneofDescriptor.class); - cRubyOneofDescriptor.includeModule(runtime.getEnumerable()); + } + }); + cRubyOneofDescriptor.defineAnnotatedMethods(RubyOneofDescriptor.class); + cRubyOneofDescriptor.includeModule(runtime.getEnumerable()); + } + + public RubyOneofDescriptor(Ruby ruby, RubyClass rubyClass) { + super(ruby, rubyClass); + fields = new ArrayList<RubyFieldDescriptor>(); + } + + /* + * call-seq: + * OneofDescriptor.name => name + * + * Returns the name of this oneof. + */ + @JRubyMethod(name = "name") + public IRubyObject getName(ThreadContext context) { + return name; + } + + /* + * call-seq: + * OneofDescriptor.each(&block) => nil + * + * Iterates through fields in this oneof, yielding to the block on each one. + */ + @JRubyMethod + public IRubyObject each(ThreadContext context, Block block) { + for (RubyFieldDescriptor field : fields) { + block.yieldSpecific(context, field); } + return context.nil; + } - public RubyOneofDescriptor(Ruby ruby, RubyClass rubyClass) { - super(ruby, rubyClass); - fields = new ArrayList<RubyFieldDescriptor>(); + protected Collection<RubyFieldDescriptor> getFields() { + return fields; + } + + protected OneofDescriptor getDescriptor() { + return descriptor; + } + + protected void setDescriptor( + ThreadContext context, + OneofDescriptor descriptor, + Map<FieldDescriptor, RubyFieldDescriptor> fieldCache) { + this.descriptor = descriptor; + this.name = context.runtime.newString(descriptor.getName()); + + for (FieldDescriptor fd : descriptor.getFields()) { + fields.add(fieldCache.get(fd)); } + } - /* - * call-seq: - * OneofDescriptor.name => name - * - * Returns the name of this oneof. - */ - @JRubyMethod(name = "name") - public IRubyObject getName(ThreadContext context) { - return name; - } - - /* - * call-seq: - * OneofDescriptor.each(&block) => nil - * - * Iterates through fields in this oneof, yielding to the block on each one. - */ - @JRubyMethod - public IRubyObject each(ThreadContext context, Block block) { - for (RubyFieldDescriptor field : fields) { - block.yieldSpecific(context, field); - } - return context.nil; - } - - protected Collection<RubyFieldDescriptor> getFields() { - return fields; - } - - protected OneofDescriptor getDescriptor() { - return descriptor; - } - - protected void setDescriptor(ThreadContext context, OneofDescriptor descriptor, Map<FieldDescriptor, RubyFieldDescriptor> fieldCache) { - this.descriptor = descriptor; - this.name = context.runtime.newString(descriptor.getName()); - - for (FieldDescriptor fd : descriptor.getFields()) { - fields.add(fieldCache.get(fd)); - } - } - - private IRubyObject name; - private List<RubyFieldDescriptor> fields; - private OneofDescriptor descriptor; + private IRubyObject name; + private List<RubyFieldDescriptor> fields; + private OneofDescriptor descriptor; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyProtobuf.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyProtobuf.java index 582c675..8d132be 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyProtobuf.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyProtobuf.java
@@ -42,41 +42,42 @@ @JRubyModule(name = "Protobuf") public class RubyProtobuf { - public static void createProtobuf(Ruby runtime) { - RubyModule mGoogle = runtime.getModule("Google"); - RubyModule mProtobuf = mGoogle.defineModuleUnder("Protobuf"); - mProtobuf.defineAnnotatedMethods(RubyProtobuf.class); - RubyModule mInternal = mProtobuf.defineModuleUnder("Internal"); - } + public static void createProtobuf(Ruby runtime) { + RubyModule mGoogle = runtime.getModule("Google"); + RubyModule mProtobuf = mGoogle.defineModuleUnder("Protobuf"); + mProtobuf.defineAnnotatedMethods(RubyProtobuf.class); + RubyModule mInternal = mProtobuf.defineModuleUnder("Internal"); + } - /* - * call-seq: - * Google::Protobuf.deep_copy(obj) => copy_of_obj - * - * Performs a deep copy of either a RepeatedField instance or a message object, - * recursively copying its members. - */ - @JRubyMethod(name = "deep_copy", meta = true) - public static IRubyObject deepCopy(ThreadContext context, IRubyObject self, IRubyObject message) { - if (message instanceof RubyMessage) { - return ((RubyMessage) message).deepCopy(context); - } else if (message instanceof RubyRepeatedField) { - return ((RubyRepeatedField) message).deepCopy(context); - } else { - return ((RubyMap) message).deepCopy(context); - } + /* + * call-seq: + * Google::Protobuf.deep_copy(obj) => copy_of_obj + * + * Performs a deep copy of either a RepeatedField instance or a message object, + * recursively copying its members. + */ + @JRubyMethod(name = "deep_copy", meta = true) + public static IRubyObject deepCopy(ThreadContext context, IRubyObject self, IRubyObject message) { + if (message instanceof RubyMessage) { + return ((RubyMessage) message).deepCopy(context); + } else if (message instanceof RubyRepeatedField) { + return ((RubyRepeatedField) message).deepCopy(context); + } else { + return ((RubyMap) message).deepCopy(context); } + } - /* - * call-seq: - * Google::Protobuf.discard_unknown(msg) - * - * Discard unknown fields in the given message object and recursively discard - * unknown fields in submessages. - */ - @JRubyMethod(name = "discard_unknown", meta = true) - public static IRubyObject discardUnknown(ThreadContext context, IRubyObject self, IRubyObject message) { - ((RubyMessage) message).discardUnknownFields(context); - return context.nil; - } + /* + * call-seq: + * Google::Protobuf.discard_unknown(msg) + * + * Discard unknown fields in the given message object and recursively discard + * unknown fields in submessages. + */ + @JRubyMethod(name = "discard_unknown", meta = true) + public static IRubyObject discardUnknown( + ThreadContext context, IRubyObject self, IRubyObject message) { + ((RubyMessage) message).discardUnknownFields(context); + return context.nil; + } }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/RubyRepeatedField.java b/ruby/src/main/java/com/google/protobuf/jruby/RubyRepeatedField.java index 995171f..77842d1 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/RubyRepeatedField.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/RubyRepeatedField.java
@@ -40,384 +40,393 @@ import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; -import java.util.Arrays; @JRubyClass(name = "RepeatedClass", include = "Enumerable") public class RubyRepeatedField extends RubyObject { - public static void createRubyRepeatedField(Ruby runtime) { - RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); - RubyClass cRepeatedField = mProtobuf.defineClassUnder("RepeatedField", runtime.getObject(), - new ObjectAllocator() { - @Override - public IRubyObject allocate(Ruby runtime, RubyClass klazz) { - return new RubyRepeatedField(runtime, klazz); - } - }); - cRepeatedField.defineAnnotatedMethods(RubyRepeatedField.class); - cRepeatedField.includeModule(runtime.getEnumerable()); + public static void createRubyRepeatedField(Ruby runtime) { + RubyModule mProtobuf = runtime.getClassFromPath("Google::Protobuf"); + RubyClass cRepeatedField = + mProtobuf.defineClassUnder( + "RepeatedField", + runtime.getObject(), + new ObjectAllocator() { + @Override + public IRubyObject allocate(Ruby runtime, RubyClass klazz) { + return new RubyRepeatedField(runtime, klazz); + } + }); + cRepeatedField.defineAnnotatedMethods(RubyRepeatedField.class); + cRepeatedField.includeModule(runtime.getEnumerable()); + } + + public RubyRepeatedField(Ruby runtime, RubyClass klazz) { + super(runtime, klazz); + } + + public RubyRepeatedField( + Ruby runtime, RubyClass klazz, FieldDescriptor.Type fieldType, IRubyObject typeClass) { + this(runtime, klazz); + this.fieldType = fieldType; + this.storage = runtime.newArray(); + this.typeClass = typeClass; + } + + @JRubyMethod(required = 1, optional = 2) + public IRubyObject initialize(ThreadContext context, IRubyObject[] args) { + Ruby runtime = context.runtime; + this.storage = runtime.newArray(); + IRubyObject ary = null; + if (!(args[0] instanceof RubySymbol)) { + throw runtime.newArgumentError("Expected Symbol for type name"); + } + this.fieldType = Utils.rubyToFieldType(args[0]); + if (fieldType == FieldDescriptor.Type.MESSAGE || fieldType == FieldDescriptor.Type.ENUM) { + if (args.length < 2) + throw runtime.newArgumentError("Expected at least 2 arguments for message/enum"); + typeClass = args[1]; + if (args.length > 2) ary = args[2]; + Utils.validateTypeClass(context, fieldType, typeClass); + } else { + if (args.length > 2) throw runtime.newArgumentError("Too many arguments: expected 1 or 2"); + if (args.length > 1) ary = args[1]; + } + if (ary != null) { + RubyArray arr = ary.convertToArray(); + for (int i = 0; i < arr.size(); i++) { + this.storage.add(arr.eltInternal(i)); + } + } + return this; + } + + /* + * call-seq: + * RepeatedField.[]=(index, value) + * + * Sets the element at the given index. On out-of-bounds assignments, extends + * the array and fills the hole (if any) with default values. + */ + @JRubyMethod(name = "[]=") + public IRubyObject indexSet(ThreadContext context, IRubyObject index, IRubyObject value) { + int arrIndex = normalizeArrayIndex(index); + value = Utils.checkType(context, fieldType, name, value, (RubyModule) typeClass); + IRubyObject defaultValue = defaultValue(context); + for (int i = this.storage.size(); i < arrIndex; i++) { + this.storage.set(i, defaultValue); + } + this.storage.set(arrIndex, value); + return context.runtime.getNil(); + } + + /* + * call-seq: + * RepeatedField.[](index) => value + * + * Accesses the element at the given index. Returns nil on out-of-bounds + */ + @JRubyMethod( + required = 1, + optional = 1, + name = {"at", "[]"}) + public IRubyObject index(ThreadContext context, IRubyObject[] args) { + if (args.length == 1) { + IRubyObject arg = args[0]; + if (Utils.isRubyNum(arg)) { + /* standard case */ + int arrIndex = normalizeArrayIndex(arg); + if (arrIndex < 0 || arrIndex >= this.storage.size()) { + return context.runtime.getNil(); + } + return this.storage.eltInternal(arrIndex); + } else if (arg instanceof RubyRange) { + RubyRange range = ((RubyRange) arg); + + int first = normalizeArrayIndex(range.first(context)); + int last = normalizeArrayIndex(range.last(context)); + + if (last - first < 0) { + return context.runtime.newEmptyArray(); + } + + return this.storage.subseq(first, last - first + (range.isExcludeEnd() ? 0 : 1)); + } + } + /* assume 2 arguments */ + int beg = RubyNumeric.num2int(args[0]); + int len = RubyNumeric.num2int(args[1]); + if (beg < 0) { + beg += this.storage.size(); + } + if (beg >= this.storage.size()) { + return context.runtime.getNil(); + } + return this.storage.subseq(beg, len); + } + + /* + * call-seq: + * RepeatedField.push(value) + * + * Adds a new element to the repeated field. + */ + @JRubyMethod( + name = {"push", "<<"}, + required = 1, + rest = true) + public IRubyObject push(ThreadContext context, IRubyObject[] args) { + for (int i = 0; i < args.length; i++) { + IRubyObject val = args[i]; + if (fieldType != FieldDescriptor.Type.MESSAGE || !val.isNil()) { + val = Utils.checkType(context, fieldType, name, val, (RubyModule) typeClass); + } + storage.add(val); } - public RubyRepeatedField(Ruby runtime, RubyClass klazz) { - super(runtime, klazz); - } + return this; + } - public RubyRepeatedField(Ruby runtime, RubyClass klazz, FieldDescriptor.Type fieldType, IRubyObject typeClass) { - this(runtime, klazz); - this.fieldType = fieldType; - this.storage = runtime.newArray(); - this.typeClass = typeClass; - } + /* + * private Ruby method used by RepeatedField.pop + */ + @JRubyMethod(visibility = org.jruby.runtime.Visibility.PRIVATE) + public IRubyObject pop_one(ThreadContext context) { + IRubyObject ret = this.storage.last(); + this.storage.remove(ret); + return ret; + } - @JRubyMethod(required = 1, optional = 2) - public IRubyObject initialize(ThreadContext context, IRubyObject[] args) { - Ruby runtime = context.runtime; - this.storage = runtime.newArray(); - IRubyObject ary = null; - if (!(args[0] instanceof RubySymbol)) { - throw runtime.newArgumentError("Expected Symbol for type name"); - } - this.fieldType = Utils.rubyToFieldType(args[0]); - if (fieldType == FieldDescriptor.Type.MESSAGE - || fieldType == FieldDescriptor.Type.ENUM) { - if (args.length < 2) - throw runtime.newArgumentError("Expected at least 2 arguments for message/enum"); - typeClass = args[1]; - if (args.length > 2) - ary = args[2]; - Utils.validateTypeClass(context, fieldType, typeClass); - } else { - if (args.length > 2) - throw runtime.newArgumentError("Too many arguments: expected 1 or 2"); - if (args.length > 1) - ary = args[1]; - } - if (ary != null) { - RubyArray arr = ary.convertToArray(); - for (int i = 0; i < arr.size(); i++) { - this.storage.add(arr.eltInternal(i)); - } - } - return this; - } + /* + * call-seq: + * RepeatedField.replace(list) + * + * Replaces the contents of the repeated field with the given list of elements. + */ + @JRubyMethod + public IRubyObject replace(ThreadContext context, IRubyObject list) { + RubyArray arr = (RubyArray) list; + checkArrayElementType(context, arr); + this.storage = arr; + return this; + } - /* - * call-seq: - * RepeatedField.[]=(index, value) - * - * Sets the element at the given index. On out-of-bounds assignments, extends - * the array and fills the hole (if any) with default values. - */ - @JRubyMethod(name = "[]=") - public IRubyObject indexSet(ThreadContext context, IRubyObject index, IRubyObject value) { - int arrIndex = normalizeArrayIndex(index); - value = Utils.checkType(context, fieldType, name, value, (RubyModule) typeClass); - IRubyObject defaultValue = defaultValue(context); - for (int i = this.storage.size(); i < arrIndex; i++) { - this.storage.set(i, defaultValue); - } - this.storage.set(arrIndex, value); + /* + * call-seq: + * RepeatedField.clear + * + * Clears (removes all elements from) this repeated field. + */ + @JRubyMethod + public IRubyObject clear(ThreadContext context) { + this.storage.clear(); + return this; + } + + /* + * call-seq: + * RepeatedField.length + * + * Returns the length of this repeated field. + */ + @JRubyMethod(name = {"length", "size"}) + public IRubyObject length(ThreadContext context) { + return context.runtime.newFixnum(this.storage.size()); + } + + /* + * call-seq: + * RepeatedField.+(other) => repeated field + * + * Returns a new repeated field that contains the concatenated list of this + * repeated field's elements and other's elements. The other (second) list may + * be either another repeated field or a Ruby array. + */ + @JRubyMethod(name = {"+"}) + public IRubyObject plus(ThreadContext context, IRubyObject list) { + RubyRepeatedField dup = (RubyRepeatedField) dup(context); + if (list instanceof RubyArray) { + checkArrayElementType(context, (RubyArray) list); + dup.storage.addAll((RubyArray) list); + } else { + RubyRepeatedField repeatedField = (RubyRepeatedField) list; + if (!fieldType.equals(repeatedField.fieldType) + || (typeClass != null && !typeClass.equals(repeatedField.typeClass))) + throw context.runtime.newArgumentError( + "Attempt to append RepeatedField with different element type."); + dup.storage.addAll((RubyArray) repeatedField.toArray(context)); + } + return dup; + } + + /* + * call-seq: + * RepeatedField.concat(other) => self + * + * concats the passed in array to self. Returns a Ruby array. + */ + @JRubyMethod + public IRubyObject concat(ThreadContext context, IRubyObject list) { + if (list instanceof RubyArray) { + checkArrayElementType(context, (RubyArray) list); + this.storage.addAll((RubyArray) list); + } else { + RubyRepeatedField repeatedField = (RubyRepeatedField) list; + if (!fieldType.equals(repeatedField.fieldType) + || (typeClass != null && !typeClass.equals(repeatedField.typeClass))) + throw context.runtime.newArgumentError( + "Attempt to append RepeatedField with different element type."); + this.storage.addAll((RubyArray) repeatedField.toArray(context)); + } + return this; + } + + /* + * call-seq: + * RepeatedField.hash => hash_value + * + * Returns a hash value computed from this repeated field's elements. + */ + @JRubyMethod + public IRubyObject hash(ThreadContext context) { + int hashCode = this.storage.hashCode(); + return context.runtime.newFixnum(hashCode); + } + + /* + * call-seq: + * RepeatedField.==(other) => boolean + * + * Compares this repeated field to another. Repeated fields are equal if their + * element types are equal, their lengths are equal, and each element is equal. + * Elements are compared as per normal Ruby semantics, by calling their :== + * methods (or performing a more efficient comparison for primitive types). + */ + @JRubyMethod(name = "==") + public IRubyObject eq(ThreadContext context, IRubyObject other) { + return this.toArray(context).op_equal(context, other); + } + + /* + * call-seq: + * RepeatedField.each(&block) + * + * Invokes the block once for each element of the repeated field. RepeatedField + * also includes Enumerable; combined with this method, the repeated field thus + * acts like an ordinary Ruby sequence. + */ + @JRubyMethod + public IRubyObject each(ThreadContext context, Block block) { + this.storage.each(context, block); + return this; + } + + @JRubyMethod(name = {"to_ary", "to_a"}) + public IRubyObject toArray(ThreadContext context) { + return this.storage; + } + + /* + * call-seq: + * RepeatedField.dup => repeated_field + * + * Duplicates this repeated field with a shallow copy. References to all + * non-primitive element objects (e.g., submessages) are shared. + */ + @JRubyMethod + public IRubyObject dup(ThreadContext context) { + RubyRepeatedField dup = new RubyRepeatedField(context.runtime, metaClass, fieldType, typeClass); + dup.push(context, storage.toJavaArray()); + return dup; + } + + @JRubyMethod + public IRubyObject inspect() { + return storage.inspect(); + } + + // Java API + protected IRubyObject get(int index) { + return this.storage.eltInternal(index); + } + + protected RubyRepeatedField deepCopy(ThreadContext context) { + RubyRepeatedField copy = + new RubyRepeatedField(context.runtime, metaClass, fieldType, typeClass); + for (int i = 0; i < size(); i++) { + IRubyObject value = storage.eltInternal(i); + if (fieldType == FieldDescriptor.Type.MESSAGE) { + copy.storage.add(((RubyMessage) value).deepCopy(context)); + } else { + copy.storage.add(value); + } + } + return copy; + } + + protected void setName(String name) { + this.name = name; + } + + protected int size() { + return this.storage.size(); + } + + private IRubyObject defaultValue(ThreadContext context) { + SentinelOuterClass.Sentinel sentinel = SentinelOuterClass.Sentinel.getDefaultInstance(); + Object value; + switch (fieldType) { + case INT32: + value = sentinel.getDefaultInt32(); + break; + case INT64: + value = sentinel.getDefaultInt64(); + break; + case UINT32: + value = sentinel.getDefaultUnit32(); + break; + case UINT64: + value = sentinel.getDefaultUint64(); + break; + case FLOAT: + value = sentinel.getDefaultFloat(); + break; + case DOUBLE: + value = sentinel.getDefaultDouble(); + break; + case BOOL: + value = sentinel.getDefaultBool(); + break; + case BYTES: + value = sentinel.getDefaultBytes(); + break; + case STRING: + value = sentinel.getDefaultString(); + break; + case ENUM: + IRubyObject defaultEnumLoc = context.runtime.newFixnum(0); + return RubyEnum.lookup(context, typeClass, defaultEnumLoc); + default: return context.runtime.getNil(); } + return Utils.wrapPrimaryValue(context, fieldType, value); + } - /* - * call-seq: - * RepeatedField.[](index) => value - * - * Accesses the element at the given index. Returns nil on out-of-bounds - */ - @JRubyMethod(required=1, optional=1, name = {"at", "[]"}) - public IRubyObject index(ThreadContext context, IRubyObject[] args) { - if (args.length == 1){ - IRubyObject arg = args[0]; - if (Utils.isRubyNum(arg)) { - /* standard case */ - int arrIndex = normalizeArrayIndex(arg); - if (arrIndex < 0 || arrIndex >= this.storage.size()) { - return context.runtime.getNil(); - } - return this.storage.eltInternal(arrIndex); - } else if (arg instanceof RubyRange) { - RubyRange range = ((RubyRange) arg); - - int beg = RubyNumeric.num2int(range.first(context)); - int len = RubyNumeric.num2int(range.size(context)); - - if (len == 0) return context.runtime.newEmptyArray(); - - return this.storage.subseq(beg, len); - } - } - /* assume 2 arguments */ - int beg = RubyNumeric.num2int(args[0]); - int len = RubyNumeric.num2int(args[1]); - if (beg < 0) { - beg += this.storage.size(); - } - if (beg >= this.storage.size()) { - return context.runtime.getNil(); - } - return this.storage.subseq(beg, len); + private void checkArrayElementType(ThreadContext context, RubyArray arr) { + for (int i = 0; i < arr.getLength(); i++) { + Utils.checkType(context, fieldType, name, arr.eltInternal(i), (RubyModule) typeClass); } + } - /* - * call-seq: - * RepeatedField.push(value) - * - * Adds a new element to the repeated field. - */ - @JRubyMethod(name = {"push", "<<"}, required = 1, rest = true) - public IRubyObject push(ThreadContext context, IRubyObject[] args) { - for (int i = 0; i < args.length; i++) { - IRubyObject val = args[i]; - if (fieldType != FieldDescriptor.Type.MESSAGE || !val.isNil()) { - val = Utils.checkType(context, fieldType, name, val, (RubyModule) typeClass); - } - storage.add(val); - } - - return this; + private int normalizeArrayIndex(IRubyObject index) { + int arrIndex = RubyNumeric.num2int(index); + int arrSize = this.storage.size(); + if (arrIndex < 0 && arrSize > 0) { + arrIndex = arrSize + arrIndex; } + return arrIndex; + } - /* - * private Ruby method used by RepeatedField.pop - */ - @JRubyMethod(visibility = org.jruby.runtime.Visibility.PRIVATE) - public IRubyObject pop_one(ThreadContext context) { - IRubyObject ret = this.storage.last(); - this.storage.remove(ret); - return ret; - } - - /* - * call-seq: - * RepeatedField.replace(list) - * - * Replaces the contents of the repeated field with the given list of elements. - */ - @JRubyMethod - public IRubyObject replace(ThreadContext context, IRubyObject list) { - RubyArray arr = (RubyArray) list; - checkArrayElementType(context, arr); - this.storage = arr; - return this; - } - - /* - * call-seq: - * RepeatedField.clear - * - * Clears (removes all elements from) this repeated field. - */ - @JRubyMethod - public IRubyObject clear(ThreadContext context) { - this.storage.clear(); - return this; - } - - /* - * call-seq: - * RepeatedField.length - * - * Returns the length of this repeated field. - */ - @JRubyMethod(name = {"length", "size"}) - public IRubyObject length(ThreadContext context) { - return context.runtime.newFixnum(this.storage.size()); - } - - /* - * call-seq: - * RepeatedField.+(other) => repeated field - * - * Returns a new repeated field that contains the concatenated list of this - * repeated field's elements and other's elements. The other (second) list may - * be either another repeated field or a Ruby array. - */ - @JRubyMethod(name = {"+"}) - public IRubyObject plus(ThreadContext context, IRubyObject list) { - RubyRepeatedField dup = (RubyRepeatedField) dup(context); - if (list instanceof RubyArray) { - checkArrayElementType(context, (RubyArray) list); - dup.storage.addAll((RubyArray) list); - } else { - RubyRepeatedField repeatedField = (RubyRepeatedField) list; - if (! fieldType.equals(repeatedField.fieldType) || (typeClass != null && ! - typeClass.equals(repeatedField.typeClass))) - throw context.runtime.newArgumentError("Attempt to append RepeatedField with different element type."); - dup.storage.addAll((RubyArray) repeatedField.toArray(context)); - } - return dup; - } - - /* - * call-seq: - * RepeatedField.concat(other) => self - * - * concats the passed in array to self. Returns a Ruby array. - */ - @JRubyMethod - public IRubyObject concat(ThreadContext context, IRubyObject list) { - if (list instanceof RubyArray) { - checkArrayElementType(context, (RubyArray) list); - this.storage.addAll((RubyArray) list); - } else { - RubyRepeatedField repeatedField = (RubyRepeatedField) list; - if (! fieldType.equals(repeatedField.fieldType) || (typeClass != null && ! - typeClass.equals(repeatedField.typeClass))) - throw context.runtime.newArgumentError("Attempt to append RepeatedField with different element type."); - this.storage.addAll((RubyArray) repeatedField.toArray(context)); - } - return this; - } - - /* - * call-seq: - * RepeatedField.hash => hash_value - * - * Returns a hash value computed from this repeated field's elements. - */ - @JRubyMethod - public IRubyObject hash(ThreadContext context) { - int hashCode = this.storage.hashCode(); - return context.runtime.newFixnum(hashCode); - } - - /* - * call-seq: - * RepeatedField.==(other) => boolean - * - * Compares this repeated field to another. Repeated fields are equal if their - * element types are equal, their lengths are equal, and each element is equal. - * Elements are compared as per normal Ruby semantics, by calling their :== - * methods (or performing a more efficient comparison for primitive types). - */ - @JRubyMethod(name = "==") - public IRubyObject eq(ThreadContext context, IRubyObject other) { - return this.toArray(context).op_equal(context, other); - } - - /* - * call-seq: - * RepeatedField.each(&block) - * - * Invokes the block once for each element of the repeated field. RepeatedField - * also includes Enumerable; combined with this method, the repeated field thus - * acts like an ordinary Ruby sequence. - */ - @JRubyMethod - public IRubyObject each(ThreadContext context, Block block) { - this.storage.each(context, block); - return this; - } - - - @JRubyMethod(name = {"to_ary", "to_a"}) - public IRubyObject toArray(ThreadContext context) { - return this.storage; - } - - /* - * call-seq: - * RepeatedField.dup => repeated_field - * - * Duplicates this repeated field with a shallow copy. References to all - * non-primitive element objects (e.g., submessages) are shared. - */ - @JRubyMethod - public IRubyObject dup(ThreadContext context) { - RubyRepeatedField dup = new RubyRepeatedField(context.runtime, metaClass, fieldType, typeClass); - dup.push(context, storage.toJavaArray()); - return dup; - } - - @JRubyMethod - public IRubyObject inspect() { - return storage.inspect(); - } - - // Java API - protected IRubyObject get(int index) { - return this.storage.eltInternal(index); - } - - protected RubyRepeatedField deepCopy(ThreadContext context) { - RubyRepeatedField copy = new RubyRepeatedField(context.runtime, metaClass, fieldType, typeClass); - for (int i = 0; i < size(); i++) { - IRubyObject value = storage.eltInternal(i); - if (fieldType == FieldDescriptor.Type.MESSAGE) { - copy.storage.add(((RubyMessage) value).deepCopy(context)); - } else { - copy.storage.add(value); - } - } - return copy; - } - - protected void setName(String name) { - this.name = name; - } - - protected int size() { - return this.storage.size(); - } - - private IRubyObject defaultValue(ThreadContext context) { - SentinelOuterClass.Sentinel sentinel = SentinelOuterClass.Sentinel.getDefaultInstance(); - Object value; - switch (fieldType) { - case INT32: - value = sentinel.getDefaultInt32(); - break; - case INT64: - value = sentinel.getDefaultInt64(); - break; - case UINT32: - value = sentinel.getDefaultUnit32(); - break; - case UINT64: - value = sentinel.getDefaultUint64(); - break; - case FLOAT: - value = sentinel.getDefaultFloat(); - break; - case DOUBLE: - value = sentinel.getDefaultDouble(); - break; - case BOOL: - value = sentinel.getDefaultBool(); - break; - case BYTES: - value = sentinel.getDefaultBytes(); - break; - case STRING: - value = sentinel.getDefaultString(); - break; - case ENUM: - IRubyObject defaultEnumLoc = context.runtime.newFixnum(0); - return RubyEnum.lookup(context, typeClass, defaultEnumLoc); - default: - return context.runtime.getNil(); - } - return Utils.wrapPrimaryValue(context, fieldType, value); - } - - private void checkArrayElementType(ThreadContext context, RubyArray arr) { - for (int i = 0; i < arr.getLength(); i++) { - Utils.checkType(context, fieldType, name, arr.eltInternal(i), (RubyModule) typeClass); - } - } - - private int normalizeArrayIndex(IRubyObject index) { - int arrIndex = RubyNumeric.num2int(index); - int arrSize = this.storage.size(); - if (arrIndex < 0 && arrSize > 0) { - arrIndex = arrSize + arrIndex; - } - return arrIndex; - } - - private FieldDescriptor.Type fieldType; - private IRubyObject typeClass; - private RubyArray storage; - private String name; + private FieldDescriptor.Type fieldType; + private IRubyObject typeClass; + private RubyArray storage; + private String name; }
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/SentinelOuterClass.java b/ruby/src/main/java/com/google/protobuf/jruby/SentinelOuterClass.java index b3f23c5..3c56cf8 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/SentinelOuterClass.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/SentinelOuterClass.java
@@ -37,74 +37,53 @@ public final class SentinelOuterClass { private SentinelOuterClass() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - } - public interface SentinelOrBuilder extends + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {} + + public interface SentinelOrBuilder + extends // @@protoc_insertion_point(interface_extends:com.google.protobuf.jruby.Sentinel) com.google.protobuf.MessageOrBuilder { - /** - * <code>optional int32 default_int32 = 1;</code> - */ + /** <code>optional int32 default_int32 = 1;</code> */ int getDefaultInt32(); - /** - * <code>optional int64 default_int64 = 2;</code> - */ + /** <code>optional int64 default_int64 = 2;</code> */ long getDefaultInt64(); - /** - * <code>optional uint32 default_unit32 = 3;</code> - */ + /** <code>optional uint32 default_unit32 = 3;</code> */ int getDefaultUnit32(); - /** - * <code>optional uint64 default_uint64 = 4;</code> - */ + /** <code>optional uint64 default_uint64 = 4;</code> */ long getDefaultUint64(); - /** - * <code>optional string default_string = 5;</code> - */ + /** <code>optional string default_string = 5;</code> */ java.lang.String getDefaultString(); - /** - * <code>optional string default_string = 5;</code> - */ - com.google.protobuf.ByteString - getDefaultStringBytes(); + /** <code>optional string default_string = 5;</code> */ + com.google.protobuf.ByteString getDefaultStringBytes(); - /** - * <code>optional bool default_bool = 6;</code> - */ + /** <code>optional bool default_bool = 6;</code> */ boolean getDefaultBool(); - /** - * <code>optional float default_float = 7;</code> - */ + /** <code>optional float default_float = 7;</code> */ float getDefaultFloat(); - /** - * <code>optional double default_double = 8;</code> - */ + /** <code>optional double default_double = 8;</code> */ double getDefaultDouble(); - /** - * <code>optional bytes default_bytes = 9;</code> - */ + /** <code>optional bytes default_bytes = 9;</code> */ com.google.protobuf.ByteString getDefaultBytes(); } - /** - * Protobuf type {@code com.google.protobuf.jruby.Sentinel} - */ - public static final class Sentinel extends - com.google.protobuf.GeneratedMessage implements + /** Protobuf type {@code com.google.protobuf.jruby.Sentinel} */ + public static final class Sentinel extends com.google.protobuf.GeneratedMessage + implements // @@protoc_insertion_point(message_implements:com.google.protobuf.jruby.Sentinel) SentinelOrBuilder { // Use Sentinel.newBuilder() to construct. private Sentinel(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); } + private Sentinel() { defaultInt32_ = 0; defaultInt64_ = 0L; @@ -118,40 +97,42 @@ } @java.lang.Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return com.google.protobuf.jruby.SentinelOuterClass.internal_static_com_google_protobuf_jruby_Sentinel_descriptor; + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.google.protobuf.jruby.SentinelOuterClass + .internal_static_com_google_protobuf_jruby_Sentinel_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return com.google.protobuf.jruby.SentinelOuterClass.internal_static_com_google_protobuf_jruby_Sentinel_fieldAccessorTable + return com.google.protobuf.jruby.SentinelOuterClass + .internal_static_com_google_protobuf_jruby_Sentinel_fieldAccessorTable .ensureFieldAccessorsInitialized( - com.google.protobuf.jruby.SentinelOuterClass.Sentinel.class, com.google.protobuf.jruby.SentinelOuterClass.Sentinel.Builder.class); + com.google.protobuf.jruby.SentinelOuterClass.Sentinel.class, + com.google.protobuf.jruby.SentinelOuterClass.Sentinel.Builder.class); } public static final com.google.protobuf.Parser<Sentinel> PARSER = new com.google.protobuf.AbstractParser<Sentinel>() { - public Sentinel parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - Builder builder = newBuilder(); - try { - builder.mergeFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(builder.buildPartial()); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e.getMessage()).setUnfinishedMessage(builder.buildPartial()); - } - return builder.buildPartial(); - } - }; + public Sentinel parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + Builder builder = newBuilder(); + try { + builder.mergeFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(builder.buildPartial()); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()) + .setUnfinishedMessage(builder.buildPartial()); + } + return builder.buildPartial(); + } + }; @java.lang.Override public com.google.protobuf.Parser<Sentinel> getParserForType() { @@ -160,52 +141,41 @@ public static final int DEFAULT_INT32_FIELD_NUMBER = 1; private int defaultInt32_; - /** - * <code>optional int32 default_int32 = 1;</code> - */ + /** <code>optional int32 default_int32 = 1;</code> */ public int getDefaultInt32() { return defaultInt32_; } public static final int DEFAULT_INT64_FIELD_NUMBER = 2; private long defaultInt64_; - /** - * <code>optional int64 default_int64 = 2;</code> - */ + /** <code>optional int64 default_int64 = 2;</code> */ public long getDefaultInt64() { return defaultInt64_; } public static final int DEFAULT_UNIT32_FIELD_NUMBER = 3; private int defaultUnit32_; - /** - * <code>optional uint32 default_unit32 = 3;</code> - */ + /** <code>optional uint32 default_unit32 = 3;</code> */ public int getDefaultUnit32() { return defaultUnit32_; } public static final int DEFAULT_UINT64_FIELD_NUMBER = 4; private long defaultUint64_; - /** - * <code>optional uint64 default_uint64 = 4;</code> - */ + /** <code>optional uint64 default_uint64 = 4;</code> */ public long getDefaultUint64() { return defaultUint64_; } public static final int DEFAULT_STRING_FIELD_NUMBER = 5; private java.lang.Object defaultString_; - /** - * <code>optional string default_string = 5;</code> - */ + /** <code>optional string default_string = 5;</code> */ public java.lang.String getDefaultString() { java.lang.Object ref = defaultString_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { defaultString_ = s; @@ -213,16 +183,12 @@ return s; } } - /** - * <code>optional string default_string = 5;</code> - */ - public com.google.protobuf.ByteString - getDefaultStringBytes() { + /** <code>optional string default_string = 5;</code> */ + public com.google.protobuf.ByteString getDefaultStringBytes() { java.lang.Object ref = defaultString_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); defaultString_ = b; return b; } else { @@ -232,36 +198,28 @@ public static final int DEFAULT_BOOL_FIELD_NUMBER = 6; private boolean defaultBool_; - /** - * <code>optional bool default_bool = 6;</code> - */ + /** <code>optional bool default_bool = 6;</code> */ public boolean getDefaultBool() { return defaultBool_; } public static final int DEFAULT_FLOAT_FIELD_NUMBER = 7; private float defaultFloat_; - /** - * <code>optional float default_float = 7;</code> - */ + /** <code>optional float default_float = 7;</code> */ public float getDefaultFloat() { return defaultFloat_; } public static final int DEFAULT_DOUBLE_FIELD_NUMBER = 8; private double defaultDouble_; - /** - * <code>optional double default_double = 8;</code> - */ + /** <code>optional double default_double = 8;</code> */ public double getDefaultDouble() { return defaultDouble_; } public static final int DEFAULT_BYTES_FIELD_NUMBER = 9; private com.google.protobuf.ByteString defaultBytes_; - /** - * <code>optional bytes default_bytes = 9;</code> - */ + /** <code>optional bytes default_bytes = 9;</code> */ public com.google.protobuf.ByteString getDefaultBytes() { return defaultBytes_; } @@ -271,47 +229,52 @@ throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } - public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseFrom(java.io.InputStream input) - throws java.io.IOException { + + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseFrom( + java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } - public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { + + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { + com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } + public static com.google.protobuf.jruby.SentinelOuterClass.Sentinel parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) @@ -319,36 +282,45 @@ return PARSER.parseFrom(input, extensionRegistry); } - public static Builder newBuilder() { return new Builder(); } - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder(com.google.protobuf.jruby.SentinelOuterClass.Sentinel prototype) { + public static Builder newBuilder() { + return new Builder(); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder( + com.google.protobuf.jruby.SentinelOuterClass.Sentinel prototype) { return newBuilder().mergeFrom(prototype); } - public Builder toBuilder() { return newBuilder(this); } + + public Builder toBuilder() { + return newBuilder(this); + } @java.lang.Override - protected Builder newBuilderForType( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } - /** - * Protobuf type {@code com.google.protobuf.jruby.Sentinel} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessage.Builder<Builder> implements + /** Protobuf type {@code com.google.protobuf.jruby.Sentinel} */ + public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> + implements // @@protoc_insertion_point(builder_implements:com.google.protobuf.jruby.Sentinel) com.google.protobuf.jruby.SentinelOuterClass.SentinelOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return com.google.protobuf.jruby.SentinelOuterClass.internal_static_com_google_protobuf_jruby_Sentinel_descriptor; + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.google.protobuf.jruby.SentinelOuterClass + .internal_static_com_google_protobuf_jruby_Sentinel_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { - return com.google.protobuf.jruby.SentinelOuterClass.internal_static_com_google_protobuf_jruby_Sentinel_fieldAccessorTable + return com.google.protobuf.jruby.SentinelOuterClass + .internal_static_com_google_protobuf_jruby_Sentinel_fieldAccessorTable .ensureFieldAccessorsInitialized( - com.google.protobuf.jruby.SentinelOuterClass.Sentinel.class, com.google.protobuf.jruby.SentinelOuterClass.Sentinel.Builder.class); + com.google.protobuf.jruby.SentinelOuterClass.Sentinel.class, + com.google.protobuf.jruby.SentinelOuterClass.Sentinel.Builder.class); } // Construct using com.google.protobuf.jruby.SentinelOuterClass.Sentinel.newBuilder() @@ -356,15 +328,15 @@ maybeForceBuilderInitialization(); } - private Builder( - com.google.protobuf.GeneratedMessage.BuilderParent parent) { + private Builder(com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } + private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { - } + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {} } + public Builder clear() { super.clear(); defaultInt32_ = 0; @@ -388,9 +360,9 @@ return this; } - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return com.google.protobuf.jruby.SentinelOuterClass.internal_static_com_google_protobuf_jruby_Sentinel_descriptor; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.google.protobuf.jruby.SentinelOuterClass + .internal_static_com_google_protobuf_jruby_Sentinel_descriptor; } public com.google.protobuf.jruby.SentinelOuterClass.Sentinel getDefaultInstanceForType() { @@ -406,7 +378,8 @@ } public com.google.protobuf.jruby.SentinelOuterClass.Sentinel buildPartial() { - com.google.protobuf.jruby.SentinelOuterClass.Sentinel result = new com.google.protobuf.jruby.SentinelOuterClass.Sentinel(this); + com.google.protobuf.jruby.SentinelOuterClass.Sentinel result = + new com.google.protobuf.jruby.SentinelOuterClass.Sentinel(this); result.defaultInt32_ = defaultInt32_; result.defaultInt64_ = defaultInt64_; result.defaultUnit32_ = defaultUnit32_; @@ -420,26 +393,19 @@ return result; } - - private int defaultInt32_ ; - /** - * <code>optional int32 default_int32 = 1;</code> - */ + private int defaultInt32_; + /** <code>optional int32 default_int32 = 1;</code> */ public int getDefaultInt32() { return defaultInt32_; } - /** - * <code>optional int32 default_int32 = 1;</code> - */ + /** <code>optional int32 default_int32 = 1;</code> */ public Builder setDefaultInt32(int value) { defaultInt32_ = value; onChanged(); return this; } - /** - * <code>optional int32 default_int32 = 1;</code> - */ + /** <code>optional int32 default_int32 = 1;</code> */ public Builder clearDefaultInt32() { defaultInt32_ = 0; @@ -447,25 +413,19 @@ return this; } - private long defaultInt64_ ; - /** - * <code>optional int64 default_int64 = 2;</code> - */ + private long defaultInt64_; + /** <code>optional int64 default_int64 = 2;</code> */ public long getDefaultInt64() { return defaultInt64_; } - /** - * <code>optional int64 default_int64 = 2;</code> - */ + /** <code>optional int64 default_int64 = 2;</code> */ public Builder setDefaultInt64(long value) { defaultInt64_ = value; onChanged(); return this; } - /** - * <code>optional int64 default_int64 = 2;</code> - */ + /** <code>optional int64 default_int64 = 2;</code> */ public Builder clearDefaultInt64() { defaultInt64_ = 0L; @@ -473,25 +433,19 @@ return this; } - private int defaultUnit32_ ; - /** - * <code>optional uint32 default_unit32 = 3;</code> - */ + private int defaultUnit32_; + /** <code>optional uint32 default_unit32 = 3;</code> */ public int getDefaultUnit32() { return defaultUnit32_; } - /** - * <code>optional uint32 default_unit32 = 3;</code> - */ + /** <code>optional uint32 default_unit32 = 3;</code> */ public Builder setDefaultUnit32(int value) { defaultUnit32_ = value; onChanged(); return this; } - /** - * <code>optional uint32 default_unit32 = 3;</code> - */ + /** <code>optional uint32 default_unit32 = 3;</code> */ public Builder clearDefaultUnit32() { defaultUnit32_ = 0; @@ -499,25 +453,19 @@ return this; } - private long defaultUint64_ ; - /** - * <code>optional uint64 default_uint64 = 4;</code> - */ + private long defaultUint64_; + /** <code>optional uint64 default_uint64 = 4;</code> */ public long getDefaultUint64() { return defaultUint64_; } - /** - * <code>optional uint64 default_uint64 = 4;</code> - */ + /** <code>optional uint64 default_uint64 = 4;</code> */ public Builder setDefaultUint64(long value) { defaultUint64_ = value; onChanged(); return this; } - /** - * <code>optional uint64 default_uint64 = 4;</code> - */ + /** <code>optional uint64 default_uint64 = 4;</code> */ public Builder clearDefaultUint64() { defaultUint64_ = 0L; @@ -526,14 +474,11 @@ } private java.lang.Object defaultString_ = ""; - /** - * <code>optional string default_string = 5;</code> - */ + /** <code>optional string default_string = 5;</code> */ public java.lang.String getDefaultString() { java.lang.Object ref = defaultString_; if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { defaultString_ = s; @@ -543,77 +488,59 @@ return (java.lang.String) ref; } } - /** - * <code>optional string default_string = 5;</code> - */ - public com.google.protobuf.ByteString - getDefaultStringBytes() { + /** <code>optional string default_string = 5;</code> */ + public com.google.protobuf.ByteString getDefaultStringBytes() { java.lang.Object ref = defaultString_; if (ref instanceof String) { com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (java.lang.String) ref); + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); defaultString_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } - /** - * <code>optional string default_string = 5;</code> - */ - public Builder setDefaultString( - java.lang.String value) { + /** <code>optional string default_string = 5;</code> */ + public Builder setDefaultString(java.lang.String value) { if (value == null) { - throw new NullPointerException(); - } + throw new NullPointerException(); + } defaultString_ = value; onChanged(); return this; } - /** - * <code>optional string default_string = 5;</code> - */ + /** <code>optional string default_string = 5;</code> */ public Builder clearDefaultString() { defaultString_ = getDefaultInstance().getDefaultString(); onChanged(); return this; } - /** - * <code>optional string default_string = 5;</code> - */ - public Builder setDefaultStringBytes( - com.google.protobuf.ByteString value) { + /** <code>optional string default_string = 5;</code> */ + public Builder setDefaultStringBytes(com.google.protobuf.ByteString value) { if (value == null) { - throw new NullPointerException(); - } + throw new NullPointerException(); + } defaultString_ = value; onChanged(); return this; } - private boolean defaultBool_ ; - /** - * <code>optional bool default_bool = 6;</code> - */ + private boolean defaultBool_; + /** <code>optional bool default_bool = 6;</code> */ public boolean getDefaultBool() { return defaultBool_; } - /** - * <code>optional bool default_bool = 6;</code> - */ + /** <code>optional bool default_bool = 6;</code> */ public Builder setDefaultBool(boolean value) { defaultBool_ = value; onChanged(); return this; } - /** - * <code>optional bool default_bool = 6;</code> - */ + /** <code>optional bool default_bool = 6;</code> */ public Builder clearDefaultBool() { defaultBool_ = false; @@ -621,25 +548,19 @@ return this; } - private float defaultFloat_ ; - /** - * <code>optional float default_float = 7;</code> - */ + private float defaultFloat_; + /** <code>optional float default_float = 7;</code> */ public float getDefaultFloat() { return defaultFloat_; } - /** - * <code>optional float default_float = 7;</code> - */ + /** <code>optional float default_float = 7;</code> */ public Builder setDefaultFloat(float value) { defaultFloat_ = value; onChanged(); return this; } - /** - * <code>optional float default_float = 7;</code> - */ + /** <code>optional float default_float = 7;</code> */ public Builder clearDefaultFloat() { defaultFloat_ = 0F; @@ -647,25 +568,19 @@ return this; } - private double defaultDouble_ ; - /** - * <code>optional double default_double = 8;</code> - */ + private double defaultDouble_; + /** <code>optional double default_double = 8;</code> */ public double getDefaultDouble() { return defaultDouble_; } - /** - * <code>optional double default_double = 8;</code> - */ + /** <code>optional double default_double = 8;</code> */ public Builder setDefaultDouble(double value) { defaultDouble_ = value; onChanged(); return this; } - /** - * <code>optional double default_double = 8;</code> - */ + /** <code>optional double default_double = 8;</code> */ public Builder clearDefaultDouble() { defaultDouble_ = 0D; @@ -674,33 +589,28 @@ } private com.google.protobuf.ByteString defaultBytes_ = com.google.protobuf.ByteString.EMPTY; - /** - * <code>optional bytes default_bytes = 9;</code> - */ + /** <code>optional bytes default_bytes = 9;</code> */ public com.google.protobuf.ByteString getDefaultBytes() { return defaultBytes_; } - /** - * <code>optional bytes default_bytes = 9;</code> - */ + /** <code>optional bytes default_bytes = 9;</code> */ public Builder setDefaultBytes(com.google.protobuf.ByteString value) { if (value == null) { - throw new NullPointerException(); - } + throw new NullPointerException(); + } defaultBytes_ = value; onChanged(); return this; } - /** - * <code>optional bytes default_bytes = 9;</code> - */ + /** <code>optional bytes default_bytes = 9;</code> */ public Builder clearDefaultBytes() { defaultBytes_ = getDefaultInstance().getDefaultBytes(); onChanged(); return this; } + public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return this; @@ -711,12 +621,13 @@ return this; } - // @@protoc_insertion_point(builder_scope:com.google.protobuf.jruby.Sentinel) } // @@protoc_insertion_point(class_scope:com.google.protobuf.jruby.Sentinel) - private static final com.google.protobuf.jruby.SentinelOuterClass.Sentinel defaultInstance;static { + private static final com.google.protobuf.jruby.SentinelOuterClass.Sentinel defaultInstance; + + static { defaultInstance = new com.google.protobuf.jruby.SentinelOuterClass.Sentinel(); } @@ -727,49 +638,55 @@ public com.google.protobuf.jruby.SentinelOuterClass.Sentinel getDefaultInstanceForType() { return defaultInstance; } - } private static final com.google.protobuf.Descriptors.Descriptor - internal_static_com_google_protobuf_jruby_Sentinel_descriptor; - private static - com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_com_google_protobuf_jruby_Sentinel_descriptor; + private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_com_google_protobuf_jruby_Sentinel_fieldAccessorTable; - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; + static { java.lang.String[] descriptorData = { - "\n\016sentinel.proto\022\031com.google.protobuf.jr" + - "uby\"\334\001\n\010Sentinel\022\025\n\rdefault_int32\030\001 \001(\005\022" + - "\025\n\rdefault_int64\030\002 \001(\003\022\026\n\016default_unit32" + - "\030\003 \001(\r\022\026\n\016default_uint64\030\004 \001(\004\022\026\n\016defaul" + - "t_string\030\005 \001(\t\022\024\n\014default_bool\030\006 \001(\010\022\025\n\r" + - "default_float\030\007 \001(\002\022\026\n\016default_double\030\010 " + - "\001(\001\022\025\n\rdefault_bytes\030\t \001(\014B\002H\002b\006proto3" + "\n\016sentinel.proto\022\031com.google.protobuf.jr" + + "uby\"\334\001\n\010Sentinel\022\025\n\rdefault_int32\030\001 \001(\005\022" + + "\025\n\rdefault_int64\030\002 \001(\003\022\026\n\016default_unit32" + + "\030\003 \001(\r\022\026\n\016default_uint64\030\004 \001(\004\022\026\n\016defaul" + + "t_string\030\005 \001(\t\022\024\n\014default_bool\030\006 \001(\010\022\025\n\r" + + "default_float\030\007 \001(\002\022\026\n\016default_double\030\010 " + + "\001(\001\022\025\n\rdefault_bytes\030\t \001(\014B\002H\002b\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = - new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }, assigner); + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); internal_static_com_google_protobuf_jruby_Sentinel_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_com_google_protobuf_jruby_Sentinel_fieldAccessorTable = new - com.google.protobuf.GeneratedMessage.FieldAccessorTable( - internal_static_com_google_protobuf_jruby_Sentinel_descriptor, - new java.lang.String[] { "DefaultInt32", "DefaultInt64", "DefaultUnit32", "DefaultUint64", "DefaultString", "DefaultBool", "DefaultFloat", "DefaultDouble", "DefaultBytes", }); + getDescriptor().getMessageTypes().get(0); + internal_static_com_google_protobuf_jruby_Sentinel_fieldAccessorTable = + new com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_com_google_protobuf_jruby_Sentinel_descriptor, + new java.lang.String[] { + "DefaultInt32", + "DefaultInt64", + "DefaultUnit32", + "DefaultUint64", + "DefaultString", + "DefaultBool", + "DefaultFloat", + "DefaultDouble", + "DefaultBytes", + }); } // @@protoc_insertion_point(outer_class_scope)
diff --git a/ruby/src/main/java/com/google/protobuf/jruby/Utils.java b/ruby/src/main/java/com/google/protobuf/jruby/Utils.java index cd27589..65de683 100644 --- a/ruby/src/main/java/com/google/protobuf/jruby/Utils.java +++ b/ruby/src/main/java/com/google/protobuf/jruby/Utils.java
@@ -35,6 +35,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; import com.google.protobuf.Descriptors.FieldDescriptor; +import java.math.BigInteger; import org.jcodings.specific.ASCIIEncoding; import org.jruby.*; import org.jruby.exceptions.RaiseException; @@ -44,302 +45,363 @@ import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; -import java.math.BigInteger; - public class Utils { - public static FieldDescriptor.Type rubyToFieldType(IRubyObject typeClass) { - return FieldDescriptor.Type.valueOf(typeClass.asJavaString().toUpperCase()); - } + public static FieldDescriptor.Type rubyToFieldType(IRubyObject typeClass) { + return FieldDescriptor.Type.valueOf(typeClass.asJavaString().toUpperCase()); + } - public static IRubyObject fieldTypeToRuby(ThreadContext context, FieldDescriptor.Type type) { - return fieldTypeToRuby(context, type.name()); - } + public static IRubyObject fieldTypeToRuby(ThreadContext context, FieldDescriptor.Type type) { + return fieldTypeToRuby(context, type.name()); + } - public static IRubyObject fieldTypeToRuby(ThreadContext context, FieldDescriptorProto.Type type) { - return fieldTypeToRuby(context, type.name()); - } + public static IRubyObject fieldTypeToRuby(ThreadContext context, FieldDescriptorProto.Type type) { + return fieldTypeToRuby(context, type.name()); + } - private static IRubyObject fieldTypeToRuby(ThreadContext context, String typeName) { + private static IRubyObject fieldTypeToRuby(ThreadContext context, String typeName) { - return context.runtime.newSymbol(typeName.replace("TYPE_", "").toLowerCase()); - } + return context.runtime.newSymbol(typeName.replace("TYPE_", "").toLowerCase()); + } - public static IRubyObject checkType(ThreadContext context, FieldDescriptor.Type fieldType, - String fieldName, IRubyObject value, RubyModule typeClass) { - Ruby runtime = context.runtime; + public static IRubyObject checkType( + ThreadContext context, + FieldDescriptor.Type fieldType, + String fieldName, + IRubyObject value, + RubyModule typeClass) { + Ruby runtime = context.runtime; - switch(fieldType) { - case SFIXED32: - case SFIXED64: - case FIXED64: - case SINT64: - case SINT32: - case FIXED32: - case INT32: - case INT64: - case UINT32: - case UINT64: - if (!isRubyNum(value)) - throw createExpectedTypeError(context, "number", "integral", fieldName, value); + switch (fieldType) { + case SFIXED32: + case SFIXED64: + case FIXED64: + case SINT64: + case SINT32: + case FIXED32: + case INT32: + case INT64: + case UINT32: + case UINT64: + if (!isRubyNum(value)) + throw createExpectedTypeError(context, "number", "integral", fieldName, value); - if (value instanceof RubyFloat) { - double doubleVal = RubyNumeric.num2dbl(value); - if (Math.floor(doubleVal) != doubleVal) { - throw runtime.newRangeError("Non-integral floating point value assigned to integer field '" + fieldName + "' (given " + value.getMetaClass() + ")."); - } - } - if (fieldType == FieldDescriptor.Type.UINT32 || fieldType == FieldDescriptor.Type.UINT64 || - fieldType == FieldDescriptor.Type.FIXED32 || fieldType == FieldDescriptor.Type.FIXED64) { - if (((RubyNumeric) value).isNegative()) { - throw runtime.newRangeError("Assigning negative value to unsigned integer field '" + fieldName + "' (given " + value.getMetaClass() + ")."); - } - } - - switch(fieldType) { - case INT32: - RubyNumeric.num2int(value); - break; - case UINT32: - case FIXED32: - num2uint(value); - break; - case UINT64: - case FIXED64: - num2ulong(context.runtime, value); - break; - default: - RubyNumeric.num2long(value); - break; - } - break; - case FLOAT: - if (!isRubyNum(value)) - throw createExpectedTypeError(context, "number", "float", fieldName, value); - break; - case DOUBLE: - if (!isRubyNum(value)) - throw createExpectedTypeError(context, "number", "double", fieldName, value); - break; - case BOOL: - if (!(value instanceof RubyBoolean)) - throw createInvalidTypeError(context, "boolean", fieldName, value); - break; - case BYTES: - value = validateAndEncodeString(context, "bytes", fieldName, value, "Encoding::ASCII_8BIT"); - break; - case STRING: - value = validateAndEncodeString(context, "string", fieldName, symToString(value), "Encoding::UTF_8"); - break; - case MESSAGE: - if (value.getMetaClass() != typeClass) { - // See if we can convert the value before flagging it as invalid - String className = typeClass.getName(); - - if (className.equals("Google::Protobuf::Timestamp") && value instanceof RubyTime) { - RubyTime rt = (RubyTime) value; - RubyHash timestampArgs = - Helpers.constructHash(runtime, - runtime.newString("nanos"), rt.nsec(), false, - runtime.newString("seconds"), rt.to_i(), false); - return ((RubyClass) typeClass).newInstance(context, timestampArgs, Block.NULL_BLOCK); - - } else if (className.equals("Google::Protobuf::Duration") && value instanceof RubyNumeric) { - IRubyObject seconds; - if (value instanceof RubyFloat) { - seconds = ((RubyFloat) value).truncate(context); - } else if (value instanceof RubyRational) { - seconds = ((RubyRational) value).to_i(context); - } else if (value instanceof RubyBigDecimal) { - seconds = ((RubyBigDecimal) value).to_int(context); - } else { - seconds = ((RubyInteger) value).to_i(); - } - - IRubyObject nanos = ((RubyNumeric) value).remainder(context, RubyFixnum.one(runtime)); - if (nanos instanceof RubyFloat) { - nanos = ((RubyFloat) nanos).op_mul(context, 1000000000); - } else if (nanos instanceof RubyRational) { - nanos = ((RubyRational) nanos).op_mul(context, runtime.newFixnum(1000000000)); - } else if (nanos instanceof RubyBigDecimal) { - nanos = ((RubyBigDecimal) nanos).op_mul(context, runtime.newFixnum(1000000000)); - } else { - nanos = ((RubyInteger) nanos).op_mul(context, 1000000000); - } - - RubyHash durationArgs = - Helpers.constructHash(runtime, - runtime.newString("nanos"), ((RubyNumeric) nanos).round(context), false, - runtime.newString("seconds"), seconds, false); - return ((RubyClass) typeClass).newInstance(context, durationArgs, Block.NULL_BLOCK); - } - - // Not able to convert so flag as invalid - throw createTypeError(context, "Invalid type " + value.getMetaClass() + " to assign to submessage field '" + fieldName + "'."); - } - - break; - case ENUM: - boolean isValid = ((RubyEnumDescriptor) typeClass.getInstanceVariable(DESCRIPTOR_INSTANCE_VAR)).isValidValue(context, value); - if (!isValid) { - throw runtime.newRangeError("Unknown symbol value for enum field '" + fieldName + "'."); - } - break; - default: - break; - } - return value; - } - - public static IRubyObject wrapPrimaryValue(ThreadContext context, FieldDescriptor.Type fieldType, Object value) { - return wrapPrimaryValue(context, fieldType, value, false); - } - - public static IRubyObject wrapPrimaryValue(ThreadContext context, FieldDescriptor.Type fieldType, Object value, boolean encodeBytes) { - Ruby runtime = context.runtime; - switch (fieldType) { - case INT32: - case SFIXED32: - case SINT32: - return runtime.newFixnum((Integer) value); - case SFIXED64: - case SINT64: - case INT64: - return runtime.newFixnum((Long) value); - case FIXED32: - case UINT32: - return runtime.newFixnum(((Integer) value) & (-1l >>> 32)); - case FIXED64: - case UINT64: - long ret = (Long) value; - return ret >= 0 ? runtime.newFixnum(ret) : - RubyBignum.newBignum(runtime, UINT64_COMPLEMENTARY.add(new BigInteger(ret + ""))); - case FLOAT: - return runtime.newFloat((Float) value); - case DOUBLE: - return runtime.newFloat((Double) value); - case BOOL: - return (Boolean) value ? runtime.getTrue() : runtime.getFalse(); - case BYTES: { - IRubyObject wrapped = encodeBytes ? - RubyString.newString(runtime, ((ByteString) value).toStringUtf8(), ASCIIEncoding.INSTANCE) : - RubyString.newString(runtime, ((ByteString) value).toByteArray()); - wrapped.setFrozen(true); - return wrapped; - } - case STRING: { - IRubyObject wrapped = runtime.newString(value.toString()); - wrapped.setFrozen(true); - return wrapped; - } - default: - return runtime.getNil(); - } - } - - public static int num2uint(IRubyObject value) { - long longVal = RubyNumeric.num2long(value); - if (longVal > UINT_MAX) - throw value.getRuntime().newRangeError("Integer " + longVal + " too big to convert to 'unsigned int'"); - long num = longVal; - if (num > Integer.MAX_VALUE || num < Integer.MIN_VALUE) - // encode to UINT32 - num = (-longVal ^ (-1l >>> 32) ) + 1; - RubyNumeric.checkInt(value, num); - return (int) num; - } - - public static long num2ulong(Ruby runtime, IRubyObject value) { if (value instanceof RubyFloat) { - RubyBignum bignum = RubyBignum.newBignum(runtime, ((RubyFloat) value).getDoubleValue()); - return RubyBignum.big2ulong(bignum); - } else if (value instanceof RubyBignum) { - return RubyBignum.big2ulong((RubyBignum) value); - } else { - return RubyNumeric.num2long(value); + double doubleVal = RubyNumeric.num2dbl(value); + if (Math.floor(doubleVal) != doubleVal) { + throw runtime.newRangeError( + "Non-integral floating point value assigned to integer field '" + + fieldName + + "' (given " + + value.getMetaClass() + + ")."); + } } - } - - /* - * Helper to make it easier to support symbols being passed instead of strings - */ - public static IRubyObject symToString(IRubyObject sym) { - if (sym instanceof RubySymbol) { - return ((RubySymbol) sym).id2name(); + if (fieldType == FieldDescriptor.Type.UINT32 + || fieldType == FieldDescriptor.Type.UINT64 + || fieldType == FieldDescriptor.Type.FIXED32 + || fieldType == FieldDescriptor.Type.FIXED64) { + if (((RubyNumeric) value).isNegative()) { + throw runtime.newRangeError( + "Assigning negative value to unsigned integer field '" + + fieldName + + "' (given " + + value.getMetaClass() + + ")."); + } } - return sym; - } - public static void checkNameAvailability(ThreadContext context, String name) { - if (context.runtime.getObject().getConstantAt(name) != null) - throw context.runtime.newNameError(name + " is already defined", name); - } - - public static boolean isMapEntry(FieldDescriptor fieldDescriptor) { - return fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE && - fieldDescriptor.isRepeated() && - fieldDescriptor.getMessageType().getOptions().getMapEntry(); - } - - public static RaiseException createTypeError(ThreadContext context, String message) { - if (cTypeError == null) { - cTypeError = (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::TypeError"); + switch (fieldType) { + case INT32: + RubyNumeric.num2int(value); + break; + case UINT32: + case FIXED32: + num2uint(value); + break; + case UINT64: + case FIXED64: + num2ulong(context.runtime, value); + break; + default: + RubyNumeric.num2long(value); + break; } - return RaiseException.from(context.runtime, cTypeError, message); - } + break; + case FLOAT: + if (!isRubyNum(value)) + throw createExpectedTypeError(context, "number", "float", fieldName, value); + break; + case DOUBLE: + if (!isRubyNum(value)) + throw createExpectedTypeError(context, "number", "double", fieldName, value); + break; + case BOOL: + if (!(value instanceof RubyBoolean)) + throw createInvalidTypeError(context, "boolean", fieldName, value); + break; + case BYTES: + value = validateAndEncodeString(context, "bytes", fieldName, value, "Encoding::ASCII_8BIT"); + break; + case STRING: + value = + validateAndEncodeString( + context, "string", fieldName, symToString(value), "Encoding::UTF_8"); + break; + case MESSAGE: + if (value.getMetaClass() != typeClass) { + // See if we can convert the value before flagging it as invalid + String className = typeClass.getName(); - public static RaiseException createExpectedTypeError(ThreadContext context, String type, String fieldType, String fieldName, IRubyObject value) { - return createTypeError(context, String.format(EXPECTED_TYPE_ERROR_FORMAT, type, fieldType, fieldName, value.getMetaClass())); - } + if (className.equals("Google::Protobuf::Timestamp") && value instanceof RubyTime) { + RubyTime rt = (RubyTime) value; + RubyHash timestampArgs = + Helpers.constructHash( + runtime, + runtime.newString("nanos"), + rt.nsec(), + false, + runtime.newString("seconds"), + rt.to_i(), + false); + return ((RubyClass) typeClass).newInstance(context, timestampArgs, Block.NULL_BLOCK); - public static RaiseException createInvalidTypeError(ThreadContext context, String fieldType, String fieldName, IRubyObject value) { - return createTypeError(context, String.format(INVALID_TYPE_ERROR_FORMAT, fieldType, fieldName, value.getMetaClass())); - } - - protected static boolean isRubyNum(Object value) { - return value instanceof RubyFixnum || value instanceof RubyFloat || value instanceof RubyBignum; - } - - protected static void validateTypeClass(ThreadContext context, FieldDescriptor.Type type, IRubyObject value) { - Ruby runtime = context.runtime; - if (!(value instanceof RubyModule)) { - throw runtime.newArgumentError("TypeClass has incorrect type"); - } - RubyModule klass = (RubyModule) value; - IRubyObject descriptor = klass.getInstanceVariable(DESCRIPTOR_INSTANCE_VAR); - if (descriptor.isNil()) { - throw runtime.newArgumentError("Type class has no descriptor. Please pass a " + - "class or enum as returned by the DescriptorPool."); - } - if (type == FieldDescriptor.Type.MESSAGE) { - if (! (descriptor instanceof RubyDescriptor)) { - throw runtime.newArgumentError("Descriptor has an incorrect type"); + } else if (className.equals("Google::Protobuf::Duration") + && value instanceof RubyNumeric) { + IRubyObject seconds; + if (value instanceof RubyFloat) { + seconds = ((RubyFloat) value).truncate(context); + } else if (value instanceof RubyRational) { + seconds = ((RubyRational) value).to_i(context); + } else if (value instanceof RubyBigDecimal) { + seconds = ((RubyBigDecimal) value).to_int(context); + } else { + seconds = ((RubyInteger) value).to_i(); } - } else if (type == FieldDescriptor.Type.ENUM) { - if (! (descriptor instanceof RubyEnumDescriptor)) { - throw runtime.newArgumentError("Descriptor has an incorrect type"); + + IRubyObject nanos = ((RubyNumeric) value).remainder(context, RubyFixnum.one(runtime)); + if (nanos instanceof RubyFloat) { + nanos = ((RubyFloat) nanos).op_mul(context, 1000000000); + } else if (nanos instanceof RubyRational) { + nanos = ((RubyRational) nanos).op_mul(context, runtime.newFixnum(1000000000)); + } else if (nanos instanceof RubyBigDecimal) { + nanos = ((RubyBigDecimal) nanos).op_mul(context, runtime.newFixnum(1000000000)); + } else { + nanos = ((RubyInteger) nanos).op_mul(context, 1000000000); } + + RubyHash durationArgs = + Helpers.constructHash( + runtime, + runtime.newString("nanos"), + ((RubyNumeric) nanos).round(context), + false, + runtime.newString("seconds"), + seconds, + false); + return ((RubyClass) typeClass).newInstance(context, durationArgs, Block.NULL_BLOCK); + } + + // Not able to convert so flag as invalid + throw createTypeError( + context, + "Invalid type " + + value.getMetaClass() + + " to assign to submessage field '" + + fieldName + + "'."); } + + break; + case ENUM: + boolean isValid = + ((RubyEnumDescriptor) typeClass.getInstanceVariable(DESCRIPTOR_INSTANCE_VAR)) + .isValidValue(context, value); + if (!isValid) { + throw runtime.newRangeError("Unknown symbol value for enum field '" + fieldName + "'."); + } + break; + default: + break; } + return value; + } - private static IRubyObject validateAndEncodeString(ThreadContext context, String fieldType, String fieldName, IRubyObject value, String encoding) { - if (!(value instanceof RubyString)) - throw createInvalidTypeError(context, fieldType, fieldName, value); + public static IRubyObject wrapPrimaryValue( + ThreadContext context, FieldDescriptor.Type fieldType, Object value) { + return wrapPrimaryValue(context, fieldType, value, false); + } - value = ((RubyString) value).encode(context, context.runtime.evalScriptlet(encoding)); - value.setFrozen(true); - return value; + public static IRubyObject wrapPrimaryValue( + ThreadContext context, FieldDescriptor.Type fieldType, Object value, boolean encodeBytes) { + Ruby runtime = context.runtime; + switch (fieldType) { + case INT32: + case SFIXED32: + case SINT32: + return runtime.newFixnum((Integer) value); + case SFIXED64: + case SINT64: + case INT64: + return runtime.newFixnum((Long) value); + case FIXED32: + case UINT32: + return runtime.newFixnum(((Integer) value) & (-1l >>> 32)); + case FIXED64: + case UINT64: + long ret = (Long) value; + return ret >= 0 + ? runtime.newFixnum(ret) + : RubyBignum.newBignum(runtime, UINT64_COMPLEMENTARY.add(new BigInteger(ret + ""))); + case FLOAT: + return runtime.newFloat((Float) value); + case DOUBLE: + return runtime.newFloat((Double) value); + case BOOL: + return (Boolean) value ? runtime.getTrue() : runtime.getFalse(); + case BYTES: + { + IRubyObject wrapped = + encodeBytes + ? RubyString.newString( + runtime, ((ByteString) value).toStringUtf8(), ASCIIEncoding.INSTANCE) + : RubyString.newString(runtime, ((ByteString) value).toByteArray()); + wrapped.setFrozen(true); + return wrapped; + } + case STRING: + { + IRubyObject wrapped = runtime.newString(value.toString()); + wrapped.setFrozen(true); + return wrapped; + } + default: + return runtime.getNil(); } + } - public static final String DESCRIPTOR_INSTANCE_VAR = "@descriptor"; + public static int num2uint(IRubyObject value) { + long longVal = RubyNumeric.num2long(value); + if (longVal > UINT_MAX) + throw value + .getRuntime() + .newRangeError("Integer " + longVal + " too big to convert to 'unsigned int'"); + long num = longVal; + if (num > Integer.MAX_VALUE || num < Integer.MIN_VALUE) + // encode to UINT32 + num = (-longVal ^ (-1l >>> 32)) + 1; + RubyNumeric.checkInt(value, num); + return (int) num; + } - public static final String EQUAL_SIGN = "="; + public static long num2ulong(Ruby runtime, IRubyObject value) { + if (value instanceof RubyFloat) { + RubyBignum bignum = RubyBignum.newBignum(runtime, ((RubyFloat) value).getDoubleValue()); + return RubyBignum.big2ulong(bignum); + } else if (value instanceof RubyBignum) { + return RubyBignum.big2ulong((RubyBignum) value); + } else { + return RubyNumeric.num2long(value); + } + } - private static final BigInteger UINT64_COMPLEMENTARY = new BigInteger("18446744073709551616"); //Math.pow(2, 64) + /* + * Helper to make it easier to support symbols being passed instead of strings + */ + public static IRubyObject symToString(IRubyObject sym) { + if (sym instanceof RubySymbol) { + return ((RubySymbol) sym).id2name(); + } + return sym; + } - private static final String EXPECTED_TYPE_ERROR_FORMAT = "Expected %s type for %s field '%s' (given %s)."; - private static final String INVALID_TYPE_ERROR_FORMAT = "Invalid argument for %s field '%s' (given %s)."; + public static void checkNameAvailability(ThreadContext context, String name) { + if (context.runtime.getObject().getConstantAt(name) != null) + throw context.runtime.newNameError(name + " is already defined", name); + } - private static final long UINT_MAX = 0xffffffffl; + public static boolean isMapEntry(FieldDescriptor fieldDescriptor) { + return fieldDescriptor.getType() == FieldDescriptor.Type.MESSAGE + && fieldDescriptor.isRepeated() + && fieldDescriptor.getMessageType().getOptions().getMapEntry(); + } - private static RubyClass cTypeError; + public static RaiseException createTypeError(ThreadContext context, String message) { + if (cTypeError == null) { + cTypeError = (RubyClass) context.runtime.getClassFromPath("Google::Protobuf::TypeError"); + } + return RaiseException.from(context.runtime, cTypeError, message); + } + + public static RaiseException createExpectedTypeError( + ThreadContext context, String type, String fieldType, String fieldName, IRubyObject value) { + return createTypeError( + context, + String.format( + EXPECTED_TYPE_ERROR_FORMAT, type, fieldType, fieldName, value.getMetaClass())); + } + + public static RaiseException createInvalidTypeError( + ThreadContext context, String fieldType, String fieldName, IRubyObject value) { + return createTypeError( + context, + String.format(INVALID_TYPE_ERROR_FORMAT, fieldType, fieldName, value.getMetaClass())); + } + + protected static boolean isRubyNum(Object value) { + return value instanceof RubyFixnum || value instanceof RubyFloat || value instanceof RubyBignum; + } + + protected static void validateTypeClass( + ThreadContext context, FieldDescriptor.Type type, IRubyObject value) { + Ruby runtime = context.runtime; + if (!(value instanceof RubyModule)) { + throw runtime.newArgumentError("TypeClass has incorrect type"); + } + RubyModule klass = (RubyModule) value; + IRubyObject descriptor = klass.getInstanceVariable(DESCRIPTOR_INSTANCE_VAR); + if (descriptor.isNil()) { + throw runtime.newArgumentError( + "Type class has no descriptor. Please pass a " + + "class or enum as returned by the DescriptorPool."); + } + if (type == FieldDescriptor.Type.MESSAGE) { + if (!(descriptor instanceof RubyDescriptor)) { + throw runtime.newArgumentError("Descriptor has an incorrect type"); + } + } else if (type == FieldDescriptor.Type.ENUM) { + if (!(descriptor instanceof RubyEnumDescriptor)) { + throw runtime.newArgumentError("Descriptor has an incorrect type"); + } + } + } + + private static IRubyObject validateAndEncodeString( + ThreadContext context, + String fieldType, + String fieldName, + IRubyObject value, + String encoding) { + if (!(value instanceof RubyString)) + throw createInvalidTypeError(context, fieldType, fieldName, value); + + value = ((RubyString) value).encode(context, context.runtime.evalScriptlet(encoding)); + value.setFrozen(true); + return value; + } + + public static final String DESCRIPTOR_INSTANCE_VAR = "@descriptor"; + + public static final String EQUAL_SIGN = "="; + + private static final BigInteger UINT64_COMPLEMENTARY = + new BigInteger("18446744073709551616"); // Math.pow(2, 64) + + private static final String EXPECTED_TYPE_ERROR_FORMAT = + "Expected %s type for %s field '%s' (given %s)."; + private static final String INVALID_TYPE_ERROR_FORMAT = + "Invalid argument for %s field '%s' (given %s)."; + + private static final long UINT_MAX = 0xffffffffl; + + private static RubyClass cTypeError; }
diff --git a/ruby/src/main/java/google/ProtobufJavaService.java b/ruby/src/main/java/google/ProtobufJavaService.java index 713891e..00d60a1 100644 --- a/ruby/src/main/java/google/ProtobufJavaService.java +++ b/ruby/src/main/java/google/ProtobufJavaService.java
@@ -33,30 +33,29 @@ package google; import com.google.protobuf.jruby.*; +import java.io.IOException; import org.jruby.Ruby; import org.jruby.runtime.load.BasicLibraryService; -import java.io.IOException; - public class ProtobufJavaService implements BasicLibraryService { - @Override - public boolean basicLoad(Ruby ruby) throws IOException { - ruby.defineModule("Google"); + @Override + public boolean basicLoad(Ruby ruby) throws IOException { + ruby.defineModule("Google"); - /* - * The order these happen in is important because we - * save a static reference to some classes and they - * need to exist before we try to save a reference to them - */ - RubyProtobuf.createProtobuf(ruby); - RubyFileDescriptor.createRubyFileDescriptor(ruby); - RubyEnumDescriptor.createRubyEnumDescriptor(ruby); - RubyRepeatedField.createRubyRepeatedField(ruby); - RubyFieldDescriptor.createRubyFieldDescriptor(ruby); - RubyMap.createRubyMap(ruby); - RubyOneofDescriptor.createRubyOneofDescriptor(ruby); - RubyDescriptor.createRubyDescriptor(ruby); - RubyDescriptorPool.createRubyDescriptorPool(ruby); - return true; - } + /* + * The order these happen in is important because we + * save a static reference to some classes and they + * need to exist before we try to save a reference to them + */ + RubyProtobuf.createProtobuf(ruby); + RubyFileDescriptor.createRubyFileDescriptor(ruby); + RubyEnumDescriptor.createRubyEnumDescriptor(ruby); + RubyRepeatedField.createRubyRepeatedField(ruby); + RubyFieldDescriptor.createRubyFieldDescriptor(ruby); + RubyMap.createRubyMap(ruby); + RubyOneofDescriptor.createRubyOneofDescriptor(ruby); + RubyDescriptor.createRubyDescriptor(ruby); + RubyDescriptorPool.createRubyDescriptorPool(ruby); + return true; + } }
diff --git a/ruby/tests/repeated_field_test.rb b/ruby/tests/repeated_field_test.rb index 7ffc0f1..881810c 100755 --- a/ruby/tests/repeated_field_test.rb +++ b/ruby/tests/repeated_field_test.rb
@@ -36,18 +36,22 @@ end fill_test_msg(m) - assert_equal -10, m.repeated_int32.first - assert_equal -1_000_000, m.repeated_int64.first + assert_equal( -10, m.repeated_int32.first ) + assert_equal( -1_000_000, m.repeated_int64.first ) assert_equal 10, m.repeated_uint32.first assert_equal 1_000_000, m.repeated_uint64.first assert_equal true, m.repeated_bool.first - assert_equal -1.01, m.repeated_float.first.round(2) - assert_equal -1.0000000000001, m.repeated_double.first + assert_equal( -1.01, m.repeated_float.first.round(2) ) + assert_equal( -1.0000000000001, m.repeated_double.first ) assert_equal 'foo', m.repeated_string.first assert_equal "bar".encode!('ASCII-8BIT'), m.repeated_bytes.first assert_equal TestMessage2.new(:foo => 1), m.repeated_msg.first assert_equal :A, m.repeated_enum.first + err = assert_raises(ArgumentError) do + m.repeated_int32.first(-1) + end + assert_equal "negative array size", err.message assert_equal [], m.repeated_int32.first(0) assert_equal [-10], m.repeated_int32.first(1) assert_equal [-10, -11], m.repeated_int32.first(2) @@ -61,17 +65,26 @@ assert_nil m.send(field_name).first end fill_test_msg(m) - assert_equal -11, m.repeated_int32.last - assert_equal -1_000_001, m.repeated_int64.last + assert_equal( -11, m.repeated_int32.last ) + assert_equal( -1_000_001, m.repeated_int64.last ) assert_equal 11, m.repeated_uint32.last assert_equal 1_000_001, m.repeated_uint64.last assert_equal false, m.repeated_bool.last - assert_equal -1.02, m.repeated_float.last.round(2) - assert_equal -1.0000000000002, m.repeated_double.last + assert_equal( -1.02, m.repeated_float.last.round(2) ) + assert_equal( -1.0000000000002, m.repeated_double.last ) assert_equal 'bar', m.repeated_string.last assert_equal "foo".encode!('ASCII-8BIT'), m.repeated_bytes.last assert_equal TestMessage2.new(:foo => 2), m.repeated_msg.last assert_equal :B, m.repeated_enum.last + + err = assert_raises(ArgumentError) do + m.repeated_int32.last(-1) + end + assert_equal "negative array size", err.message + assert_equal [], m.repeated_int32.last(0) + assert_equal [-11], m.repeated_int32.last(1) + assert_equal [-10, -11], m.repeated_int32.last(2) + assert_equal [-10, -11], m.repeated_int32.last(3) end @@ -82,20 +95,20 @@ end fill_test_msg(m) - assert_equal -11, m.repeated_int32.pop - assert_equal -10, m.repeated_int32.pop - assert_equal -1_000_001, m.repeated_int64.pop - assert_equal -1_000_000, m.repeated_int64.pop + assert_equal( -11, m.repeated_int32.pop ) + assert_equal( -10, m.repeated_int32.pop ) + assert_equal( -1_000_001, m.repeated_int64.pop ) + assert_equal( -1_000_000, m.repeated_int64.pop ) assert_equal 11, m.repeated_uint32.pop assert_equal 10, m.repeated_uint32.pop assert_equal 1_000_001, m.repeated_uint64.pop assert_equal 1_000_000, m.repeated_uint64.pop assert_equal false, m.repeated_bool.pop assert_equal true, m.repeated_bool.pop - assert_equal -1.02, m.repeated_float.pop.round(2) - assert_equal -1.01, m.repeated_float.pop.round(2) - assert_equal -1.0000000000002, m.repeated_double.pop - assert_equal -1.0000000000001, m.repeated_double.pop + assert_equal( -1.02, m.repeated_float.pop.round(2) ) + assert_equal( -1.01, m.repeated_float.pop.round(2) ) + assert_equal( -1.0000000000002, m.repeated_double.pop ) + assert_equal( -1.0000000000001, m.repeated_double.pop ) assert_equal 'bar', m.repeated_string.pop assert_equal 'foo', m.repeated_string.pop assert_equal "foo".encode!('ASCII-8BIT'), m.repeated_bytes.pop @@ -163,6 +176,51 @@ arr[0..2] end check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[0..5] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[0..-1] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[0..-3] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[0...-1] # Exclusive range + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[0...-3] # Exclusive range + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[-2..-1] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + arr[-5..-1] + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # Infinite range; introduce in Ruby 2.7. + if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7') + eval "arr[0..]" + end + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # Beginless range; introduced in Ruby 2.7. + if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7') + eval "arr[..-1]" + end + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # Infinite range; introduce in Ruby 2.7. + if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7') + eval "arr[0...]" # Exclusive range + end + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| + # Beginless range; introduced in Ruby 2.7. + if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.7') + eval "arr[...-1]" # Exclusive range + end + end + check_self_modifying_method(m.repeated_string, reference_arr) do |arr| arr[-1, 1] end check_self_modifying_method(m.repeated_string, reference_arr) do |arr| @@ -487,11 +545,8 @@ def test_shuffle! m = TestMessage.new m.repeated_string += %w(foo bar baz) - orig_repeated_string = m.repeated_string.clone result = m.repeated_string.shuffle! assert_equal m.repeated_string, result - # NOTE: sometimes it doesn't change the order... - # assert_not_equal m.repeated_string.to_a, orig_repeated_string.to_a end def test_slice!
diff --git a/src/Makefile.am b/src/Makefile.am index ad51b45..4e9742c 100644 --- a/src/Makefile.am +++ b/src/Makefile.am
@@ -74,18 +74,18 @@ google/protobuf/arenaz_sampler.h \ google/protobuf/compiler/code_generator.h \ google/protobuf/compiler/command_line_interface.h \ - google/protobuf/compiler/cpp/cpp_file.h \ - google/protobuf/compiler/cpp/cpp_generator.h \ - google/protobuf/compiler/cpp/cpp_helpers.h \ - google/protobuf/compiler/cpp/cpp_names.h \ + google/protobuf/compiler/cpp/file.h \ + google/protobuf/compiler/cpp/generator.h \ + google/protobuf/compiler/cpp/helpers.h \ + google/protobuf/compiler/cpp/names.h \ google/protobuf/compiler/csharp/csharp_doc_comment.h \ google/protobuf/compiler/csharp/csharp_generator.h \ google/protobuf/compiler/csharp/csharp_names.h \ google/protobuf/compiler/csharp/csharp_options.h \ google/protobuf/compiler/importer.h \ - google/protobuf/compiler/java/java_generator.h \ - google/protobuf/compiler/java/java_kotlin_generator.h \ - google/protobuf/compiler/java/java_names.h \ + google/protobuf/compiler/java/generator.h \ + google/protobuf/compiler/java/kotlin_generator.h \ + google/protobuf/compiler/java/names.h \ google/protobuf/compiler/js/js_generator.h \ google/protobuf/compiler/objectivec/objectivec_generator.h \ google/protobuf/compiler/objectivec/objectivec_helpers.h \ @@ -93,8 +93,8 @@ google/protobuf/compiler/php/php_generator.h \ google/protobuf/compiler/plugin.h \ google/protobuf/compiler/plugin.pb.h \ - google/protobuf/compiler/python/python_generator.h \ - google/protobuf/compiler/python/python_pyi_generator.h \ + google/protobuf/compiler/python/generator.h \ + google/protobuf/compiler/python/pyi_generator.h \ google/protobuf/compiler/ruby/ruby_generator.h \ google/protobuf/descriptor.h \ google/protobuf/descriptor.pb.h \ @@ -102,6 +102,7 @@ google/protobuf/duration.pb.h \ google/protobuf/dynamic_message.h \ google/protobuf/empty.pb.h \ + google/protobuf/endian.h \ google/protobuf/explicitly_constructed.h \ google/protobuf/extension_set.h \ google/protobuf/extension_set_inl.h \ @@ -142,6 +143,7 @@ google/protobuf/port_def.inc \ google/protobuf/port_undef.inc \ google/protobuf/reflection.h \ + google/protobuf/reflection_internal.h \ google/protobuf/reflection_ops.h \ google/protobuf/repeated_field.h \ google/protobuf/repeated_ptr_field.h \ @@ -259,7 +261,6 @@ google/protobuf/io/tokenizer.cc \ google/protobuf/map_field.cc \ google/protobuf/message.cc \ - google/protobuf/reflection_internal.h \ google/protobuf/reflection_ops.cc \ google/protobuf/service.cc \ google/protobuf/source_context.pb.cc \ @@ -325,35 +326,35 @@ libprotoc_la_SOURCES = \ google/protobuf/compiler/code_generator.cc \ google/protobuf/compiler/command_line_interface.cc \ - google/protobuf/compiler/cpp/cpp_enum.cc \ - google/protobuf/compiler/cpp/cpp_enum.h \ - google/protobuf/compiler/cpp/cpp_enum_field.cc \ - google/protobuf/compiler/cpp/cpp_enum_field.h \ - google/protobuf/compiler/cpp/cpp_extension.cc \ - google/protobuf/compiler/cpp/cpp_extension.h \ - google/protobuf/compiler/cpp/cpp_field.cc \ - google/protobuf/compiler/cpp/cpp_field.h \ - google/protobuf/compiler/cpp/cpp_file.cc \ - google/protobuf/compiler/cpp/cpp_generator.cc \ - google/protobuf/compiler/cpp/cpp_helpers.cc \ - google/protobuf/compiler/cpp/cpp_map_field.cc \ - google/protobuf/compiler/cpp/cpp_map_field.h \ - google/protobuf/compiler/cpp/cpp_message.cc \ - google/protobuf/compiler/cpp/cpp_message.h \ - google/protobuf/compiler/cpp/cpp_message_field.cc \ - google/protobuf/compiler/cpp/cpp_message_field.h \ - google/protobuf/compiler/cpp/cpp_message_layout_helper.h \ - google/protobuf/compiler/cpp/cpp_options.h \ - google/protobuf/compiler/cpp/cpp_padding_optimizer.cc \ - google/protobuf/compiler/cpp/cpp_padding_optimizer.h \ - google/protobuf/compiler/cpp/cpp_parse_function_generator.cc \ - google/protobuf/compiler/cpp/cpp_parse_function_generator.h \ - google/protobuf/compiler/cpp/cpp_primitive_field.cc \ - google/protobuf/compiler/cpp/cpp_primitive_field.h \ - google/protobuf/compiler/cpp/cpp_service.cc \ - google/protobuf/compiler/cpp/cpp_service.h \ - google/protobuf/compiler/cpp/cpp_string_field.cc \ - google/protobuf/compiler/cpp/cpp_string_field.h \ + google/protobuf/compiler/cpp/enum.cc \ + google/protobuf/compiler/cpp/enum.h \ + google/protobuf/compiler/cpp/enum_field.cc \ + google/protobuf/compiler/cpp/enum_field.h \ + google/protobuf/compiler/cpp/extension.cc \ + google/protobuf/compiler/cpp/extension.h \ + google/protobuf/compiler/cpp/field.cc \ + google/protobuf/compiler/cpp/field.h \ + google/protobuf/compiler/cpp/file.cc \ + google/protobuf/compiler/cpp/generator.cc \ + google/protobuf/compiler/cpp/helpers.cc \ + google/protobuf/compiler/cpp/map_field.cc \ + google/protobuf/compiler/cpp/map_field.h \ + google/protobuf/compiler/cpp/message.cc \ + google/protobuf/compiler/cpp/message.h \ + google/protobuf/compiler/cpp/message_field.cc \ + google/protobuf/compiler/cpp/message_field.h \ + google/protobuf/compiler/cpp/message_layout_helper.h \ + google/protobuf/compiler/cpp/options.h \ + google/protobuf/compiler/cpp/padding_optimizer.cc \ + google/protobuf/compiler/cpp/padding_optimizer.h \ + google/protobuf/compiler/cpp/parse_function_generator.cc \ + google/protobuf/compiler/cpp/parse_function_generator.h \ + google/protobuf/compiler/cpp/primitive_field.cc \ + google/protobuf/compiler/cpp/primitive_field.h \ + google/protobuf/compiler/cpp/service.cc \ + google/protobuf/compiler/cpp/service.h \ + google/protobuf/compiler/cpp/string_field.cc \ + google/protobuf/compiler/cpp/string_field.h \ google/protobuf/compiler/csharp/csharp_doc_comment.cc \ google/protobuf/compiler/csharp/csharp_enum.cc \ google/protobuf/compiler/csharp/csharp_enum.h \ @@ -384,63 +385,63 @@ google/protobuf/compiler/csharp/csharp_source_generator_base.h \ google/protobuf/compiler/csharp/csharp_wrapper_field.cc \ google/protobuf/compiler/csharp/csharp_wrapper_field.h \ - google/protobuf/compiler/java/java_context.cc \ - google/protobuf/compiler/java/java_context.h \ - google/protobuf/compiler/java/java_doc_comment.cc \ - google/protobuf/compiler/java/java_doc_comment.h \ - google/protobuf/compiler/java/java_enum.cc \ - google/protobuf/compiler/java/java_enum.h \ - google/protobuf/compiler/java/java_enum_field.cc \ - google/protobuf/compiler/java/java_enum_field.h \ - google/protobuf/compiler/java/java_enum_field_lite.cc \ - google/protobuf/compiler/java/java_enum_field_lite.h \ - google/protobuf/compiler/java/java_enum_lite.cc \ - google/protobuf/compiler/java/java_enum_lite.h \ - google/protobuf/compiler/java/java_extension.cc \ - google/protobuf/compiler/java/java_extension.h \ - google/protobuf/compiler/java/java_extension_lite.cc \ - google/protobuf/compiler/java/java_extension_lite.h \ - google/protobuf/compiler/java/java_field.cc \ - google/protobuf/compiler/java/java_field.h \ - google/protobuf/compiler/java/java_file.cc \ - google/protobuf/compiler/java/java_file.h \ - google/protobuf/compiler/java/java_generator.cc \ - google/protobuf/compiler/java/java_generator_factory.cc \ - google/protobuf/compiler/java/java_generator_factory.h \ - google/protobuf/compiler/java/java_helpers.cc \ - google/protobuf/compiler/java/java_helpers.h \ - google/protobuf/compiler/java/java_kotlin_generator.cc \ - google/protobuf/compiler/java/java_map_field.cc \ - google/protobuf/compiler/java/java_map_field.h \ - google/protobuf/compiler/java/java_map_field_lite.cc \ - google/protobuf/compiler/java/java_map_field_lite.h \ - google/protobuf/compiler/java/java_message.cc \ - google/protobuf/compiler/java/java_message.h \ - google/protobuf/compiler/java/java_message_builder.cc \ - google/protobuf/compiler/java/java_message_builder.h \ - google/protobuf/compiler/java/java_message_builder_lite.cc \ - google/protobuf/compiler/java/java_message_builder_lite.h \ - google/protobuf/compiler/java/java_message_field.cc \ - google/protobuf/compiler/java/java_message_field.h \ - google/protobuf/compiler/java/java_message_field_lite.cc \ - google/protobuf/compiler/java/java_message_field_lite.h \ - google/protobuf/compiler/java/java_message_lite.cc \ - google/protobuf/compiler/java/java_message_lite.h \ - google/protobuf/compiler/java/java_name_resolver.cc \ - google/protobuf/compiler/java/java_name_resolver.h \ - google/protobuf/compiler/java/java_options.h \ - google/protobuf/compiler/java/java_primitive_field.cc \ - google/protobuf/compiler/java/java_primitive_field.h \ - google/protobuf/compiler/java/java_primitive_field_lite.cc \ - google/protobuf/compiler/java/java_primitive_field_lite.h \ - google/protobuf/compiler/java/java_service.cc \ - google/protobuf/compiler/java/java_service.h \ - google/protobuf/compiler/java/java_shared_code_generator.cc \ - google/protobuf/compiler/java/java_shared_code_generator.h \ - google/protobuf/compiler/java/java_string_field.cc \ - google/protobuf/compiler/java/java_string_field.h \ - google/protobuf/compiler/java/java_string_field_lite.cc \ - google/protobuf/compiler/java/java_string_field_lite.h \ + google/protobuf/compiler/java/context.cc \ + google/protobuf/compiler/java/context.h \ + google/protobuf/compiler/java/doc_comment.cc \ + google/protobuf/compiler/java/doc_comment.h \ + google/protobuf/compiler/java/enum.cc \ + google/protobuf/compiler/java/enum.h \ + google/protobuf/compiler/java/enum_field.cc \ + google/protobuf/compiler/java/enum_field.h \ + google/protobuf/compiler/java/enum_field_lite.cc \ + google/protobuf/compiler/java/enum_field_lite.h \ + google/protobuf/compiler/java/enum_lite.cc \ + google/protobuf/compiler/java/enum_lite.h \ + google/protobuf/compiler/java/extension.cc \ + google/protobuf/compiler/java/extension.h \ + google/protobuf/compiler/java/extension_lite.cc \ + google/protobuf/compiler/java/extension_lite.h \ + google/protobuf/compiler/java/field.cc \ + google/protobuf/compiler/java/field.h \ + google/protobuf/compiler/java/file.cc \ + google/protobuf/compiler/java/file.h \ + google/protobuf/compiler/java/generator.cc \ + google/protobuf/compiler/java/generator_factory.cc \ + google/protobuf/compiler/java/generator_factory.h \ + google/protobuf/compiler/java/helpers.cc \ + google/protobuf/compiler/java/helpers.h \ + google/protobuf/compiler/java/kotlin_generator.cc \ + google/protobuf/compiler/java/map_field.cc \ + google/protobuf/compiler/java/map_field.h \ + google/protobuf/compiler/java/map_field_lite.cc \ + google/protobuf/compiler/java/map_field_lite.h \ + google/protobuf/compiler/java/message.cc \ + google/protobuf/compiler/java/message.h \ + google/protobuf/compiler/java/message_builder.cc \ + google/protobuf/compiler/java/message_builder.h \ + google/protobuf/compiler/java/message_builder_lite.cc \ + google/protobuf/compiler/java/message_builder_lite.h \ + google/protobuf/compiler/java/message_field.cc \ + google/protobuf/compiler/java/message_field.h \ + google/protobuf/compiler/java/message_field_lite.cc \ + google/protobuf/compiler/java/message_field_lite.h \ + google/protobuf/compiler/java/message_lite.cc \ + google/protobuf/compiler/java/message_lite.h \ + google/protobuf/compiler/java/name_resolver.cc \ + google/protobuf/compiler/java/name_resolver.h \ + google/protobuf/compiler/java/options.h \ + google/protobuf/compiler/java/primitive_field.cc \ + google/protobuf/compiler/java/primitive_field.h \ + google/protobuf/compiler/java/primitive_field_lite.cc \ + google/protobuf/compiler/java/primitive_field_lite.h \ + google/protobuf/compiler/java/service.cc \ + google/protobuf/compiler/java/service.h \ + google/protobuf/compiler/java/shared_code_generator.cc \ + google/protobuf/compiler/java/shared_code_generator.h \ + google/protobuf/compiler/java/string_field.cc \ + google/protobuf/compiler/java/string_field.h \ + google/protobuf/compiler/java/string_field_lite.cc \ + google/protobuf/compiler/java/string_field_lite.h \ google/protobuf/compiler/js/js_generator.cc \ google/protobuf/compiler/js/well_known_types_embed.cc \ google/protobuf/compiler/js/well_known_types_embed.h \ @@ -470,10 +471,10 @@ google/protobuf/compiler/php/php_generator.cc \ google/protobuf/compiler/plugin.cc \ google/protobuf/compiler/plugin.pb.cc \ - google/protobuf/compiler/python/python_generator.cc \ - google/protobuf/compiler/python/python_helpers.cc \ - google/protobuf/compiler/python/python_helpers.h \ - google/protobuf/compiler/python/python_pyi_generator.cc \ + google/protobuf/compiler/python/generator.cc \ + google/protobuf/compiler/python/helpers.cc \ + google/protobuf/compiler/python/helpers.h \ + google/protobuf/compiler/python/pyi_generator.cc \ google/protobuf/compiler/ruby/ruby_generator.cc \ google/protobuf/compiler/scc.h \ google/protobuf/compiler/subprocess.cc \ @@ -489,8 +490,8 @@ protoc_inputs = \ google/protobuf/any_test.proto \ - google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto \ - google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto \ + google/protobuf/compiler/cpp/test_bad_identifiers.proto \ + google/protobuf/compiler/cpp/test_large_enum_value.proto \ google/protobuf/map_lite_unittest.proto \ google/protobuf/map_proto2_unittest.proto \ google/protobuf/map_unittest.proto \ @@ -593,10 +594,10 @@ $(protoc_lite_outputs) \ google/protobuf/any_test.pb.cc \ google/protobuf/any_test.pb.h \ - google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.cc \ - google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h \ - google/protobuf/compiler/cpp/cpp_test_large_enum_value.pb.cc \ - google/protobuf/compiler/cpp/cpp_test_large_enum_value.pb.h \ + google/protobuf/compiler/cpp/test_bad_identifiers.pb.cc \ + google/protobuf/compiler/cpp/test_bad_identifiers.pb.h \ + google/protobuf/compiler/cpp/test_large_enum_value.pb.cc \ + google/protobuf/compiler/cpp/test_large_enum_value.pb.h \ google/protobuf/map_proto2_unittest.pb.cc \ google/protobuf/map_proto2_unittest.pb.h \ google/protobuf/map_unittest.pb.cc \ @@ -703,7 +704,7 @@ COMMON_TEST_SOURCES = \ $(COMMON_LITE_TEST_SOURCES) \ - google/protobuf/compiler/cpp/cpp_unittest.h \ + google/protobuf/compiler/cpp/unittest.h \ google/protobuf/map_test_util.h \ google/protobuf/map_test_util.inc \ google/protobuf/reflection_tester.cc \ @@ -743,22 +744,23 @@ google/protobuf/compiler/annotation_test_util.cc \ google/protobuf/compiler/annotation_test_util.h \ google/protobuf/compiler/command_line_interface_unittest.cc \ - google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc \ - google/protobuf/compiler/cpp/cpp_move_unittest.cc \ - google/protobuf/compiler/cpp/cpp_plugin_unittest.cc \ - google/protobuf/compiler/cpp/cpp_unittest.cc \ - google/protobuf/compiler/cpp/cpp_unittest.inc \ + google/protobuf/compiler/cpp/bootstrap_unittest.cc \ + google/protobuf/compiler/cpp/message_size_unittest.cc \ google/protobuf/compiler/cpp/metadata_test.cc \ + google/protobuf/compiler/cpp/move_unittest.cc \ + google/protobuf/compiler/cpp/plugin_unittest.cc \ + google/protobuf/compiler/cpp/unittest.cc \ + google/protobuf/compiler/cpp/unittest.inc \ google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc \ google/protobuf/compiler/csharp/csharp_generator_unittest.cc \ google/protobuf/compiler/importer_unittest.cc \ - google/protobuf/compiler/java/java_doc_comment_unittest.cc \ - google/protobuf/compiler/java/java_plugin_unittest.cc \ + google/protobuf/compiler/java/doc_comment_unittest.cc \ + google/protobuf/compiler/java/plugin_unittest.cc \ google/protobuf/compiler/mock_code_generator.cc \ google/protobuf/compiler/mock_code_generator.h \ google/protobuf/compiler/objectivec/objectivec_helpers_unittest.cc \ google/protobuf/compiler/parser_unittest.cc \ - google/protobuf/compiler/python/python_plugin_unittest.cc \ + google/protobuf/compiler/python/plugin_unittest.cc \ google/protobuf/compiler/ruby/ruby_generator_unittest.cc \ google/protobuf/descriptor_database_unittest.cc \ google/protobuf/descriptor_unittest.cc \ @@ -831,7 +833,7 @@ -DPROTOBUF_TEST_NO_DESCRIPTORS protobuf_lazy_descriptor_test_CXXFLAGS = $(NO_OPT_CXXFLAGS) protobuf_lazy_descriptor_test_SOURCES = \ - google/protobuf/compiler/cpp/cpp_unittest.cc \ + google/protobuf/compiler/cpp/unittest.cc \ $(COMMON_TEST_SOURCES) nodist_protobuf_lazy_descriptor_test_SOURCES = $(protoc_outputs) $(am_protobuf_lazy_descriptor_test_OBJECTS): unittest_proto_middleman
diff --git a/src/README.md b/src/README.md index 80e8668..cf843d7 100644 --- a/src/README.md +++ b/src/README.md
@@ -129,6 +129,10 @@ sudo /opt/local/bin/port install autoconf automake libtool +Alternative for Homebrew users: + + brew install autoconf automake libtool + Then follow the Unix instructions above. **Note for cross-compiling**
diff --git a/src/google/protobuf/any.h b/src/google/protobuf/any.h index d688a0c..92ea2bb 100644 --- a/src/google/protobuf/any.h +++ b/src/google/protobuf/any.h
@@ -130,8 +130,8 @@ // *full_type_name. Returns false if the type_url does not have a "/" // in the type url separating the full type name. // -// NOTE: this function is available publicly as: -// google::protobuf::Any() // static method on the generated message type. +// NOTE: this function is available publicly as a static method on the +// generated message type: google::protobuf::Any::ParseAnyTypeUrl() bool ParseAnyTypeUrl(StringPiece type_url, std::string* full_type_name); // Get the proto type name and prefix from Any::type_url value. For example,
diff --git a/src/google/protobuf/any.pb.cc b/src/google/protobuf/any.pb.cc index 74b7903..6bedc64 100644 --- a/src/google/protobuf/any.pb.cc +++ b/src/google/protobuf/any.pb.cc
@@ -26,10 +26,11 @@ #endif // __llvm__ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Any::Any( - ::_pbi::ConstantInitialized) - : type_url_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , value_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , _any_metadata_(&type_url_, &value_){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.type_url_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_._any_metadata_)*/{&_impl_.type_url_, &_impl_.value_}} {} struct AnyDefaultTypeInternal { PROTOBUF_CONSTEXPR AnyDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -51,8 +52,8 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, type_url_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _impl_.type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Any, _impl_.value_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Any)}, @@ -108,43 +109,56 @@ Any::Any(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _any_metadata_(&type_url_, &value_) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Any) } Any::Any(const Any& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _any_metadata_(&type_url_, &value_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.type_url_){} + , decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_._any_metadata_)*/{&_impl_.type_url_, &_impl_.value_}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - type_url_.InitDefault(); + _impl_.type_url_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - type_url_.Set("", GetArenaForAllocation()); + _impl_.type_url_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_type_url().empty()) { - type_url_.Set(from._internal_type_url(), + _impl_.type_url_.Set(from._internal_type_url(), GetArenaForAllocation()); } - value_.InitDefault(); + _impl_.value_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - value_.Set("", GetArenaForAllocation()); + _impl_.value_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_value().empty()) { - value_.Set(from._internal_value(), + _impl_.value_.Set(from._internal_value(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:google.protobuf.Any) } -inline void Any::SharedCtor() { -type_url_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - type_url_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -value_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - value_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING +inline void Any::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.type_url_){} + , decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_._any_metadata_)*/{&_impl_.type_url_, &_impl_.value_} + }; + _impl_.type_url_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.type_url_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.value_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.value_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Any::~Any() { @@ -158,12 +172,13 @@ inline void Any::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - type_url_.Destroy(); - value_.Destroy(); + _impl_.type_url_.Destroy(); + _impl_.value_.Destroy(); + _impl_._any_metadata_.~AnyMetadata(); } void Any::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Any::Clear() { @@ -172,8 +187,8 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - type_url_.ClearToEmpty(); - value_.ClearToEmpty(); + _impl_.type_url_.ClearToEmpty(); + _impl_.value_.ClearToEmpty(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -277,11 +292,11 @@ this->_internal_value()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Any::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Any::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Any::GetClassData() const { return &_class_data_; } @@ -325,12 +340,12 @@ auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &type_url_, lhs_arena, - &other->type_url_, rhs_arena + &_impl_.type_url_, lhs_arena, + &other->_impl_.type_url_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &value_, lhs_arena, - &other->value_, rhs_arena + &_impl_.value_, lhs_arena, + &other->_impl_.value_, rhs_arena ); }
diff --git a/src/google/protobuf/any.pb.h b/src/google/protobuf/any.pb.h index 39e47d1..8fa3ab0 100644 --- a/src/google/protobuf/any.pb.h +++ b/src/google/protobuf/any.pb.h
@@ -109,14 +109,16 @@ // implements Any ----------------------------------------------- bool PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message) { - return _any_metadata_.PackFrom(GetArena(), message); + GOOGLE_DCHECK_NE(&message, this); + return _impl_._any_metadata_.PackFrom(GetArena(), message); } bool PackFrom(const ::PROTOBUF_NAMESPACE_ID::Message& message, ::PROTOBUF_NAMESPACE_ID::ConstStringParam type_url_prefix) { - return _any_metadata_.PackFrom(GetArena(), message, type_url_prefix); + GOOGLE_DCHECK_NE(&message, this); + return _impl_._any_metadata_.PackFrom(GetArena(), message, type_url_prefix); } bool UnpackTo(::PROTOBUF_NAMESPACE_ID::Message* message) const { - return _any_metadata_.UnpackTo(message); + return _impl_._any_metadata_.UnpackTo(message); } static bool GetAnyFieldDescriptors( const ::PROTOBUF_NAMESPACE_ID::Message& message, @@ -124,18 +126,18 @@ const ::PROTOBUF_NAMESPACE_ID::FieldDescriptor** value_field); template <typename T, class = typename std::enable_if<!std::is_convertible<T, const ::PROTOBUF_NAMESPACE_ID::Message&>::value>::type> bool PackFrom(const T& message) { - return _any_metadata_.PackFrom<T>(GetArena(), message); + return _impl_._any_metadata_.PackFrom<T>(GetArena(), message); } template <typename T, class = typename std::enable_if<!std::is_convertible<T, const ::PROTOBUF_NAMESPACE_ID::Message&>::value>::type> bool PackFrom(const T& message, ::PROTOBUF_NAMESPACE_ID::ConstStringParam type_url_prefix) { - return _any_metadata_.PackFrom<T>(GetArena(), message, type_url_prefix);} + return _impl_._any_metadata_.PackFrom<T>(GetArena(), message, type_url_prefix);} template <typename T, class = typename std::enable_if<!std::is_convertible<T, const ::PROTOBUF_NAMESPACE_ID::Message&>::value>::type> bool UnpackTo(T* message) const { - return _any_metadata_.UnpackTo<T>(message); + return _impl_._any_metadata_.UnpackTo<T>(message); } template<typename T> bool Is() const { - return _any_metadata_.Is<T>(); + return _impl_._any_metadata_.Is<T>(); } static bool ParseAnyTypeUrl(::PROTOBUF_NAMESPACE_ID::ConstStringParam type_url, std::string* full_type_name); @@ -180,10 +182,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Any* other); @@ -246,10 +248,13 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata _any_metadata_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata _any_metadata_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fany_2eproto; }; // =================================================================== @@ -265,7 +270,7 @@ // string type_url = 1; inline void Any::clear_type_url() { - type_url_.ClearToEmpty(); + _impl_.type_url_.ClearToEmpty(); } inline const std::string& Any::type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Any.type_url) @@ -275,7 +280,7 @@ inline PROTOBUF_ALWAYS_INLINE void Any::set_type_url(ArgT0&& arg0, ArgT... args) { - type_url_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.type_url_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Any.type_url) } inline std::string* Any::mutable_type_url() { @@ -284,19 +289,19 @@ return _s; } inline const std::string& Any::_internal_type_url() const { - return type_url_.Get(); + return _impl_.type_url_.Get(); } inline void Any::_internal_set_type_url(const std::string& value) { - type_url_.Set(value, GetArenaForAllocation()); + _impl_.type_url_.Set(value, GetArenaForAllocation()); } inline std::string* Any::_internal_mutable_type_url() { - return type_url_.Mutable(GetArenaForAllocation()); + return _impl_.type_url_.Mutable(GetArenaForAllocation()); } inline std::string* Any::release_type_url() { // @@protoc_insertion_point(field_release:google.protobuf.Any.type_url) - return type_url_.Release(); + return _impl_.type_url_.Release(); } inline void Any::set_allocated_type_url(std::string* type_url) { if (type_url != nullptr) { @@ -304,10 +309,10 @@ } else { } - type_url_.SetAllocated(type_url, GetArenaForAllocation()); + _impl_.type_url_.SetAllocated(type_url, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (type_url_.IsDefault()) { - type_url_.Set("", GetArenaForAllocation()); + if (_impl_.type_url_.IsDefault()) { + _impl_.type_url_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.type_url) @@ -315,7 +320,7 @@ // bytes value = 2; inline void Any::clear_value() { - value_.ClearToEmpty(); + _impl_.value_.ClearToEmpty(); } inline const std::string& Any::value() const { // @@protoc_insertion_point(field_get:google.protobuf.Any.value) @@ -325,7 +330,7 @@ inline PROTOBUF_ALWAYS_INLINE void Any::set_value(ArgT0&& arg0, ArgT... args) { - value_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.value_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Any.value) } inline std::string* Any::mutable_value() { @@ -334,19 +339,19 @@ return _s; } inline const std::string& Any::_internal_value() const { - return value_.Get(); + return _impl_.value_.Get(); } inline void Any::_internal_set_value(const std::string& value) { - value_.Set(value, GetArenaForAllocation()); + _impl_.value_.Set(value, GetArenaForAllocation()); } inline std::string* Any::_internal_mutable_value() { - return value_.Mutable(GetArenaForAllocation()); + return _impl_.value_.Mutable(GetArenaForAllocation()); } inline std::string* Any::release_value() { // @@protoc_insertion_point(field_release:google.protobuf.Any.value) - return value_.Release(); + return _impl_.value_.Release(); } inline void Any::set_allocated_value(std::string* value) { if (value != nullptr) { @@ -354,10 +359,10 @@ } else { } - value_.SetAllocated(value, GetArenaForAllocation()); + _impl_.value_.SetAllocated(value, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (value_.IsDefault()) { - value_.Set("", GetArenaForAllocation()); + if (_impl_.value_.IsDefault()) { + _impl_.value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Any.value)
diff --git a/src/google/protobuf/any_test.cc b/src/google/protobuf/any_test.cc index 1d136aa..a82afb2 100644 --- a/src/google/protobuf/any_test.cc +++ b/src/google/protobuf/any_test.cc
@@ -176,6 +176,16 @@ EXPECT_EQ(12345, payload.int32_value()); } +#ifdef PROTOBUF_HAS_DEATH_TEST +#ifndef NDEBUG +TEST(AnyTest, PackSelfDeath) { + google::protobuf::Any any; + EXPECT_DEATH(any.PackFrom(any), "&message"); + EXPECT_DEATH(any.PackFrom(any, ""), "&message"); +} +#endif // !NDEBUG +#endif // PROTOBUF_HAS_DEATH_TEST + } // namespace } // namespace protobuf
diff --git a/src/google/protobuf/api.pb.cc b/src/google/protobuf/api.pb.cc index 7b35b0c..98eed9e 100644 --- a/src/google/protobuf/api.pb.cc +++ b/src/google/protobuf/api.pb.cc
@@ -22,15 +22,15 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Api::Api( - ::_pbi::ConstantInitialized) - : methods_() - , options_() - , mixins_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , version_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , source_context_(nullptr) - , syntax_(0) -{} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.methods_)*/{} + , /*decltype(_impl_.options_)*/{} + , /*decltype(_impl_.mixins_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.version_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.source_context_)*/nullptr + , /*decltype(_impl_.syntax_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct ApiDefaultTypeInternal { PROTOBUF_CONSTEXPR ApiDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -41,15 +41,15 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ApiDefaultTypeInternal _Api_default_instance_; PROTOBUF_CONSTEXPR Method::Method( - ::_pbi::ConstantInitialized) - : options_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , request_type_url_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , response_type_url_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , request_streaming_(false) - , response_streaming_(false) - , syntax_(0) -{} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.options_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.request_type_url_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.response_type_url_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.request_streaming_)*/false + , /*decltype(_impl_.response_streaming_)*/false + , /*decltype(_impl_.syntax_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct MethodDefaultTypeInternal { PROTOBUF_CONSTEXPR MethodDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -60,9 +60,10 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 MethodDefaultTypeInternal _Method_default_instance_; PROTOBUF_CONSTEXPR Mixin::Mixin( - ::_pbi::ConstantInitialized) - : name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , root_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.root_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_._cached_size_)*/{}} {} struct MixinDefaultTypeInternal { PROTOBUF_CONSTEXPR MixinDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -84,34 +85,34 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, methods_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, version_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, source_context_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, mixins_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, syntax_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.methods_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.version_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.source_context_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.mixins_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Api, _impl_.syntax_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, request_type_url_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, request_streaming_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, response_type_url_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, response_streaming_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, syntax_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.request_type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.request_streaming_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.response_type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.response_streaming_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Method, _impl_.syntax_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, root_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Mixin, _impl_.root_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Api)}, @@ -176,70 +177,81 @@ const ::PROTOBUF_NAMESPACE_ID::SourceContext& Api::_Internal::source_context(const Api* msg) { - return *msg->source_context_; + return *msg->_impl_.source_context_; } void Api::clear_options() { - options_.Clear(); + _impl_.options_.Clear(); } void Api::clear_source_context() { - if (GetArenaForAllocation() == nullptr && source_context_ != nullptr) { - delete source_context_; + if (GetArenaForAllocation() == nullptr && _impl_.source_context_ != nullptr) { + delete _impl_.source_context_; } - source_context_ = nullptr; + _impl_.source_context_ = nullptr; } Api::Api(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - methods_(arena), - options_(arena), - mixins_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Api) } Api::Api(const Api& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - methods_(from.methods_), - options_(from.options_), - mixins_(from.mixins_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.methods_){from._impl_.methods_} + , decltype(_impl_.options_){from._impl_.options_} + , decltype(_impl_.mixins_){from._impl_.mixins_} + , decltype(_impl_.name_){} + , decltype(_impl_.version_){} + , decltype(_impl_.source_context_){nullptr} + , decltype(_impl_.syntax_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_name().empty()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - version_.InitDefault(); + _impl_.version_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - version_.Set("", GetArenaForAllocation()); + _impl_.version_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_version().empty()) { - version_.Set(from._internal_version(), + _impl_.version_.Set(from._internal_version(), GetArenaForAllocation()); } if (from._internal_has_source_context()) { - source_context_ = new ::PROTOBUF_NAMESPACE_ID::SourceContext(*from.source_context_); - } else { - source_context_ = nullptr; + _impl_.source_context_ = new ::PROTOBUF_NAMESPACE_ID::SourceContext(*from._impl_.source_context_); } - syntax_ = from.syntax_; + _impl_.syntax_ = from._impl_.syntax_; // @@protoc_insertion_point(copy_constructor:google.protobuf.Api) } -inline void Api::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -version_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - version_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&source_context_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&syntax_) - - reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_)); +inline void Api::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.methods_){arena} + , decltype(_impl_.options_){arena} + , decltype(_impl_.mixins_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.version_){} + , decltype(_impl_.source_context_){nullptr} + , decltype(_impl_.syntax_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.version_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.version_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Api::~Api() { @@ -253,13 +265,16 @@ inline void Api::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - version_.Destroy(); - if (this != internal_default_instance()) delete source_context_; + _impl_.methods_.~RepeatedPtrField(); + _impl_.options_.~RepeatedPtrField(); + _impl_.mixins_.~RepeatedPtrField(); + _impl_.name_.Destroy(); + _impl_.version_.Destroy(); + if (this != internal_default_instance()) delete _impl_.source_context_; } void Api::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Api::Clear() { @@ -268,16 +283,16 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - methods_.Clear(); - options_.Clear(); - mixins_.Clear(); - name_.ClearToEmpty(); - version_.ClearToEmpty(); - if (GetArenaForAllocation() == nullptr && source_context_ != nullptr) { - delete source_context_; + _impl_.methods_.Clear(); + _impl_.options_.Clear(); + _impl_.mixins_.Clear(); + _impl_.name_.ClearToEmpty(); + _impl_.version_.ClearToEmpty(); + if (GetArenaForAllocation() == nullptr && _impl_.source_context_ != nullptr) { + delete _impl_.source_context_; } - source_context_ = nullptr; - syntax_ = 0; + _impl_.source_context_ = nullptr; + _impl_.syntax_ = 0; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -468,21 +483,21 @@ // repeated .google.protobuf.Method methods = 2; total_size += 1UL * this->_internal_methods_size(); - for (const auto& msg : this->methods_) { + for (const auto& msg : this->_impl_.methods_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.Option options = 3; total_size += 1UL * this->_internal_options_size(); - for (const auto& msg : this->options_) { + for (const auto& msg : this->_impl_.options_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.Mixin mixins = 6; total_size += 1UL * this->_internal_mixins_size(); - for (const auto& msg : this->mixins_) { + for (const auto& msg : this->_impl_.mixins_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } @@ -505,7 +520,7 @@ if (this->_internal_has_source_context()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *source_context_); + *_impl_.source_context_); } // .google.protobuf.Syntax syntax = 7; @@ -514,11 +529,11 @@ ::_pbi::WireFormatLite::EnumSize(this->_internal_syntax()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Api::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Api::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Api::GetClassData() const { return &_class_data_; } @@ -536,9 +551,9 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - methods_.MergeFrom(from.methods_); - options_.MergeFrom(from.options_); - mixins_.MergeFrom(from.mixins_); + _impl_.methods_.MergeFrom(from._impl_.methods_); + _impl_.options_.MergeFrom(from._impl_.options_); + _impl_.mixins_.MergeFrom(from._impl_.mixins_); if (!from._internal_name().empty()) { _internal_set_name(from._internal_name()); } @@ -570,23 +585,23 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - methods_.InternalSwap(&other->methods_); - options_.InternalSwap(&other->options_); - mixins_.InternalSwap(&other->mixins_); + _impl_.methods_.InternalSwap(&other->_impl_.methods_); + _impl_.options_.InternalSwap(&other->_impl_.options_); + _impl_.mixins_.InternalSwap(&other->_impl_.mixins_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &version_, lhs_arena, - &other->version_, rhs_arena + &_impl_.version_, lhs_arena, + &other->_impl_.version_, rhs_arena ); ::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_FIELD_OFFSET(Api, _impl_.syntax_) + + sizeof(Api::_impl_.syntax_) + - PROTOBUF_FIELD_OFFSET(Api, _impl_.source_context_)>( + reinterpret_cast<char*>(&_impl_.source_context_), + reinterpret_cast<char*>(&other->_impl_.source_context_)); } ::PROTOBUF_NAMESPACE_ID::Metadata Api::GetMetadata() const { @@ -602,66 +617,83 @@ }; void Method::clear_options() { - options_.Clear(); + _impl_.options_.Clear(); } Method::Method(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - options_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Method) } Method::Method(const Method& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - options_(from.options_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.options_){from._impl_.options_} + , decltype(_impl_.name_){} + , decltype(_impl_.request_type_url_){} + , decltype(_impl_.response_type_url_){} + , decltype(_impl_.request_streaming_){} + , decltype(_impl_.response_streaming_){} + , decltype(_impl_.syntax_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_name().empty()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - request_type_url_.InitDefault(); + _impl_.request_type_url_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - request_type_url_.Set("", GetArenaForAllocation()); + _impl_.request_type_url_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_request_type_url().empty()) { - request_type_url_.Set(from._internal_request_type_url(), + _impl_.request_type_url_.Set(from._internal_request_type_url(), GetArenaForAllocation()); } - response_type_url_.InitDefault(); + _impl_.response_type_url_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - response_type_url_.Set("", GetArenaForAllocation()); + _impl_.response_type_url_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_response_type_url().empty()) { - response_type_url_.Set(from._internal_response_type_url(), + _impl_.response_type_url_.Set(from._internal_response_type_url(), GetArenaForAllocation()); } - ::memcpy(&request_streaming_, &from.request_streaming_, - static_cast<size_t>(reinterpret_cast<char*>(&syntax_) - - reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_)); + ::memcpy(&_impl_.request_streaming_, &from._impl_.request_streaming_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.syntax_) - + reinterpret_cast<char*>(&_impl_.request_streaming_)) + sizeof(_impl_.syntax_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.Method) } -inline void Method::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -request_type_url_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - request_type_url_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -response_type_url_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - response_type_url_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&request_streaming_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&syntax_) - - reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_)); +inline void Method::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.options_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.request_type_url_){} + , decltype(_impl_.response_type_url_){} + , decltype(_impl_.request_streaming_){false} + , decltype(_impl_.response_streaming_){false} + , decltype(_impl_.syntax_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.request_type_url_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.request_type_url_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.response_type_url_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.response_type_url_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Method::~Method() { @@ -675,13 +707,14 @@ inline void Method::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - request_type_url_.Destroy(); - response_type_url_.Destroy(); + _impl_.options_.~RepeatedPtrField(); + _impl_.name_.Destroy(); + _impl_.request_type_url_.Destroy(); + _impl_.response_type_url_.Destroy(); } void Method::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Method::Clear() { @@ -690,13 +723,13 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - options_.Clear(); - name_.ClearToEmpty(); - request_type_url_.ClearToEmpty(); - response_type_url_.ClearToEmpty(); - ::memset(&request_streaming_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&syntax_) - - reinterpret_cast<char*>(&request_streaming_)) + sizeof(syntax_)); + _impl_.options_.Clear(); + _impl_.name_.ClearToEmpty(); + _impl_.request_type_url_.ClearToEmpty(); + _impl_.response_type_url_.ClearToEmpty(); + ::memset(&_impl_.request_streaming_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.syntax_) - + reinterpret_cast<char*>(&_impl_.request_streaming_)) + sizeof(_impl_.syntax_)); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -729,7 +762,7 @@ // bool request_streaming = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) { - request_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.request_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -747,7 +780,7 @@ // bool response_streaming = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 40)) { - response_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.response_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -878,7 +911,7 @@ // repeated .google.protobuf.Option options = 6; total_size += 1UL * this->_internal_options_size(); - for (const auto& msg : this->options_) { + for (const auto& msg : this->_impl_.options_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } @@ -920,11 +953,11 @@ ::_pbi::WireFormatLite::EnumSize(this->_internal_syntax()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Method::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Method::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Method::GetClassData() const { return &_class_data_; } @@ -942,7 +975,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - options_.MergeFrom(from.options_); + _impl_.options_.MergeFrom(from._impl_.options_); if (!from._internal_name().empty()) { _internal_set_name(from._internal_name()); } @@ -980,25 +1013,25 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - options_.InternalSwap(&other->options_); + _impl_.options_.InternalSwap(&other->_impl_.options_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &request_type_url_, lhs_arena, - &other->request_type_url_, rhs_arena + &_impl_.request_type_url_, lhs_arena, + &other->_impl_.request_type_url_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &response_type_url_, lhs_arena, - &other->response_type_url_, rhs_arena + &_impl_.response_type_url_, lhs_arena, + &other->_impl_.response_type_url_, rhs_arena ); ::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_FIELD_OFFSET(Method, _impl_.syntax_) + + sizeof(Method::_impl_.syntax_) + - PROTOBUF_FIELD_OFFSET(Method, _impl_.request_streaming_)>( + reinterpret_cast<char*>(&_impl_.request_streaming_), + reinterpret_cast<char*>(&other->_impl_.request_streaming_)); } ::PROTOBUF_NAMESPACE_ID::Metadata Method::GetMetadata() const { @@ -1016,40 +1049,53 @@ Mixin::Mixin(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Mixin) } Mixin::Mixin(const Mixin& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.name_){} + , decltype(_impl_.root_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_name().empty()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - root_.InitDefault(); + _impl_.root_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - root_.Set("", GetArenaForAllocation()); + _impl_.root_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_root().empty()) { - root_.Set(from._internal_root(), + _impl_.root_.Set(from._internal_root(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:google.protobuf.Mixin) } -inline void Mixin::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -root_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - root_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING +inline void Mixin::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.name_){} + , decltype(_impl_.root_){} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.root_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.root_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Mixin::~Mixin() { @@ -1063,12 +1109,12 @@ inline void Mixin::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - root_.Destroy(); + _impl_.name_.Destroy(); + _impl_.root_.Destroy(); } void Mixin::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Mixin::Clear() { @@ -1077,8 +1123,8 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - name_.ClearToEmpty(); - root_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); + _impl_.root_.ClearToEmpty(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1187,11 +1233,11 @@ this->_internal_root()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Mixin::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Mixin::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Mixin::GetClassData() const { return &_class_data_; } @@ -1235,12 +1281,12 @@ auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &root_, lhs_arena, - &other->root_, rhs_arena + &_impl_.root_, lhs_arena, + &other->_impl_.root_, rhs_arena ); }
diff --git a/src/google/protobuf/api.pb.h b/src/google/protobuf/api.pb.h index d68d8cf..744e467 100644 --- a/src/google/protobuf/api.pb.h +++ b/src/google/protobuf/api.pb.h
@@ -157,10 +157,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Api* other); @@ -309,14 +309,17 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr version_; - ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; - int syntax_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::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_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr version_; + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; + int syntax_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // ------------------------------------------------------------------- @@ -412,10 +415,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Method* other); @@ -542,14 +545,17 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr response_type_url_; - bool request_streaming_; - bool response_streaming_; - int syntax_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr request_type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr response_type_url_; + bool request_streaming_; + bool response_streaming_; + int syntax_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // ------------------------------------------------------------------- @@ -645,10 +651,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Mixin* other); @@ -711,9 +717,12 @@ 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_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr root_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fapi_2eproto; }; // =================================================================== @@ -729,7 +738,7 @@ // string name = 1; inline void Api::clear_name() { - name_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); } inline const std::string& Api::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.name) @@ -739,7 +748,7 @@ inline PROTOBUF_ALWAYS_INLINE void Api::set_name(ArgT0&& arg0, ArgT... args) { - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Api.name) } inline std::string* Api::mutable_name() { @@ -748,19 +757,19 @@ return _s; } inline const std::string& Api::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void Api::_internal_set_name(const std::string& value) { - name_.Set(value, GetArenaForAllocation()); + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* Api::_internal_mutable_name() { - return name_.Mutable(GetArenaForAllocation()); + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* Api::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Api.name) - return name_.Release(); + return _impl_.name_.Release(); } inline void Api::set_allocated_name(std::string* name) { if (name != nullptr) { @@ -768,10 +777,10 @@ } else { } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.name) @@ -779,32 +788,32 @@ // repeated .google.protobuf.Method methods = 2; inline int Api::_internal_methods_size() const { - return methods_.size(); + return _impl_.methods_.size(); } inline int Api::methods_size() const { return _internal_methods_size(); } inline void Api::clear_methods() { - methods_.Clear(); + _impl_.methods_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::Method* Api::mutable_methods(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.methods) - return methods_.Mutable(index); + return _impl_.methods_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Method >* Api::mutable_methods() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.methods) - return &methods_; + return &_impl_.methods_; } inline const ::PROTOBUF_NAMESPACE_ID::Method& Api::_internal_methods(int index) const { - return methods_.Get(index); + return _impl_.methods_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Method& Api::methods(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Api.methods) return _internal_methods(index); } inline ::PROTOBUF_NAMESPACE_ID::Method* Api::_internal_add_methods() { - return methods_.Add(); + return _impl_.methods_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Method* Api::add_methods() { ::PROTOBUF_NAMESPACE_ID::Method* _add = _internal_add_methods(); @@ -814,34 +823,34 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Method >& Api::methods() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.methods) - return methods_; + return _impl_.methods_; } // repeated .google.protobuf.Option options = 3; inline int Api::_internal_options_size() const { - return options_.size(); + return _impl_.options_.size(); } inline int Api::options_size() const { return _internal_options_size(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Api::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.options) - return options_.Mutable(index); + return _impl_.options_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* Api::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.options) - return &options_; + return &_impl_.options_; } inline const ::PROTOBUF_NAMESPACE_ID::Option& Api::_internal_options(int index) const { - return options_.Get(index); + return _impl_.options_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Option& Api::options(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Api.options) return _internal_options(index); } inline ::PROTOBUF_NAMESPACE_ID::Option* Api::_internal_add_options() { - return options_.Add(); + return _impl_.options_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Api::add_options() { ::PROTOBUF_NAMESPACE_ID::Option* _add = _internal_add_options(); @@ -851,12 +860,12 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& Api::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.options) - return options_; + return _impl_.options_; } // string version = 4; inline void Api::clear_version() { - version_.ClearToEmpty(); + _impl_.version_.ClearToEmpty(); } inline const std::string& Api::version() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.version) @@ -866,7 +875,7 @@ inline PROTOBUF_ALWAYS_INLINE void Api::set_version(ArgT0&& arg0, ArgT... args) { - version_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.version_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Api.version) } inline std::string* Api::mutable_version() { @@ -875,19 +884,19 @@ return _s; } inline const std::string& Api::_internal_version() const { - return version_.Get(); + return _impl_.version_.Get(); } inline void Api::_internal_set_version(const std::string& value) { - version_.Set(value, GetArenaForAllocation()); + _impl_.version_.Set(value, GetArenaForAllocation()); } inline std::string* Api::_internal_mutable_version() { - return version_.Mutable(GetArenaForAllocation()); + return _impl_.version_.Mutable(GetArenaForAllocation()); } inline std::string* Api::release_version() { // @@protoc_insertion_point(field_release:google.protobuf.Api.version) - return version_.Release(); + return _impl_.version_.Release(); } inline void Api::set_allocated_version(std::string* version) { if (version != nullptr) { @@ -895,10 +904,10 @@ } else { } - version_.SetAllocated(version, GetArenaForAllocation()); + _impl_.version_.SetAllocated(version, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (version_.IsDefault()) { - version_.Set("", GetArenaForAllocation()); + if (_impl_.version_.IsDefault()) { + _impl_.version_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.version) @@ -906,13 +915,13 @@ // .google.protobuf.SourceContext source_context = 5; inline bool Api::_internal_has_source_context() const { - return this != internal_default_instance() && source_context_ != nullptr; + return this != internal_default_instance() && _impl_.source_context_ != nullptr; } inline bool Api::has_source_context() const { return _internal_has_source_context(); } inline const ::PROTOBUF_NAMESPACE_ID::SourceContext& Api::_internal_source_context() const { - const ::PROTOBUF_NAMESPACE_ID::SourceContext* p = source_context_; + const ::PROTOBUF_NAMESPACE_ID::SourceContext* p = _impl_.source_context_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::SourceContext&>( ::PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_); } @@ -923,9 +932,9 @@ inline void Api::unsafe_arena_set_allocated_source_context( ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_context_); } - source_context_ = source_context; + _impl_.source_context_ = source_context; if (source_context) { } else { @@ -935,8 +944,8 @@ } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Api::release_source_context() { - ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_; - source_context_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = _impl_.source_context_; + _impl_.source_context_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -951,17 +960,17 @@ 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_; - source_context_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = _impl_.source_context_; + _impl_.source_context_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Api::_internal_mutable_source_context() { - if (source_context_ == nullptr) { + if (_impl_.source_context_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::SourceContext>(GetArenaForAllocation()); - source_context_ = p; + _impl_.source_context_ = p; } - return source_context_; + return _impl_.source_context_; } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Api::mutable_source_context() { ::PROTOBUF_NAMESPACE_ID::SourceContext* _msg = _internal_mutable_source_context(); @@ -971,7 +980,7 @@ inline void Api::set_allocated_source_context(::PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_context_); } if (source_context) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -985,38 +994,38 @@ } else { } - source_context_ = source_context; + _impl_.source_context_ = source_context; // @@protoc_insertion_point(field_set_allocated:google.protobuf.Api.source_context) } // repeated .google.protobuf.Mixin mixins = 6; inline int Api::_internal_mixins_size() const { - return mixins_.size(); + return _impl_.mixins_.size(); } inline int Api::mixins_size() const { return _internal_mixins_size(); } inline void Api::clear_mixins() { - mixins_.Clear(); + _impl_.mixins_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::Mixin* Api::mutable_mixins(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Api.mixins) - return mixins_.Mutable(index); + return _impl_.mixins_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Mixin >* Api::mutable_mixins() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Api.mixins) - return &mixins_; + return &_impl_.mixins_; } inline const ::PROTOBUF_NAMESPACE_ID::Mixin& Api::_internal_mixins(int index) const { - return mixins_.Get(index); + return _impl_.mixins_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Mixin& Api::mixins(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Api.mixins) return _internal_mixins(index); } inline ::PROTOBUF_NAMESPACE_ID::Mixin* Api::_internal_add_mixins() { - return mixins_.Add(); + return _impl_.mixins_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Mixin* Api::add_mixins() { ::PROTOBUF_NAMESPACE_ID::Mixin* _add = _internal_add_mixins(); @@ -1026,15 +1035,15 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Mixin >& Api::mixins() const { // @@protoc_insertion_point(field_list:google.protobuf.Api.mixins) - return mixins_; + return _impl_.mixins_; } // .google.protobuf.Syntax syntax = 7; inline void Api::clear_syntax() { - syntax_ = 0; + _impl_.syntax_ = 0; } inline ::PROTOBUF_NAMESPACE_ID::Syntax Api::_internal_syntax() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(syntax_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(_impl_.syntax_); } inline ::PROTOBUF_NAMESPACE_ID::Syntax Api::syntax() const { // @@protoc_insertion_point(field_get:google.protobuf.Api.syntax) @@ -1042,7 +1051,7 @@ } inline void Api::_internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { - syntax_ = value; + _impl_.syntax_ = value; } inline void Api::set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { _internal_set_syntax(value); @@ -1055,7 +1064,7 @@ // string name = 1; inline void Method::clear_name() { - name_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); } inline const std::string& Method::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.name) @@ -1065,7 +1074,7 @@ inline PROTOBUF_ALWAYS_INLINE void Method::set_name(ArgT0&& arg0, ArgT... args) { - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Method.name) } inline std::string* Method::mutable_name() { @@ -1074,19 +1083,19 @@ return _s; } inline const std::string& Method::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void Method::_internal_set_name(const std::string& value) { - name_.Set(value, GetArenaForAllocation()); + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* Method::_internal_mutable_name() { - return name_.Mutable(GetArenaForAllocation()); + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* Method::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Method.name) - return name_.Release(); + return _impl_.name_.Release(); } inline void Method::set_allocated_name(std::string* name) { if (name != nullptr) { @@ -1094,10 +1103,10 @@ } else { } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.name) @@ -1105,7 +1114,7 @@ // string request_type_url = 2; inline void Method::clear_request_type_url() { - request_type_url_.ClearToEmpty(); + _impl_.request_type_url_.ClearToEmpty(); } inline const std::string& Method::request_type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.request_type_url) @@ -1115,7 +1124,7 @@ inline PROTOBUF_ALWAYS_INLINE void Method::set_request_type_url(ArgT0&& arg0, ArgT... args) { - request_type_url_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.request_type_url_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Method.request_type_url) } inline std::string* Method::mutable_request_type_url() { @@ -1124,19 +1133,19 @@ return _s; } inline const std::string& Method::_internal_request_type_url() const { - return request_type_url_.Get(); + return _impl_.request_type_url_.Get(); } inline void Method::_internal_set_request_type_url(const std::string& value) { - request_type_url_.Set(value, GetArenaForAllocation()); + _impl_.request_type_url_.Set(value, GetArenaForAllocation()); } inline std::string* Method::_internal_mutable_request_type_url() { - return request_type_url_.Mutable(GetArenaForAllocation()); + return _impl_.request_type_url_.Mutable(GetArenaForAllocation()); } inline std::string* Method::release_request_type_url() { // @@protoc_insertion_point(field_release:google.protobuf.Method.request_type_url) - return request_type_url_.Release(); + return _impl_.request_type_url_.Release(); } inline void Method::set_allocated_request_type_url(std::string* request_type_url) { if (request_type_url != nullptr) { @@ -1144,10 +1153,10 @@ } else { } - request_type_url_.SetAllocated(request_type_url, GetArenaForAllocation()); + _impl_.request_type_url_.SetAllocated(request_type_url, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (request_type_url_.IsDefault()) { - request_type_url_.Set("", GetArenaForAllocation()); + if (_impl_.request_type_url_.IsDefault()) { + _impl_.request_type_url_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.request_type_url) @@ -1155,10 +1164,10 @@ // bool request_streaming = 3; inline void Method::clear_request_streaming() { - request_streaming_ = false; + _impl_.request_streaming_ = false; } inline bool Method::_internal_request_streaming() const { - return request_streaming_; + return _impl_.request_streaming_; } inline bool Method::request_streaming() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.request_streaming) @@ -1166,7 +1175,7 @@ } inline void Method::_internal_set_request_streaming(bool value) { - request_streaming_ = value; + _impl_.request_streaming_ = value; } inline void Method::set_request_streaming(bool value) { _internal_set_request_streaming(value); @@ -1175,7 +1184,7 @@ // string response_type_url = 4; inline void Method::clear_response_type_url() { - response_type_url_.ClearToEmpty(); + _impl_.response_type_url_.ClearToEmpty(); } inline const std::string& Method::response_type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.response_type_url) @@ -1185,7 +1194,7 @@ inline PROTOBUF_ALWAYS_INLINE void Method::set_response_type_url(ArgT0&& arg0, ArgT... args) { - response_type_url_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.response_type_url_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Method.response_type_url) } inline std::string* Method::mutable_response_type_url() { @@ -1194,19 +1203,19 @@ return _s; } inline const std::string& Method::_internal_response_type_url() const { - return response_type_url_.Get(); + return _impl_.response_type_url_.Get(); } inline void Method::_internal_set_response_type_url(const std::string& value) { - response_type_url_.Set(value, GetArenaForAllocation()); + _impl_.response_type_url_.Set(value, GetArenaForAllocation()); } inline std::string* Method::_internal_mutable_response_type_url() { - return response_type_url_.Mutable(GetArenaForAllocation()); + return _impl_.response_type_url_.Mutable(GetArenaForAllocation()); } inline std::string* Method::release_response_type_url() { // @@protoc_insertion_point(field_release:google.protobuf.Method.response_type_url) - return response_type_url_.Release(); + return _impl_.response_type_url_.Release(); } inline void Method::set_allocated_response_type_url(std::string* response_type_url) { if (response_type_url != nullptr) { @@ -1214,10 +1223,10 @@ } else { } - response_type_url_.SetAllocated(response_type_url, GetArenaForAllocation()); + _impl_.response_type_url_.SetAllocated(response_type_url, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (response_type_url_.IsDefault()) { - response_type_url_.Set("", GetArenaForAllocation()); + if (_impl_.response_type_url_.IsDefault()) { + _impl_.response_type_url_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Method.response_type_url) @@ -1225,10 +1234,10 @@ // bool response_streaming = 5; inline void Method::clear_response_streaming() { - response_streaming_ = false; + _impl_.response_streaming_ = false; } inline bool Method::_internal_response_streaming() const { - return response_streaming_; + return _impl_.response_streaming_; } inline bool Method::response_streaming() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.response_streaming) @@ -1236,7 +1245,7 @@ } inline void Method::_internal_set_response_streaming(bool value) { - response_streaming_ = value; + _impl_.response_streaming_ = value; } inline void Method::set_response_streaming(bool value) { _internal_set_response_streaming(value); @@ -1245,29 +1254,29 @@ // repeated .google.protobuf.Option options = 6; inline int Method::_internal_options_size() const { - return options_.size(); + return _impl_.options_.size(); } inline int Method::options_size() const { return _internal_options_size(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Method::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Method.options) - return options_.Mutable(index); + return _impl_.options_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* Method::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Method.options) - return &options_; + return &_impl_.options_; } inline const ::PROTOBUF_NAMESPACE_ID::Option& Method::_internal_options(int index) const { - return options_.Get(index); + return _impl_.options_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Option& Method::options(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Method.options) return _internal_options(index); } inline ::PROTOBUF_NAMESPACE_ID::Option* Method::_internal_add_options() { - return options_.Add(); + return _impl_.options_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Method::add_options() { ::PROTOBUF_NAMESPACE_ID::Option* _add = _internal_add_options(); @@ -1277,15 +1286,15 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& Method::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Method.options) - return options_; + return _impl_.options_; } // .google.protobuf.Syntax syntax = 7; inline void Method::clear_syntax() { - syntax_ = 0; + _impl_.syntax_ = 0; } inline ::PROTOBUF_NAMESPACE_ID::Syntax Method::_internal_syntax() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(syntax_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(_impl_.syntax_); } inline ::PROTOBUF_NAMESPACE_ID::Syntax Method::syntax() const { // @@protoc_insertion_point(field_get:google.protobuf.Method.syntax) @@ -1293,7 +1302,7 @@ } inline void Method::_internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { - syntax_ = value; + _impl_.syntax_ = value; } inline void Method::set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { _internal_set_syntax(value); @@ -1306,7 +1315,7 @@ // string name = 1; inline void Mixin::clear_name() { - name_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); } inline const std::string& Mixin::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Mixin.name) @@ -1316,7 +1325,7 @@ inline PROTOBUF_ALWAYS_INLINE void Mixin::set_name(ArgT0&& arg0, ArgT... args) { - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Mixin.name) } inline std::string* Mixin::mutable_name() { @@ -1325,19 +1334,19 @@ return _s; } inline const std::string& Mixin::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void Mixin::_internal_set_name(const std::string& value) { - name_.Set(value, GetArenaForAllocation()); + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* Mixin::_internal_mutable_name() { - return name_.Mutable(GetArenaForAllocation()); + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* Mixin::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Mixin.name) - return name_.Release(); + return _impl_.name_.Release(); } inline void Mixin::set_allocated_name(std::string* name) { if (name != nullptr) { @@ -1345,10 +1354,10 @@ } else { } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.name) @@ -1356,7 +1365,7 @@ // string root = 2; inline void Mixin::clear_root() { - root_.ClearToEmpty(); + _impl_.root_.ClearToEmpty(); } inline const std::string& Mixin::root() const { // @@protoc_insertion_point(field_get:google.protobuf.Mixin.root) @@ -1366,7 +1375,7 @@ inline PROTOBUF_ALWAYS_INLINE void Mixin::set_root(ArgT0&& arg0, ArgT... args) { - root_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.root_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Mixin.root) } inline std::string* Mixin::mutable_root() { @@ -1375,19 +1384,19 @@ return _s; } inline const std::string& Mixin::_internal_root() const { - return root_.Get(); + return _impl_.root_.Get(); } inline void Mixin::_internal_set_root(const std::string& value) { - root_.Set(value, GetArenaForAllocation()); + _impl_.root_.Set(value, GetArenaForAllocation()); } inline std::string* Mixin::_internal_mutable_root() { - return root_.Mutable(GetArenaForAllocation()); + return _impl_.root_.Mutable(GetArenaForAllocation()); } inline std::string* Mixin::release_root() { // @@protoc_insertion_point(field_release:google.protobuf.Mixin.root) - return root_.Release(); + return _impl_.root_.Release(); } inline void Mixin::set_allocated_root(std::string* root) { if (root != nullptr) { @@ -1395,10 +1404,10 @@ } else { } - root_.SetAllocated(root, GetArenaForAllocation()); + _impl_.root_.SetAllocated(root, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (root_.IsDefault()) { - root_.Set("", GetArenaForAllocation()); + if (_impl_.root_.IsDefault()) { + _impl_.root_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Mixin.root)
diff --git a/src/google/protobuf/arena_test_util.cc b/src/google/protobuf/arena_test_util.cc index da32960..2cb5075 100644 --- a/src/google/protobuf/arena_test_util.cc +++ b/src/google/protobuf/arena_test_util.cc
@@ -29,6 +29,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <google/protobuf/arena_test_util.h> + #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h>
diff --git a/src/google/protobuf/arena_test_util.h b/src/google/protobuf/arena_test_util.h index 7286769..6e42d4b 100644 --- a/src/google/protobuf/arena_test_util.h +++ b/src/google/protobuf/arena_test_util.h
@@ -33,9 +33,9 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> +#include <google/protobuf/arena.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> -#include <google/protobuf/arena.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/arena_unittest.cc b/src/google/protobuf/arena_unittest.cc index e80e0e8..7539b4b 100644 --- a/src/google/protobuf/arena_unittest.cc +++ b/src/google/protobuf/arena_unittest.cc
@@ -41,20 +41,20 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/arena_test_util.h> -#include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_arena.pb.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/arena_test_util.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/extension_set.h> +#include <google/protobuf/io/coded_stream.h> +#include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <google/protobuf/message.h> #include <google/protobuf/message_lite.h> #include <google/protobuf/repeated_field.h> +#include <google/protobuf/test_util.h> #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/wire_format_lite.h>
diff --git a/src/google/protobuf/arenaz_sampler.cc b/src/google/protobuf/arenaz_sampler.cc index b0aed50..0eac693 100644 --- a/src/google/protobuf/arenaz_sampler.cc +++ b/src/google/protobuf/arenaz_sampler.cc
@@ -55,13 +55,13 @@ namespace { PROTOBUF_CONSTINIT std::atomic<bool> g_arenaz_enabled{true}; -PROTOBUF_CONSTINIT std::atomic<int32_t> g_arenaz_sample_parameter{1 << 20}; +PROTOBUF_CONSTINIT std::atomic<int32_t> g_arenaz_sample_parameter{1 << 10}; PROTOBUF_THREAD_LOCAL absl::profiling_internal::ExponentialBiased g_exponential_biased_generator; } // namespace -PROTOBUF_THREAD_LOCAL int64_t global_next_sample = 1LL << 20; +PROTOBUF_THREAD_LOCAL int64_t global_next_sample = 1LL << 10; ThreadSafeArenaStats::ThreadSafeArenaStats() { PrepareForSampling(); } ThreadSafeArenaStats::~ThreadSafeArenaStats() = default;
diff --git a/src/google/protobuf/compiler/annotation_test_util.h b/src/google/protobuf/compiler/annotation_test_util.h index 551f224..b7c6ddd 100644 --- a/src/google/protobuf/compiler/annotation_test_util.h +++ b/src/google/protobuf/compiler/annotation_test_util.h
@@ -78,7 +78,7 @@ bool DecodeMetadata(const std::string& path, GeneratedCodeInfo* info); // Finds all of the Annotations for a given source file and path. -// See Location.path in https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/descriptor.proto for +// See Location.path in https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto for // explanation of what path vector is. void FindAnnotationsOnPath( const GeneratedCodeInfo& info, const std::string& source_file, @@ -88,7 +88,7 @@ // Finds the Annotation for a given source file and path (or returns null if it // couldn't). If there are several annotations for given path, returns the first // one. See Location.path in -// https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/descriptor.proto for explanation of what path +// https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto for explanation of what path // vector is. const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( const GeneratedCodeInfo& info, const std::string& source_file,
diff --git a/src/google/protobuf/compiler/code_generator.h b/src/google/protobuf/compiler/code_generator.h index 0a99fe1..9c0b115 100644 --- a/src/google/protobuf/compiler/code_generator.h +++ b/src/google/protobuf/compiler/code_generator.h
@@ -189,9 +189,9 @@ // Several code generators treat the parameter argument as holding a // list of options separated by commas. This helper function parses // a set of comma-delimited name/value pairs: e.g., -// "foo=bar,baz,qux=corge" +// "foo=bar,baz,moo=corge" // parses to the pairs: -// ("foo", "bar"), ("baz", ""), ("qux", "corge") +// ("foo", "bar"), ("baz", ""), ("moo", "corge") PROTOC_EXPORT void ParseGeneratorParameter( const std::string&, std::vector<std::pair<std::string, std::string> >*);
diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc index 52e8347..5e9a2c4 100644 --- a/src/google/protobuf/compiler/command_line_interface.cc +++ b/src/google/protobuf/compiler/command_line_interface.cc
@@ -34,8 +34,6 @@ #include <google/protobuf/compiler/command_line_interface.h> -#include <cstdint> - #include <google/protobuf/stubs/platform_macros.h> #include <stdio.h> @@ -70,20 +68,20 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/compiler/subprocess.h> -#include <google/protobuf/compiler/zip_writer.h> #include <google/protobuf/compiler/plugin.pb.h> -#include <google/protobuf/compiler/code_generator.h> -#include <google/protobuf/compiler/importer.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/dynamic_message.h> -#include <google/protobuf/text_format.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/stringprintf.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/compiler/code_generator.h> +#include <google/protobuf/compiler/importer.h> +#include <google/protobuf/compiler/zip_writer.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/dynamic_message.h> +#include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/io_win32.h> +#include <google/protobuf/io/printer.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/text_format.h> #include <google/protobuf/stubs/map_util.h> #include <google/protobuf/stubs/stl_util.h> @@ -2211,6 +2209,10 @@ } } + if (!descriptor_set_out_name_.empty()) { + output_filenames.push_back(descriptor_set_out_name_); + } + int fd; do { fd = open(dependency_out_name_.c_str(),
diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc index efdd594..f48135e 100644 --- a/src/google/protobuf/compiler/command_line_interface_unittest.cc +++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc
@@ -50,24 +50,27 @@ #include <google/protobuf/testing/file.h> #include <google/protobuf/testing/file.h> #include <google/protobuf/any.pb.h> -#include <google/protobuf/compiler/mock_code_generator.h> -#include <google/protobuf/compiler/subprocess.h> -#include <google/protobuf/compiler/code_generator.h> -#include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/test_util2.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_custom_options.pb.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/descriptor.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/compiler/code_generator.h> +#include <google/protobuf/compiler/command_line_interface.h> +#include <google/protobuf/compiler/mock_code_generator.h> +#include <google/protobuf/compiler/subprocess.h> +#include <google/protobuf/descriptor.h> #include <google/protobuf/io/io_win32.h> +#include <google/protobuf/io/printer.h> +#include <google/protobuf/io/zero_copy_stream.h> +// Must be included last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace compiler { @@ -1753,6 +1756,28 @@ "$tmpdir/bar.proto.MockCodeGenerator.test_generator: " "$tmpdir/foo.proto\\\n $tmpdir/bar.proto"); } + +TEST_F(CommandLineInterfaceTest, + WriteDependencyManifestFileWithDescriptorSetOut) { + CreateTempFile("foo.proto", + "syntax = \"proto2\";\n" + "message Foo {}\n"); + CreateTempFile("bar.proto", + "syntax = \"proto2\";\n" + "import \"foo.proto\";\n" + "message Bar {\n" + " optional Foo foo = 1;\n" + "}\n"); + + Run("protocol_compiler --dependency_out=$tmpdir/manifest " + "--descriptor_set_out=$tmpdir/bar.pb --proto_path=$tmpdir bar.proto"); + + ExpectNoErrors(); + + ExpectFileContent("manifest", + "$tmpdir/bar.pb: " + "$tmpdir/foo.proto\\\n $tmpdir/bar.proto"); +} #endif // !_WIN32 TEST_F(CommandLineInterfaceTest, TestArgumentFile) { @@ -2755,6 +2780,8 @@ #endif // !GOOGLE_PROTOBUF_HEAP_CHECK_DRACONIAN +#include <google/protobuf/port_undef.inc> + } // namespace compiler } // namespace protobuf } // namespace google
diff --git a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/bootstrap_unittest.cc similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc rename to src/google/protobuf/compiler/cpp/bootstrap_unittest.cc index 6ed3a07..2619e60 100644 --- a/src/google/protobuf/compiler/cpp/cpp_bootstrap_unittest.cc +++ b/src/google/protobuf/compiler/cpp/bootstrap_unittest.cc
@@ -46,8 +46,7 @@ #include <google/protobuf/testing/file.h> #include <google/protobuf/testing/file.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_generator.h> +#include <google/protobuf/compiler/cpp/generator.h> #include <google/protobuf/compiler/importer.h> #include <google/protobuf/test_util2.h> #include <google/protobuf/io/zero_copy_stream_impl.h> @@ -56,6 +55,7 @@ #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/compiler/cpp/helpers.h> #include <google/protobuf/stubs/map_util.h> #include <google/protobuf/stubs/stl_util.h>
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.cc b/src/google/protobuf/compiler/cpp/enum.cc similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_enum.cc rename to src/google/protobuf/compiler/cpp/enum.cc index fb72b75..8124369 100644 --- a/src/google/protobuf/compiler/cpp/cpp_enum.cc +++ b/src/google/protobuf/compiler/cpp/enum.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_enum.h> +#include <google/protobuf/compiler/cpp/enum.h> #include <cstdint> #include <limits> @@ -40,8 +40,8 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_names.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/names.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum.h b/src/google/protobuf/compiler/cpp/enum.h similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_enum.h rename to src/google/protobuf/compiler/cpp/enum.h index 2a17ede..610d4fc 100644 --- a/src/google/protobuf/compiler/cpp/cpp_enum.h +++ b/src/google/protobuf/compiler/cpp/enum.h
@@ -40,7 +40,7 @@ #include <string> #include <google/protobuf/descriptor.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc b/src/google/protobuf/compiler/cpp/enum_field.cc similarity index 89% rename from src/google/protobuf/compiler/cpp/cpp_enum_field.cc rename to src/google/protobuf/compiler/cpp/enum_field.cc index 0e83202..254ac3b 100644 --- a/src/google/protobuf/compiler/cpp/cpp_enum_field.cc +++ b/src/google/protobuf/compiler/cpp/enum_field.cc
@@ -32,12 +32,12 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_enum_field.h> +#include <google/protobuf/compiler/cpp/enum_field.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> namespace google { namespace protobuf { @@ -131,11 +131,6 @@ format("swap($field$, other->$field$);\n"); } -void EnumFieldGenerator::GenerateConstructorCode(io::Printer* printer) const { - Formatter format(printer, variables_); - format("$field$ = $default$;\n"); -} - void EnumFieldGenerator::GenerateCopyConstructorCode( io::Printer* printer) const { Formatter format(printer, variables_); @@ -158,10 +153,22 @@ " ::_pbi::WireFormatLite::EnumSize(this->_internal_$name$());\n"); } -void EnumFieldGenerator::GenerateConstinitInitializer( +void EnumFieldGenerator::GenerateConstexprAggregateInitializer( io::Printer* printer) const { Formatter format(printer, variables_); - format("$name$_($default$)\n"); + format("/*decltype($field$)*/$default$"); +} + +void EnumFieldGenerator::GenerateAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){$default$}"); +} + +void EnumFieldGenerator::GenerateCopyAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){}"); } // =================================================================== @@ -336,6 +343,12 @@ // Not needed for repeated fields. } +void RepeatedEnumFieldGenerator::GenerateDestructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$field$.~RepeatedField();\n"); +} + void RepeatedEnumFieldGenerator::GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const { Formatter format(printer, variables_); @@ -392,13 +405,36 @@ format("}\n"); } -void RepeatedEnumFieldGenerator::GenerateConstinitInitializer( +void RepeatedEnumFieldGenerator::GenerateConstexprAggregateInitializer( io::Printer* printer) const { Formatter format(printer, variables_); - format("$name$_()"); + format("/*decltype($field$)*/{}"); if (descriptor_->is_packed() && HasGeneratedMethods(descriptor_->file(), options_)) { - format("\n, $cached_byte_size_name$(0)"); + format("\n, /*decltype($cached_byte_size_field$)*/{0}"); + } +} + +void RepeatedEnumFieldGenerator::GenerateAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){arena}"); + if (descriptor_->is_packed() && + HasGeneratedMethods(descriptor_->file(), options_)) { + // std::atomic has no copy constructor, which prevents explicit aggregate + // initialization pre-C++17. + format("\n, /*decltype($cached_byte_size_field$)*/{0}"); + } +} + +void RepeatedEnumFieldGenerator::GenerateCopyAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){from.$field$}"); + if (descriptor_->is_packed() && + HasGeneratedMethods(descriptor_->file(), options_)) { + // std::atomic has no copy constructor. + format("\n, /*decltype($cached_byte_size_field$)*/{0}"); } }
diff --git a/src/google/protobuf/compiler/cpp/cpp_enum_field.h b/src/google/protobuf/compiler/cpp/enum_field.h similarity index 89% rename from src/google/protobuf/compiler/cpp/cpp_enum_field.h rename to src/google/protobuf/compiler/cpp/enum_field.h index 2a4ca51..44269a6 100644 --- a/src/google/protobuf/compiler/cpp/cpp_enum_field.h +++ b/src/google/protobuf/compiler/cpp/enum_field.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/cpp/cpp_field.h> +#include <google/protobuf/compiler/cpp/field.h> namespace google { namespace protobuf { @@ -57,12 +57,15 @@ void GenerateClearingCode(io::Printer* printer) const override; void GenerateMergingCode(io::Printer* printer) const override; void GenerateSwappingCode(io::Printer* printer) const override; - void GenerateConstructorCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override {} void GenerateCopyConstructorCode(io::Printer* printer) const override; void GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; + void GenerateConstexprAggregateInitializer( + io::Printer* printer) const override; + void GenerateAggregateInitializer(io::Printer* printer) const override; + void GenerateCopyAggregateInitializer(io::Printer* printer) const override; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); @@ -99,10 +102,14 @@ void GenerateSwappingCode(io::Printer* printer) const override; void GenerateConstructorCode(io::Printer* printer) const override; void GenerateCopyConstructorCode(io::Printer* printer) const override {} + void GenerateDestructorCode(io::Printer* printer) const override; void GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; + void GenerateConstexprAggregateInitializer( + io::Printer* printer) const override; + void GenerateAggregateInitializer(io::Printer* printer) const override; + void GenerateCopyAggregateInitializer(io::Printer* printer) const override; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator);
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.cc b/src/google/protobuf/compiler/cpp/extension.cc similarity index 97% rename from src/google/protobuf/compiler/cpp/cpp_extension.cc rename to src/google/protobuf/compiler/cpp/extension.cc index 90e292b..950ed9e 100644 --- a/src/google/protobuf/compiler/cpp/cpp_extension.cc +++ b/src/google/protobuf/compiler/cpp/extension.cc
@@ -32,13 +32,13 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_extension.h> +#include <google/protobuf/compiler/cpp/extension.h> #include <map> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> #include <google/protobuf/descriptor.pb.h> namespace google { @@ -78,7 +78,7 @@ break; } SetCommonVars(options, &variables_); - SetCommonMessageDataVariables(&variables_); + SetCommonMessageDataVariables(descriptor_->containing_type(), &variables_); variables_["extendee"] = QualifiedClassName(descriptor_->containing_type(), options_); variables_["type_traits"] = type_traits_;
diff --git a/src/google/protobuf/compiler/cpp/cpp_extension.h b/src/google/protobuf/compiler/cpp/extension.h similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_extension.h rename to src/google/protobuf/compiler/cpp/extension.h index bcc8018..282931f 100644 --- a/src/google/protobuf/compiler/cpp/cpp_extension.h +++ b/src/google/protobuf/compiler/cpp/extension.h
@@ -39,7 +39,7 @@ #include <string> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.cc b/src/google/protobuf/compiler/cpp/field.cc similarity index 94% rename from src/google/protobuf/compiler/cpp/cpp_field.cc rename to src/google/protobuf/compiler/cpp/field.cc index 49d6248..ba262c2 100644 --- a/src/google/protobuf/compiler/cpp/cpp_field.cc +++ b/src/google/protobuf/compiler/cpp/field.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_field.h> +#include <google/protobuf/compiler/cpp/field.h> #include <cstdint> #include <memory> @@ -40,16 +40,16 @@ #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_primitive_field.h> -#include <google/protobuf/compiler/cpp/cpp_string_field.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/primitive_field.h> +#include <google/protobuf/compiler/cpp/string_field.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> -#include <google/protobuf/compiler/cpp/cpp_enum_field.h> -#include <google/protobuf/compiler/cpp/cpp_map_field.h> -#include <google/protobuf/compiler/cpp/cpp_message_field.h> +#include <google/protobuf/compiler/cpp/enum_field.h> +#include <google/protobuf/compiler/cpp/map_field.h> +#include <google/protobuf/compiler/cpp/message_field.h> #include <google/protobuf/descriptor.pb.h> namespace google { @@ -236,7 +236,7 @@ std::map<std::string, std::string>* variables, const Options& options) { SetCommonVars(options, variables); - SetCommonMessageDataVariables(variables); + SetCommonMessageDataVariables(descriptor->containing_type(), variables); (*variables)["ns"] = Namespace(descriptor, options); (*variables)["name"] = FieldName(descriptor); @@ -304,6 +304,23 @@ "u"); } +void FieldGenerator::GenerateAggregateInitializer(io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){arena}"); +} + +void FieldGenerator::GenerateConstexprAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("/*decltype($field$)*/{}"); +} + +void FieldGenerator::GenerateCopyAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){from.$field$}"); +} + void SetCommonOneofFieldVariables( const FieldDescriptor* descriptor, std::map<std::string, std::string>* variables) {
diff --git a/src/google/protobuf/compiler/cpp/cpp_field.h b/src/google/protobuf/compiler/cpp/field.h similarity index 85% rename from src/google/protobuf/compiler/cpp/cpp_field.h rename to src/google/protobuf/compiler/cpp/field.h index 165b6fa..52098e7 100644 --- a/src/google/protobuf/compiler/cpp/cpp_field.h +++ b/src/google/protobuf/compiler/cpp/field.h
@@ -41,8 +41,8 @@ #include <string> #include <google/protobuf/descriptor.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/options.h> namespace google { namespace protobuf { @@ -165,10 +165,32 @@ } // Generate initialization code for private members declared by - // GeneratePrivateMembers(), specifically for the constexpr constructor. - // These go into the constructor's initializer list and must follow that - // syntax (eg `field_(args)`). Does not include `:` or `,` separators. - virtual void GenerateConstinitInitializer(io::Printer* printer) const {} + // GeneratePrivateMembers(). These go into the SharedCtor's + // aggregate initialization of the _impl_ struct and must follow the syntax + // (e.g. `decltype($field$){$default$}`). Does not include `:` or `,` + // separators. Default values should be specified here when possible. + // + // Note: We use `decltype($field$)` for both explicit construction and the + // fact that it's self-documenting. Pre-C++17, copy elision isn't guaranteed + // in aggregate initialization so a valid copy/move constructor must exist + // (even though it's not used). Because of this, we need to comment out the + // decltype and fallback to implicit construction. + virtual void GenerateAggregateInitializer(io::Printer* printer) const; + + // Generate constinit initialization code for private members declared by + // GeneratePrivateMembers(). These go into the constexpr constructor's + // aggregate initialization of the _impl_ struct and must follow the syntax + // (e.g. `/*decltype($field$)*/{}`, see above). Does not + // include `:` or `,` separators. + virtual void GenerateConstexprAggregateInitializer( + io::Printer* printer) const; + + // Generate copy initialization code for private members declared by + // GeneratePrivateMembers(). These go into the copy constructor's + // aggregate initialization of the _impl_ struct and must follow the syntax + // (e.g. `decltype($field$){from.$field$}`, see above). Does not + // include `:` or `,` separators. + virtual void GenerateCopyAggregateInitializer(io::Printer* printer) const; // Generate lines to serialize this field directly to the array "target", // which are placed within the message's SerializeWithCachedSizesToArray()
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.cc b/src/google/protobuf/compiler/cpp/file.cc similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_file.cc rename to src/google/protobuf/compiler/cpp/file.cc index 24f2ccb..d409661 100644 --- a/src/google/protobuf/compiler/cpp/cpp_file.cc +++ b/src/google/protobuf/compiler/cpp/file.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_file.h> +#include <google/protobuf/compiler/cpp/file.h> #include <iostream> #include <map> @@ -45,12 +45,12 @@ #include <google/protobuf/compiler/scc.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/cpp/cpp_enum.h> -#include <google/protobuf/compiler/cpp/cpp_extension.h> -#include <google/protobuf/compiler/cpp/cpp_field.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_message.h> -#include <google/protobuf/compiler/cpp/cpp_service.h> +#include <google/protobuf/compiler/cpp/enum.h> +#include <google/protobuf/compiler/cpp/extension.h> +#include <google/protobuf/compiler/cpp/field.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/message.h> +#include <google/protobuf/compiler/cpp/service.h> #include <google/protobuf/descriptor.pb.h> // Must be last. @@ -510,7 +510,7 @@ // Force the initialization of the inlined string in the default instance. format( "PROTOBUF_ATTRIBUTE_INIT_PRIORITY2 std::true_type " - "$1$::_init_inline_$2$_ = " + "$1$::Impl_::_init_inline_$2$_ = " "($3$._instance.$4$.Init(), std::true_type{});\n", ClassName(generator->descriptor_), FieldName(field), DefaultInstanceName(generator->descriptor_, options_),
diff --git a/src/google/protobuf/compiler/cpp/cpp_file.h b/src/google/protobuf/compiler/cpp/file.h similarity index 97% rename from src/google/protobuf/compiler/cpp/cpp_file.h rename to src/google/protobuf/compiler/cpp/file.h index b69202f..ca05361 100644 --- a/src/google/protobuf/compiler/cpp/cpp_file.h +++ b/src/google/protobuf/compiler/cpp/file.h
@@ -42,10 +42,10 @@ #include <vector> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/cpp/cpp_field.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/field.h> +#include <google/protobuf/compiler/cpp/helpers.h> #include <google/protobuf/compiler/scc.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.cc b/src/google/protobuf/compiler/cpp/generator.cc similarity index 96% rename from src/google/protobuf/compiler/cpp/cpp_generator.cc rename to src/google/protobuf/compiler/cpp/generator.cc index 824edc1..63a2bce 100644 --- a/src/google/protobuf/compiler/cpp/cpp_generator.cc +++ b/src/google/protobuf/compiler/cpp/generator.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_generator.h> +#include <google/protobuf/compiler/cpp/generator.h> #include <memory> #include <string> @@ -42,8 +42,8 @@ #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/compiler/cpp/cpp_file.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/file.h> +#include <google/protobuf/compiler/cpp/helpers.h> #include <google/protobuf/descriptor.pb.h> namespace google { @@ -135,12 +135,12 @@ .insert(options[i].second.substr(pos, next_pos - pos)); pos = next_pos + 1; } while (pos < options[i].second.size()); - } else if (options[i].first == "verified_lazy_message_sets") { - file_options.unverified_lazy_message_sets = false; + } else if (options[i].first == "verified_lazy") { + file_options.unverified_lazy = false; } else if (options[i].first == "unverified_lazy_message_sets") { file_options.unverified_lazy_message_sets = true; - } else if (options[i].first == "eagerly_verified_lazy") { - file_options.eagerly_verified_lazy = true; + } else if (options[i].first == "message_owned_arena_trial") { + file_options.message_owned_arena_trial = true; } else if (options[i].first == "force_eagerly_verified_lazy") { file_options.force_eagerly_verified_lazy = true; } else if (options[i].first == "experimental_tail_call_table_mode") {
diff --git a/src/google/protobuf/compiler/cpp/cpp_generator.h b/src/google/protobuf/compiler/cpp/generator.h similarity index 100% rename from src/google/protobuf/compiler/cpp/cpp_generator.h rename to src/google/protobuf/compiler/cpp/generator.h
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.cc b/src/google/protobuf/compiler/cpp/helpers.cc similarity index 94% rename from src/google/protobuf/compiler/cpp/cpp_helpers.cc rename to src/google/protobuf/compiler/cpp/helpers.cc index 9545ff0..0c37858 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.cc +++ b/src/google/protobuf/compiler/cpp/helpers.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> #include <cstdint> #include <functional> @@ -45,8 +45,8 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/descriptor.h> -#include <google/protobuf/compiler/cpp/cpp_names.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/names.h> +#include <google/protobuf/compiler/cpp/options.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/compiler/scc.h> #include <google/protobuf/io/printer.h> @@ -178,9 +178,10 @@ std::map<std::string, std::string>* variables) { (*variables)[type] = IntTypeName(options, type); } -bool IsEagerlyVerifiedLazyImpl(const FieldDescriptor* field, - const Options& options, - MessageSCCAnalyzer* scc_analyzer) { + +// Returns true if the message can potentially allocate memory for its field. +// This is used to determine if message-owned arena will be useful. +bool AllocExpected(const Descriptor* descriptor) { return false; } @@ -189,7 +190,25 @@ bool IsLazy(const FieldDescriptor* field, const Options& options, MessageSCCAnalyzer* scc_analyzer) { return IsLazilyVerifiedLazy(field, options) || - IsEagerlyVerifiedLazyImpl(field, options, scc_analyzer); + IsEagerlyVerifiedLazy(field, options, scc_analyzer); +} + +// Returns true if "field" is a message field that is backed by LazyField per +// profile (go/pdlazy). +inline bool IsEagerlyVerifiedLazyByProfile(const FieldDescriptor* field, + const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + return false; +} + +bool IsEagerlyVerifiedLazy(const FieldDescriptor* field, const Options& options, + MessageSCCAnalyzer* scc_analyzer) { + return false; +} + +bool IsLazilyVerifiedLazy(const FieldDescriptor* field, + const Options& options) { + return false; } void SetCommonVars(const Options& options, @@ -230,15 +249,18 @@ } void SetCommonMessageDataVariables( + const Descriptor* descriptor, std::map<std::string, std::string>* variables) { - (*variables)["any_metadata"] = "_any_metadata_"; - (*variables)["cached_size"] = "_cached_size_"; - (*variables)["extensions"] = "_extensions_"; - (*variables)["has_bits"] = "_has_bits_"; - (*variables)["inlined_string_donated_array"] = "_inlined_string_donated_"; - (*variables)["oneof_case"] = "_oneof_case_"; - (*variables)["tracker"] = "_tracker_"; - (*variables)["weak_field_map"] = "_weak_field_map_"; + std::string prefix = IsMapEntryMessage(descriptor) ? "" : "_impl_."; + (*variables)["any_metadata"] = prefix + "_any_metadata_"; + (*variables)["cached_size"] = prefix + "_cached_size_"; + (*variables)["extensions"] = prefix + "_extensions_"; + (*variables)["has_bits"] = prefix + "_has_bits_"; + (*variables)["inlined_string_donated_array"] = + prefix + "_inlined_string_donated_"; + (*variables)["oneof_case"] = prefix + "_oneof_case_"; + (*variables)["tracker"] = "Impl_::_tracker_"; + (*variables)["weak_field_map"] = prefix + "_weak_field_map_"; } void SetUnknownFieldsVariable(const Descriptor* descriptor, @@ -466,11 +488,13 @@ } std::string FieldMemberName(const FieldDescriptor* field) { + StringPiece prefix = + IsMapEntryMessage(field->containing_type()) ? "" : "_impl_."; if (field->real_containing_oneof() == nullptr) { - return StrCat(FieldName(field), "_"); + return StrCat(prefix, FieldName(field), "_"); } - return StrCat(field->containing_oneof()->name(), "_.", FieldName(field), - "_"); + return StrCat(prefix, field->containing_oneof()->name(), "_.", + FieldName(field), "_"); } std::string OneofCaseConstantName(const FieldDescriptor* field) { @@ -987,6 +1011,16 @@ return false; } +bool IsUtf8String(const FieldDescriptor* field) { + return IsProto3(field->file()) && + field->type() == FieldDescriptor::TYPE_STRING; +} + +bool ShouldVerifySimple(const Descriptor* descriptor) { + (void)descriptor; + return false; +} + bool IsStringOrMessage(const FieldDescriptor* field) { switch (field->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: @@ -1505,12 +1539,32 @@ return FileOptions::SPEED; } +inline bool IsMessageOwnedArenaEligible(const Descriptor* desc, + const Options& options) { + return GetOptimizeFor(desc->file(), options) != FileOptions::LITE_RUNTIME && + !options.bootstrap && !options.opensource_runtime && + AllocExpected(desc); +} + bool EnableMessageOwnedArena(const Descriptor* desc, const Options& options) { (void)desc; (void)options; return false; } +bool EnableMessageOwnedArenaTrial(const Descriptor* desc, + const Options& options) { + return false; +} + +bool HasMessageFieldOrExtension(const Descriptor* desc) { + if (desc->extension_range_count() > 0) return true; + for (const auto* f : FieldRange(desc)) { + if (f->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) return true; + } + return false; +} + } // namespace cpp } // namespace compiler } // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_helpers.h b/src/google/protobuf/compiler/cpp/helpers.h similarity index 96% rename from src/google/protobuf/compiler/cpp/cpp_helpers.h rename to src/google/protobuf/compiler/cpp/helpers.h index d848831..bab2501 100644 --- a/src/google/protobuf/compiler/cpp/cpp_helpers.h +++ b/src/google/protobuf/compiler/cpp/helpers.h
@@ -43,8 +43,8 @@ #include <google/protobuf/compiler/scc.h> #include <google/protobuf/compiler/code_generator.h> -#include <google/protobuf/compiler/cpp/cpp_names.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/names.h> +#include <google/protobuf/compiler/cpp/options.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.h> @@ -89,6 +89,7 @@ // Variables to access message data from the message scope. void SetCommonMessageDataVariables( + const Descriptor* descriptor, std::map<std::string, std::string>* variables); void SetUnknownFieldsVariable(const Descriptor* descriptor, @@ -127,11 +128,11 @@ // Returns the non-nested type name for the given type. If "qualified" is // true, prefix the type with the full namespace. For example, if you had: // package foo.bar; -// message Baz { message Qux {} } -// Then the qualified ClassName for Qux would be: -// ::foo::bar::Baz_Qux +// message Baz { message Moo {} } +// Then the qualified ClassName for Moo would be: +// ::foo::bar::Baz_Moo // While the non-qualified version would be: -// Baz_Qux +// Baz_Moo inline std::string ClassName(const Descriptor* descriptor, bool qualified) { return qualified ? QualifiedClassName(descriptor, Options()) : ClassName(descriptor); @@ -363,21 +364,10 @@ return field->options().lazy() || field->options().unverified_lazy(); } -inline bool IsLazilyVerifiedLazy(const FieldDescriptor* field, - const Options& options) { - // TODO(b/211906113): Make lazy() imply eagerly verified lazy. - return IsExplicitLazy(field) && !field->is_repeated() && - field->type() == FieldDescriptor::TYPE_MESSAGE && - GetOptimizeFor(field->file(), options) != FileOptions::LITE_RUNTIME && - !options.opensource_runtime; -} +bool IsEagerlyVerifiedLazy(const FieldDescriptor* field, const Options& options, + MessageSCCAnalyzer* scc_analyzer); -inline bool IsEagerlyVerifiedLazy(const FieldDescriptor* field, - const Options& options, - MessageSCCAnalyzer* scc_analyzer) { - // TODO(b/211906113): Make lazy() imply eagerly verified lazy. - return IsLazy(field, options, scc_analyzer) && !IsExplicitLazy(field); -} +bool IsLazilyVerifiedLazy(const FieldDescriptor* field, const Options& options); inline bool IsFieldUsed(const FieldDescriptor* /* field */, const Options& /* options */) { @@ -485,8 +475,8 @@ } inline std::string MakeDefaultName(const FieldDescriptor* field) { - return "_i_give_permission_to_break_this_code_default_" + FieldName(field) + - "_"; + return StrCat("_i_give_permission_to_break_this_code_default_", + FieldName(field), "_"); } // Semantically distinct from MakeDefaultName in that it gives the C++ code @@ -500,7 +490,7 @@ // exists at some nested level like: // internal_container_._i_give_permission_to_break_this_code_default_field_; inline std::string MakeDefaultFieldName(const FieldDescriptor* field) { - return MakeDefaultName(field); + return StrCat("Impl_::", MakeDefaultName(field)); } inline std::string MakeVarintCachedSizeName(const FieldDescriptor* field) { @@ -519,7 +509,7 @@ // like: // internal_container_._field_cached_byte_size_; inline std::string MakeVarintCachedSizeFieldName(const FieldDescriptor* field) { - return StrCat("_", FieldName(field), "_cached_byte_size_"); + return StrCat("_impl_._", FieldName(field), "_cached_byte_size_"); } // Note: A lot of libraries detect Any protos based on Descriptor::full_name() @@ -734,6 +724,18 @@ return ""; } +// Returns true if this message has a _tracker_ field. +inline bool HasTracker(const Descriptor* desc, const Options& options) { + return options.field_listener_options.inject_field_listener_events && + desc->file()->options().optimize_for() != + google::protobuf::FileOptions::LITE_RUNTIME; +} + +// Returns true if this message needs an Impl_ struct for it's data. +inline bool HasImplData(const Descriptor* desc, const Options& options) { + return !HasSimpleBaseClass(desc, options); +} + // Formatter is a functor class which acts as a closure around printer and // the variable map. It's much like printer->Print except it supports both named // variables that are substituted using a key value map and direct arguments. In @@ -1011,10 +1013,20 @@ bool EnableMessageOwnedArena(const Descriptor* desc, const Options& options); +bool EnableMessageOwnedArenaTrial(const Descriptor* desc, + const Options& options); + bool ShouldVerify(const Descriptor* descriptor, const Options& options, MessageSCCAnalyzer* scc_analyzer); bool ShouldVerify(const FileDescriptor* file, const Options& options, MessageSCCAnalyzer* scc_analyzer); + +bool ShouldVerifySimple(const Descriptor* descriptor); + +bool IsUtf8String(const FieldDescriptor* field); + +bool HasMessageFieldOrExtension(const Descriptor* desc); + } // namespace cpp } // namespace compiler } // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.cc b/src/google/protobuf/compiler/cpp/map_field.cc similarity index 92% rename from src/google/protobuf/compiler/cpp/cpp_map_field.cc rename to src/google/protobuf/compiler/cpp/map_field.cc index 5713fd8..f1356e7 100644 --- a/src/google/protobuf/compiler/cpp/cpp_map_field.cc +++ b/src/google/protobuf/compiler/cpp/map_field.cc
@@ -28,12 +28,12 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/cpp/cpp_map_field.h> +#include <google/protobuf/compiler/cpp/map_field.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> namespace google { @@ -226,8 +226,7 @@ format); } } - format( - "};\n"); + format("};\n"); } format( @@ -271,21 +270,37 @@ "false;\n"); } -void MapFieldGenerator::GenerateConstinitInitializer( +void MapFieldGenerator::GenerateConstexprAggregateInitializer( io::Printer* printer) const { Formatter format(printer, variables_); if (HasDescriptorMethods(descriptor_->file(), options_)) { - format("$name$_(::$proto_ns$::internal::ConstantInitialized{})"); + format("/*decltype($field$)*/{::_pbi::ConstantInitialized()}"); } else { - format("$name$_()"); + format("/*decltype($field$)*/{}"); } } +void MapFieldGenerator::GenerateCopyAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + // MapField has no move constructor, which prevents explicit aggregate + // initialization pre-C++17. + format("/*decltype($field$)*/{}"); +} + +void MapFieldGenerator::GenerateAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + // MapField has no move constructor. + format("/*decltype($field$)*/{::_pbi::ArenaInitialized(), arena}"); +} + void MapFieldGenerator::GenerateDestructorCode(io::Printer* printer) const { GOOGLE_CHECK(!IsFieldStripped(descriptor_, options_)); Formatter format(printer, variables_); format("$field$.Destruct();\n"); + format("$field$.~MapField$lite$();\n"); } void MapFieldGenerator::GenerateArenaDestructorCode(
diff --git a/src/google/protobuf/compiler/cpp/cpp_map_field.h b/src/google/protobuf/compiler/cpp/map_field.h similarity index 90% rename from src/google/protobuf/compiler/cpp/cpp_map_field.h rename to src/google/protobuf/compiler/cpp/map_field.h index 9e71267..678a128 100644 --- a/src/google/protobuf/compiler/cpp/cpp_map_field.h +++ b/src/google/protobuf/compiler/cpp/map_field.h
@@ -34,8 +34,8 @@ #include <map> #include <string> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_message_field.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/message_field.h> namespace google { namespace protobuf { @@ -61,7 +61,10 @@ io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; void GenerateIsInitialized(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; + void GenerateConstexprAggregateInitializer( + io::Printer* printer) const override; + void GenerateCopyAggregateInitializer(io::Printer* printer) const override; + void GenerateAggregateInitializer(io::Printer* printer) const override; void GenerateDestructorCode(io::Printer* printer) const override; void GenerateArenaDestructorCode(io::Printer* printer) const override; ArenaDtorNeeds NeedsArenaDestructor() const override;
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.cc b/src/google/protobuf/compiler/cpp/message.cc similarity index 93% rename from src/google/protobuf/compiler/cpp/cpp_message.cc rename to src/google/protobuf/compiler/cpp/message.cc index 8be652b..a2acc26 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.cc +++ b/src/google/protobuf/compiler/cpp/message.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_message.h> +#include <google/protobuf/compiler/cpp/message.h> #include <algorithm> #include <cstdint> @@ -52,12 +52,12 @@ #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/cpp/cpp_enum.h> -#include <google/protobuf/compiler/cpp/cpp_extension.h> -#include <google/protobuf/compiler/cpp/cpp_field.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h> -#include <google/protobuf/compiler/cpp/cpp_parse_function_generator.h> +#include <google/protobuf/compiler/cpp/enum.h> +#include <google/protobuf/compiler/cpp/extension.h> +#include <google/protobuf/compiler/cpp/field.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/padding_optimizer.h> +#include <google/protobuf/compiler/cpp/parse_function_generator.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/stubs/hash.h> @@ -83,7 +83,7 @@ // masks must be non-zero. std::string ConditionalToCheckBitmasks( const std::vector<uint32_t>& masks, bool return_success = true, - StringPiece has_bits_var = "_has_bits_") { + StringPiece has_bits_var = "_impl_._has_bits_") { std::vector<std::string> parts; for (int i = 0; i < masks.size(); i++) { if (masks[i] == 0) continue; @@ -403,7 +403,7 @@ class ColdChunkSkipper { public: ColdChunkSkipper( - const Options& options, + const Descriptor* descriptor, const Options& options, const std::vector<std::vector<const FieldDescriptor*>>& chunks, const std::vector<int>& has_bit_indices, const double cold_threshold) : chunks_(chunks), @@ -411,7 +411,7 @@ access_info_map_(options.access_info_map), cold_threshold_(cold_threshold) { SetCommonVars(options, &variables_); - SetCommonMessageDataVariables(&variables_); + SetCommonMessageDataVariables(descriptor, &variables_); } // May open an external if check for a batch of cold fields. "from" is the @@ -495,7 +495,7 @@ 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); + format("($1$_impl_._has_bits_[$2$] & 0x$mask$u) != 0", from, this_word); } } format(")) {\n"); @@ -547,9 +547,7 @@ for (const auto& annotation : accessor_annotations_to_hooks) { (*variables)[annotation.first] = ""; } - if (!options.field_listener_options.inject_field_listener_events || - descriptor->file()->options().optimize_for() == - google::protobuf::FileOptions::LITE_RUNTIME) { + if (!HasTracker(descriptor, options)) { return; } StringPiece tracker = (*variables)["tracker"]; @@ -617,7 +615,7 @@ if (!message_layout_helper_) { message_layout_helper_.reset(new PaddingOptimizer()); } - SetCommonMessageDataVariables(&variables_); + SetCommonMessageDataVariables(descriptor, &variables_); // Variables that apply to this class variables_["classname"] = classname_; @@ -630,9 +628,7 @@ variables_["annotate_bytesize"] = ""; variables_["annotate_mergefrom"] = ""; - if (options.field_listener_options.inject_field_listener_events && - descriptor->file()->options().optimize_for() != - google::protobuf::FileOptions::LITE_RUNTIME) { + if (HasTracker(descriptor_, options_)) { const std::string injector_template = StrCat(" ", variables_["tracker"], "."); @@ -1398,6 +1394,11 @@ format( "inline $classname$() : $classname$(" "::$proto_ns$::Arena::InternalCreateMessageOwnedArena(), true) {}\n"); + } else if (EnableMessageOwnedArenaTrial(descriptor_, options_)) { + format( + "inline $classname$() : $classname$(InMoaTrial() ? " + "::$proto_ns$::Arena::InternalCreateMessageOwnedArena() : nullptr, " + "InMoaTrial()) {}\n"); } else { format("inline $classname$() : $classname$(nullptr) {}\n"); } @@ -1510,11 +1511,13 @@ if (HasDescriptorMethods(descriptor_->file(), options_)) { format( "bool PackFrom(const ::$proto_ns$::Message& message) {\n" + " $DCHK$_NE(&message, this);\n" " return $any_metadata$.PackFrom(GetArena(), message);\n" "}\n" "bool PackFrom(const ::$proto_ns$::Message& message,\n" " ::PROTOBUF_NAMESPACE_ID::ConstStringParam " "type_url_prefix) {\n" + " $DCHK$_NE(&message, this);\n" " return $any_metadata$.PackFrom(GetArena(), message, " "type_url_prefix);\n" "}\n" @@ -1676,7 +1679,7 @@ "int GetCachedSize() const final { return " "$cached_size$.Get(); }" "\n\nprivate:\n" - "void SharedCtor();\n" + "void SharedCtor(::$proto_ns$::Arena* arena, bool is_message_owned);\n" "void SharedDtor();\n" "void SetCachedSize(int size) const$ full_final$;\n" "void InternalSwap($classname$* other);\n"); @@ -1837,12 +1840,21 @@ : StrCat("::$proto_ns$::internal::HasBits<", sizeof_has_bits, "> _has_bits_;\n"); + format( + "template <typename T> friend class " + "::$proto_ns$::Arena::InternalHelper;\n" + "typedef void InternalArenaConstructable_;\n" + "typedef void DestructorSkippable_;\n"); + // To minimize padding, data members are divided into three sections: // (1) members assumed to align to 8 bytes // (2) members corresponding to message fields, re-ordered to optimize // alignment. // (3) members assumed to align to 4 bytes. + format("struct Impl_ {\n"); + format.Indent(); + // Members assumed to align to 8 bytes: if (descriptor_->extension_range_count() > 0) { @@ -1851,9 +1863,7 @@ "\n"); } - if (options_.field_listener_options.inject_field_listener_events && - descriptor_->file()->options().optimize_for() != - google::protobuf::FileOptions::LITE_RUNTIME) { + if (HasTracker(descriptor_, options_)) { format("static ::$proto_ns$::AccessListener<$1$> _tracker_;\n", ClassName(descriptor_)); } @@ -1866,12 +1876,6 @@ InlinedStringDonatedSize()); } - format( - "template <typename T> friend class " - "::$proto_ns$::Arena::InternalHelper;\n" - "typedef void InternalArenaConstructable_;\n" - "typedef void DestructorSkippable_;\n"); - 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 @@ -1941,6 +1945,14 @@ format("::$proto_ns$::internal::AnyMetadata _any_metadata_;\n"); } + format.Outdent(); + format("};\n"); + + // Only create the _impl_ field if it contains data. + if (HasImplData(descriptor_, options_)) { + format("union { Impl_ _impl_; };\n"); + } + // The TableStruct struct needs access to the private parts, in order to // construct the offsets of all members. format("friend struct ::$tablename$;\n"); @@ -2172,9 +2184,7 @@ "\n"); } - if (options_.field_listener_options.inject_field_listener_events && - descriptor_->file()->options().optimize_for() != - google::protobuf::FileOptions::LITE_RUNTIME) { + if (HasTracker(descriptor_, options_)) { format( "::$proto_ns$::AccessListener<$classtype$> " "$1$::$tracker$(&FullMessageName);\n", @@ -2250,7 +2260,7 @@ int count = 0; for (auto oneof : OneOfRange(descriptor_)) { - format("PROTOBUF_FIELD_OFFSET($classtype$, $1$_),\n", oneof->name()); + format("PROTOBUF_FIELD_OFFSET($classtype$, _impl_.$1$_),\n", oneof->name()); count++; } GOOGLE_CHECK_EQ(count, descriptor_->real_oneof_decl_count()); @@ -2286,15 +2296,110 @@ if (HasSimpleBaseClass(descriptor_, options_)) return; Formatter format(printer, variables_); - format("inline void $classname$::SharedCtor() {\n"); + format( + "inline void $classname$::SharedCtor(\n" + " ::_pb::Arena* arena, bool is_message_owned) {\n" + " (void)arena;\n" + " (void)is_message_owned;\n"); - std::vector<bool> processed(optimized_order_.size(), false); - GenerateConstructorBody(printer, processed, false); + format.Indent(); + // Impl_ _impl_. + format("new (&_impl_) Impl_{"); + format.Indent(); + const char* field_sep = " "; + const auto put_sep = [&] { + format("\n$1$ ", field_sep); + field_sep = ","; + }; + + // Note: any fields without move/copy constructors can't be explicitly + // aggregate initialized pre-C++17. + if (descriptor_->extension_range_count() > 0) { + put_sep(); + format("/*decltype($extensions$)*/{::_pbi::ArenaInitialized(), arena}"); + } + if (!inlined_string_indices_.empty()) { + put_sep(); + format("decltype($inlined_string_donated_array$){}"); + } + bool need_to_emit_cached_size = !HasSimpleBaseClass(descriptor_, options_); + if (!has_bit_indices_.empty()) { + put_sep(); + format("decltype($has_bits$){}"); + if (need_to_emit_cached_size) { + put_sep(); + format("/*decltype($cached_size$)*/{}"); + need_to_emit_cached_size = false; + } + } + + // Initialize member variables with arena constructor. + for (auto field : optimized_order_) { + GOOGLE_DCHECK(!IsFieldStripped(field, options_)); + put_sep(); + field_generators_.get(field).GenerateAggregateInitializer(printer); + } + for (auto oneof : OneOfRange(descriptor_)) { + put_sep(); + format("decltype(_impl_.$1$_){}", oneof->name()); + } + + if (need_to_emit_cached_size) { + put_sep(); + format("/*decltype($cached_size$)*/{}"); + } + + if (descriptor_->real_oneof_decl_count() != 0) { + put_sep(); + format("/*decltype($oneof_case$)*/{}"); + } + if (num_weak_fields_ > 0) { + put_sep(); + format("decltype($weak_field_map$){arena}"); + } + if (IsAnyMessage(descriptor_, options_)) { + put_sep(); + // AnyMetadata has no move constructor. + format("/*decltype($any_metadata$)*/{&_impl_.type_url_, &_impl_.value_}"); + } + + format.Outdent(); + format("\n};\n"); + + if (!inlined_string_indices_.empty()) { + // Donate inline string fields. + format.Indent(); + // The last bit is the tracking bit for registering ArenaDtor. The bit is 1 + // means ArenaDtor is not registered on construction, and on demand register + // is needed. + format("if (arena != nullptr) {\n"); + if (NeedsArenaDestructor() == ArenaDtorNeeds::kOnDemand) { + format( + " if (!is_message_owned) {\n" + " $inlined_string_donated_array$[0] = ~0u;\n" + " } else {\n" + // We should not register ArenaDtor for MOA. + " $inlined_string_donated_array$[0] = 0xFFFFFFFEu;\n" + " }\n"); + } else { + format(" $inlined_string_donated_array$[0] = 0xFFFFFFFEu;\n"); + } + for (size_t i = 1; i < InlinedStringDonatedSize(); ++i) { + format(" $inlined_string_donated_array$[$1$] = ~0u;\n", i); + } + format("}\n"); + format.Outdent(); + } + + for (const FieldDescriptor* field : optimized_order_) { + field_generators_.get(field).GenerateConstructorCode(printer); + } for (auto oneof : OneOfRange(descriptor_)) { format("clear_has_$1$();\n", oneof->name()); } + format.Outdent(); format("}\n\n"); } @@ -2305,6 +2410,11 @@ format("inline void $classname$::SharedDtor() {\n"); format.Indent(); format("$DCHK$(GetArenaForAllocation() == nullptr);\n"); + + if (descriptor_->extension_range_count() > 0) { + format("$extensions$.~ExtensionSet();\n"); + } + // Write the destructors for each field except oneof members. // optimized_order_ does not contain oneof fields. for (auto field : optimized_order_) { @@ -2323,6 +2433,11 @@ if (num_weak_fields_) { format("$weak_field_map$.ClearAll();\n"); } + + if (IsAnyMessage(descriptor_, options_)) { + format("$any_metadata$.~AnyMetadata();\n"); + } + format.Outdent(); format( "}\n" @@ -2378,71 +2493,90 @@ void MessageGenerator::GenerateConstexprConstructor(io::Printer* printer) { Formatter format(printer, variables_); + if (IsMapEntryMessage(descriptor_) || !HasImplData(descriptor_, options_)) { + format( + "PROTOBUF_CONSTEXPR $classname$::$classname$(\n" + " ::_pbi::ConstantInitialized) {}\n"); + return; + } + format( "PROTOBUF_CONSTEXPR $classname$::$classname$(\n" " ::_pbi::ConstantInitialized)"); + + bool need_to_emit_cached_size = !HasSimpleBaseClass(descriptor_, options_); + format(": _impl_{"); format.Indent(); - const char* field_sep = ":"; + const char* field_sep = " "; const auto put_sep = [&] { format("\n$1$ ", field_sep); field_sep = ","; }; - - if (!IsMapEntryMessage(descriptor_)) { - // Process non-oneof fields first. - for (auto field : optimized_order_) { - auto& gen = field_generators_.get(field); + if (descriptor_->extension_range_count() > 0) { + put_sep(); + format("/*decltype($extensions$)*/{}"); + } + if (!inlined_string_indices_.empty()) { + put_sep(); + format("/*decltype($inlined_string_donated_array$)*/{}"); + } + if (!has_bit_indices_.empty()) { + put_sep(); + format("/*decltype($has_bits$)*/{}"); + if (need_to_emit_cached_size) { put_sep(); - gen.GenerateConstinitInitializer(printer); + format("/*decltype($cached_size$)*/{}"); + need_to_emit_cached_size = false; } + } + for (auto field : optimized_order_) { + put_sep(); + field_generators_.get(field).GenerateConstexprAggregateInitializer(printer); + } + for (auto oneof : OneOfRange(descriptor_)) { + put_sep(); + format("/*decltype(_impl_.$1$_)*/{}", oneof->name()); + } - if (IsAnyMessage(descriptor_, options_)) { - put_sep(); - format("_any_metadata_(&type_url_, &value_)"); - } + if (need_to_emit_cached_size) { + put_sep(); + format("/*decltype($cached_size$)*/{}"); + } - if (descriptor_->real_oneof_decl_count() != 0) { - put_sep(); - format("_oneof_case_{}"); - } + if (descriptor_->real_oneof_decl_count() != 0) { + put_sep(); + format("/*decltype($oneof_case$)*/{}"); + } + + if (num_weak_fields_) { + put_sep(); + format("/*decltype($weak_field_map$)*/{}"); + } + + if (IsAnyMessage(descriptor_, options_)) { + put_sep(); + format( + "/*decltype($any_metadata$)*/{&_impl_.type_url_, " + "&_impl_.value_}"); } format.Outdent(); - format("{}\n"); + format("} {}\n"); } -void MessageGenerator::GenerateConstructorBody(io::Printer* printer, - std::vector<bool> processed, - bool copy_constructor) const { +void MessageGenerator::GenerateCopyConstructorBody(io::Printer* printer) const { Formatter format(printer, variables_); - const RunMap runs = FindRuns( - optimized_order_, [copy_constructor, this](const FieldDescriptor* field) { - return (copy_constructor && IsPOD(field)) || - (!copy_constructor && - CanBeManipulatedAsRawBytes(field, options_, scc_analyzer_)); - }); + const RunMap runs = + FindRuns(optimized_order_, + [](const FieldDescriptor* field) { return IsPOD(field); }); - std::string pod_template; - if (copy_constructor) { - pod_template = - "::memcpy(&$first$, &from.$first$,\n" - " static_cast<size_t>(reinterpret_cast<char*>(&$last$) -\n" - " reinterpret_cast<char*>(&$first$)) + sizeof($last$));\n"; - } else { - pod_template = - "::memset(reinterpret_cast<char*>(this) + static_cast<size_t>(\n" - " reinterpret_cast<char*>(&$first$) - " - "reinterpret_cast<char*>(this)),\n" - " 0, static_cast<size_t>(reinterpret_cast<char*>(&$last$) -\n" - " reinterpret_cast<char*>(&$first$)) + sizeof($last$));\n"; - } + std::string pod_template = + "::memcpy(&$first$, &from.$first$,\n" + " static_cast<size_t>(reinterpret_cast<char*>(&$last$) -\n" + " reinterpret_cast<char*>(&$first$)) + sizeof($last$));\n"; - for (int i = 0; i < optimized_order_.size(); ++i) { - if (processed[i]) { - continue; - } - + for (size_t i = 0; i < optimized_order_.size(); ++i) { const FieldDescriptor* field = optimized_order_[i]; const auto it = runs.find(field); @@ -2463,11 +2597,7 @@ i += run_length - 1; // ++i at the top of the loop. } else { - if (copy_constructor) { - field_generators_.get(field).GenerateCopyConstructorCode(printer); - } else { - field_generators_.get(field).GenerateConstructorCode(printer); - } + field_generators_.get(field).GenerateCopyConstructorCode(printer); } } } @@ -2475,78 +2605,14 @@ void MessageGenerator::GenerateStructors(io::Printer* printer) { Formatter format(printer, variables_); - std::string superclass; - superclass = SuperClassName(descriptor_, options_); - std::string initializer_with_arena = superclass + "(arena, is_message_owned)"; - - if (descriptor_->extension_range_count() > 0) { - initializer_with_arena += ",\n _extensions_(arena)"; - } - - // Initialize member variables with arena constructor. - for (auto field : optimized_order_) { - GOOGLE_DCHECK(!IsFieldStripped(field, options_)); - bool has_arena_constructor = field->is_repeated(); - if (!field->real_containing_oneof() && - (IsLazy(field, options_, scc_analyzer_) || - IsStringPiece(field, options_) || - (IsString(field, options_) && IsStringInlined(field, options_)))) { - has_arena_constructor = true; - } - if (has_arena_constructor) { - initializer_with_arena += - std::string(",\n ") + FieldName(field) + std::string("_(arena)"); - } - } - - if (IsAnyMessage(descriptor_, options_)) { - initializer_with_arena += ",\n _any_metadata_(&type_url_, &value_)"; - } - if (num_weak_fields_ > 0) { - initializer_with_arena += ", _weak_field_map_(arena)"; - } - - std::string initializer_null = superclass + "()"; - if (IsAnyMessage(descriptor_, options_)) { - initializer_null += ", _any_metadata_(&type_url_, &value_)"; - } - if (num_weak_fields_ > 0) { - initializer_null += ", _weak_field_map_(nullptr)"; - } - format( "$classname$::$classname$(::$proto_ns$::Arena* arena,\n" " bool is_message_owned)\n" - " : $1$ {\n", - initializer_with_arena); - - if (!inlined_string_indices_.empty()) { - // Donate inline string fields. - format.Indent(); - // The last bit is the tracking bit for registering ArenaDtor. The bit is 1 - // means ArenaDtor is not registered on construction, and on demand register - // is needed. - format("if (arena != nullptr) {\n"); - if (NeedsArenaDestructor() == ArenaDtorNeeds::kOnDemand) { - format( - " if (!is_message_owned) {\n" - " $inlined_string_donated_array$[0] = ~0u;\n" - " } else {\n" - // We should not register ArenaDtor for MOA. - " $inlined_string_donated_array$[0] = 0xFFFFFFFEu;\n" - " }\n"); - } else { - format(" $inlined_string_donated_array$[0] = 0xFFFFFFFEu;\n"); - } - for (size_t i = 1; i < InlinedStringDonatedSize(); ++i) { - format(" $inlined_string_donated_array$[$1$] = ~0u;\n", i); - } - format("}\n"); - format.Outdent(); - } + " : $1$(arena, is_message_owned) {\n", + SuperClassName(descriptor_, options_)); if (!HasSimpleBaseClass(descriptor_, options_)) { - format(" SharedCtor();\n"); + format(" SharedCtor(arena, is_message_owned);\n"); if (NeedsArenaDestructor() == ArenaDtorNeeds::kRequired) { format( " if (arena != nullptr && !is_message_owned) {\n" @@ -2576,40 +2642,72 @@ } else { format( "$classname$::$classname$(const $classname$& from)\n" - " : $superclass$()"); - format.Indent(); - format.Indent(); + " : $superclass$() {\n"); format.Indent(); - // Do not copy inlined_string_donated_, because this is not an arena - // constructor. + if (HasImplData(descriptor_, options_)) { + const char* field_sep = " "; + const auto put_sep = [&] { + format("\n$1$ ", field_sep); + field_sep = ","; + }; - if (!has_bit_indices_.empty()) { - format(",\n_has_bits_(from._has_bits_)"); - } + format("new (&_impl_) Impl_{"); + format.Indent(); - std::vector<bool> processed(optimized_order_.size(), false); - for (int i = 0; i < optimized_order_.size(); i++) { - auto field = optimized_order_[i]; - if (!(field->is_repeated() && !(field->is_map())) && - !IsCord(field, options_)) { - continue; + if (descriptor_->extension_range_count() > 0) { + put_sep(); + format("/*decltype($extensions$)*/{}"); + } + if (!inlined_string_indices_.empty()) { + // Do not copy inlined_string_donated_, because this is not an arena + // constructor. + put_sep(); + format("decltype($inlined_string_donated_array$){}"); + } + bool need_to_emit_cached_size = + !HasSimpleBaseClass(descriptor_, options_); + if (!has_bit_indices_.empty()) { + put_sep(); + format("decltype($has_bits$){from.$has_bits$}"); + if (need_to_emit_cached_size) { + put_sep(); + format("/*decltype($cached_size$)*/{}"); + need_to_emit_cached_size = false; + } } - processed[i] = true; - format(",\n$1$_(from.$1$_)", FieldName(field)); - } + // Initialize member variables with arena constructor. + for (auto field : optimized_order_) { + put_sep(); + field_generators_.get(field).GenerateCopyAggregateInitializer(printer); + } + for (auto oneof : OneOfRange(descriptor_)) { + put_sep(); + format("decltype(_impl_.$1$_){}", oneof->name()); + } - if (IsAnyMessage(descriptor_, options_)) { - format(",\n_any_metadata_(&type_url_, &value_)"); - } - if (num_weak_fields_ > 0) { - format(",\n_weak_field_map_(from._weak_field_map_)"); - } + if (need_to_emit_cached_size) { + put_sep(); + format("/*decltype($cached_size$)*/{}"); + } - format.Outdent(); - format.Outdent(); - format(" {\n"); + if (descriptor_->real_oneof_decl_count() != 0) { + put_sep(); + format("/*decltype($oneof_case$)*/{}"); + } + if (num_weak_fields_ > 0) { + put_sep(); + format("decltype($weak_field_map$){from.$weak_field_map$}"); + } + if (IsAnyMessage(descriptor_, options_)) { + put_sep(); + format( + "/*decltype($any_metadata$)*/{&_impl_.type_url_, &_impl_.value_}"); + } + format.Outdent(); + format("};\n\n"); + } format( "_internal_metadata_.MergeFrom<$unknown_fields_type$>(from._internal_" @@ -2621,7 +2719,7 @@ "from.$extensions$);\n"); } - GenerateConstructorBody(printer, processed, true); + GenerateCopyConstructorBody(printer); // Copy oneof fields. Oneof field requires oneof case check. for (auto oneof : OneOfRange(descriptor_)) { @@ -2763,7 +2861,8 @@ return same; }); - ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio); + ColdChunkSkipper cold_skipper(descriptor_, options_, chunks, has_bit_indices_, + kColdRatio); int cached_has_word_index = -1; for (int chunk_index = 0; chunk_index < chunks.size(); chunk_index++) { @@ -3002,14 +3101,11 @@ } for (auto oneof : OneOfRange(descriptor_)) { - format("swap($1$_, other->$1$_);\n", oneof->name()); + format("swap(_impl_.$1$_, other->_impl_.$1$_);\n", oneof->name()); } for (int i = 0; i < descriptor_->real_oneof_decl_count(); i++) { - format( - "swap($oneof_case$[$1$], " - "other->$oneof_case$[$1$]);\n", - i); + format("swap($oneof_case$[$1$], other->$oneof_case$[$1$]);\n", i); } if (num_weak_fields_) { @@ -3050,7 +3146,7 @@ format( "const ::$proto_ns$::Message::ClassData " "$classname$::_class_data_ = {\n" - " ::$proto_ns$::Message::CopyWithSizeCheck,\n" + " ::$proto_ns$::Message::CopyWithSourceCheck,\n" " $classname$::MergeImpl\n" "};\n" "const ::$proto_ns$::Message::ClassData*" @@ -3109,7 +3205,8 @@ return HasByteIndex(a) == HasByteIndex(b); }); - ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio); + ColdChunkSkipper cold_skipper(descriptor_, options_, chunks, has_bit_indices_, + kColdRatio); // cached_has_word_index maintains that: // cached_has_bits = from._has_bits_[cached_has_word_index] @@ -3263,12 +3360,12 @@ // takes in the Message base class as a parameter); instead we just // let the base Message::CopyFrom take care of it. The base MergeFrom // knows how to quickly confirm the types exactly match, and if so, will - // use GetClassData() to get the address of Message::CopyWithSizeCheck, + // use GetClassData() to get the address of Message::CopyWithSourceCheck, // which calls Clear() and then MergeFrom(), as well as making sure that - // clearing the destination message doesn't alter the size of the source, - // when in debug builds. - // Most callers avoid this by passing a "from" message that is the same - // type as the message being merged into, rather than a generic Message. + // clearing the destination message doesn't alter the source, when in debug + // builds. Most callers avoid this by passing a "from" message that is the + // same type as the message being merged into, rather than a generic + // Message. } // Generate the class-specific CopyFrom. @@ -3280,20 +3377,33 @@ format("if (&from == this) return;\n"); - if (!options_.opensource_runtime) { + if (!options_.opensource_runtime && HasMessageFieldOrExtension(descriptor_)) { // This check is disabled in the opensource release because we're // concerned that many users do not define NDEBUG in their release builds. + // It is also disabled if a message has neither message fields nor + // extensions, as it's impossible to copy from its descendant. + // + // Note that FailIfCopyFromDescendant is implemented by reflection and not + // available for lite runtime. In that case, check if the size of the source + // has changed after Clear. + format("#ifndef NDEBUG\n"); + if (HasDescriptorMethods(descriptor_->file(), options_)) { + format("FailIfCopyFromDescendant(this, from);\n"); + } else { + format("size_t from_size = from.ByteSizeLong();\n"); + } format( - "#ifndef NDEBUG\n" - "size_t from_size = from.ByteSizeLong();\n" "#endif\n" - "Clear();\n" - "#ifndef NDEBUG\n" - "$CHK$_EQ(from_size, from.ByteSizeLong())\n" - " << \"Source of CopyFrom changed when clearing target. Either \"\n" - " \"source is a nested message in target (not allowed), or \"\n" - " \"another thread is modifying the source.\";\n" - "#endif\n"); + "Clear();\n"); + if (!HasDescriptorMethods(descriptor_->file(), options_)) { + format( + "#ifndef NDEBUG\n" + "$CHK$_EQ(from_size, from.ByteSizeLong())\n" + " << \"Source of CopyFrom changed when clearing target. Either \"\n" + " \"source is a nested message in target (not allowed), or \"\n" + " \"another thread is modifying the source.\";\n" + "#endif\n"); + } } else { format("Clear();\n"); } @@ -3485,7 +3595,7 @@ // Reload. int new_index = has_bit_index / 32; - format_("cached_has_bits = _has_bits_[$1$];\n", new_index); + format_("cached_has_bits = _impl_._has_bits_[$1$];\n", new_index); cached_has_bit_index_ = new_index; } @@ -3885,7 +3995,8 @@ chunks.erase(std::remove_if(chunks.begin(), chunks.end(), IsRequired), chunks.end()); - ColdChunkSkipper cold_skipper(options_, chunks, has_bit_indices_, kColdRatio); + ColdChunkSkipper cold_skipper(descriptor_, options_, chunks, has_bit_indices_, + kColdRatio); int cached_has_word_index = -1; format(
diff --git a/src/google/protobuf/compiler/cpp/cpp_message.h b/src/google/protobuf/compiler/cpp/message.h similarity index 94% rename from src/google/protobuf/compiler/cpp/cpp_message.h rename to src/google/protobuf/compiler/cpp/message.h index 5051a97..ec23c44 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message.h +++ b/src/google/protobuf/compiler/cpp/message.h
@@ -40,11 +40,11 @@ #include <set> #include <string> -#include <google/protobuf/compiler/cpp/cpp_field.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_message_layout_helper.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> -#include <google/protobuf/compiler/cpp/cpp_parse_function_generator.h> +#include <google/protobuf/compiler/cpp/field.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/message_layout_helper.h> +#include <google/protobuf/compiler/cpp/options.h> +#include <google/protobuf/compiler/cpp/parse_function_generator.h> namespace google { namespace protobuf { @@ -161,9 +161,8 @@ void GenerateFieldClear(const FieldDescriptor* field, bool is_inline, Formatter format); - void GenerateConstructorBody(io::Printer* printer, - std::vector<bool> already_processed, - bool copy_constructor) const; + // Generates the body of the message's copy constructor. + void GenerateCopyConstructorBody(io::Printer* printer) const; // Returns the level that this message needs ArenaDtor. If the message has // a field that is not arena-exclusive, it needs an ArenaDtor
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.cc b/src/google/protobuf/compiler/cpp/message_field.cc similarity index 97% rename from src/google/protobuf/compiler/cpp/cpp_message_field.cc rename to src/google/protobuf/compiler/cpp/message_field.cc index 809a9e0..65b63ae 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message_field.cc +++ b/src/google/protobuf/compiler/cpp/message_field.cc
@@ -32,10 +32,10 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_message_field.h> +#include <google/protobuf/compiler/cpp/message_field.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> #include <google/protobuf/stubs/strutil.h> @@ -157,8 +157,7 @@ } void MessageFieldGenerator::GenerateNonInlineAccessorDefinitions( - io::Printer* printer) const { -} + io::Printer* printer) const {} void MessageFieldGenerator::GenerateInlineAccessorDefinitions( io::Printer* printer) const { @@ -438,14 +437,6 @@ format("delete $field$;\n"); } -void MessageFieldGenerator::GenerateConstructorCode( - io::Printer* printer) const { - GOOGLE_CHECK(!IsFieldStripped(descriptor_, options_)); - - Formatter format(printer, variables_); - format("$field$ = nullptr;\n"); -} - void MessageFieldGenerator::GenerateCopyConstructorCode( io::Printer* printer) const { GOOGLE_CHECK(!IsFieldStripped(descriptor_, options_)); @@ -454,8 +445,6 @@ format( "if (from._internal_has_$name$()) {\n" " $field$ = new $type$(*from.$field$);\n" - "} else {\n" - " $field$ = nullptr;\n" "}\n"); } @@ -500,10 +489,22 @@ "}\n"); } -void MessageFieldGenerator::GenerateConstinitInitializer( +void MessageFieldGenerator::GenerateConstexprAggregateInitializer( io::Printer* printer) const { Formatter format(printer, variables_); - format("$name$_(nullptr)"); + format("/*decltype($field$)*/nullptr"); +} + +void MessageFieldGenerator::GenerateCopyAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){nullptr}"); +} + +void MessageFieldGenerator::GenerateAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){nullptr}"); } // =================================================================== @@ -846,6 +847,18 @@ // Not needed for repeated fields. } +void RepeatedMessageFieldGenerator::GenerateDestructorCode( + io::Printer* printer) const { + GOOGLE_CHECK(!IsFieldStripped(descriptor_, options_)); + + Formatter format(printer, variables_); + if (implicit_weak_field_) { + format("$field$.~WeakRepeatedPtrField();\n"); + } else { + format("$field$.~RepeatedPtrField();\n"); + } +} + void RepeatedMessageFieldGenerator::GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const { GOOGLE_CHECK(!IsFieldStripped(descriptor_, options_)); @@ -922,12 +935,6 @@ } } -void RepeatedMessageFieldGenerator::GenerateConstinitInitializer( - io::Printer* printer) const { - Formatter format(printer, variables_); - format("$name$_()"); -} - } // namespace cpp } // namespace compiler } // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_field.h b/src/google/protobuf/compiler/cpp/message_field.h similarity index 93% rename from src/google/protobuf/compiler/cpp/cpp_message_field.h rename to src/google/protobuf/compiler/cpp/message_field.h index 528b419..70c42c0 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message_field.h +++ b/src/google/protobuf/compiler/cpp/message_field.h
@@ -38,8 +38,8 @@ #include <map> #include <string> -#include <google/protobuf/compiler/cpp/cpp_field.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/field.h> +#include <google/protobuf/compiler/cpp/helpers.h> namespace google { namespace protobuf { @@ -67,13 +67,16 @@ void GenerateMergingCode(io::Printer* printer) const override; void GenerateSwappingCode(io::Printer* printer) const override; void GenerateDestructorCode(io::Printer* printer) const override; - void GenerateConstructorCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override {} void GenerateCopyConstructorCode(io::Printer* printer) const override; void GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; void GenerateIsInitialized(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; + void GenerateConstexprAggregateInitializer( + io::Printer* printer) const override; + void GenerateAggregateInitializer(io::Printer* printer) const override; + void GenerateCopyAggregateInitializer(io::Printer* printer) const override; protected: const bool implicit_weak_field_; @@ -124,11 +127,11 @@ void GenerateSwappingCode(io::Printer* printer) const override; void GenerateConstructorCode(io::Printer* printer) const override; void GenerateCopyConstructorCode(io::Printer* printer) const override {} + void GenerateDestructorCode(io::Printer* printer) const override; void GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; void GenerateIsInitialized(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; private: const bool implicit_weak_field_;
diff --git a/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h b/src/google/protobuf/compiler/cpp/message_layout_helper.h similarity index 97% rename from src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h rename to src/google/protobuf/compiler/cpp/message_layout_helper.h index 8086005..a8813a1 100644 --- a/src/google/protobuf/compiler/cpp/cpp_message_layout_helper.h +++ b/src/google/protobuf/compiler/cpp/message_layout_helper.h
@@ -36,7 +36,7 @@ #define GOOGLE_PROTOBUF_COMPILER_CPP_MESSAGE_LAYOUT_HELPER_H__ #include <google/protobuf/descriptor.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/message_size_unittest.cc b/src/google/protobuf/compiler/cpp/message_size_unittest.cc new file mode 100644 index 0000000..761988b --- /dev/null +++ b/src/google/protobuf/compiler/cpp/message_size_unittest.cc
@@ -0,0 +1,272 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include <google/protobuf/unittest.pb.h> +#include <gmock/gmock.h> +#include <gtest/gtest.h> +#include <google/protobuf/descriptor.h> + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +// Can't use an anonymous namespace here due to brokenness of Tru64 compiler. +namespace cpp_unittest { + + +#if !defined(GOOGLE_CHECK_MESSAGE_SIZE) +#define GOOGLE_CHECK_MESSAGE_SIZE(t, expected) +#endif + +// Mock structures to lock down the size of messages in a platform-independent +// way. The commented sizes only apply when build with clang x86_64. +struct MockMessageBase { + virtual ~MockMessageBase() = default; // 8 bytes vtable + void* internal_metadata; // 8 bytes +}; +GOOGLE_CHECK_MESSAGE_SIZE(MockMessageBase, 16); + +struct MockZeroFieldsBase : public MockMessageBase { + int cached_size; // 4 bytes + // + 4 bytes padding +}; +GOOGLE_CHECK_MESSAGE_SIZE(MockZeroFieldsBase, 24); + +struct MockExtensionSet { + void* arena; // 8 bytes + int16_t capacity; // 4 bytes + int16_t size; // 4 bytes + void* data; // 8 bytes +}; +GOOGLE_CHECK_MESSAGE_SIZE(MockExtensionSet, 24); + +struct MockRepeatedPtrField { + void* arena; // 8 bytes + int current_size; // 4 bytes + int total_size; // 4 bytes + void* data; // 8 bytes +}; +GOOGLE_CHECK_MESSAGE_SIZE(MockRepeatedPtrField, 24); + +struct MockRepeatedField { + int current_size; // 4 bytes + int total_size; // 4 bytes + void* data; // 8 bytes +}; +GOOGLE_CHECK_MESSAGE_SIZE(MockRepeatedField, 16); + +TEST(GeneratedMessageTest, MockSizes) { + // Consistency checks -- if these fail, the tests below will definitely fail. + GOOGLE_CHECK_EQ(sizeof(MessageLite), sizeof(MockMessageBase)); + GOOGLE_CHECK_EQ(sizeof(Message), sizeof(MockMessageBase)); + GOOGLE_CHECK_EQ(sizeof(internal::ZeroFieldsBase), sizeof(MockZeroFieldsBase)); + GOOGLE_CHECK_EQ(sizeof(internal::ExtensionSet), sizeof(MockExtensionSet)); + GOOGLE_CHECK_EQ(sizeof(RepeatedPtrField<std::string>), sizeof(MockRepeatedPtrField)); + GOOGLE_CHECK_EQ(sizeof(RepeatedField<int>), sizeof(MockRepeatedField)); +} + +TEST(GeneratedMessageTest, EmptyMessageSize) { + EXPECT_EQ(sizeof(protobuf_unittest::TestEmptyMessage), + sizeof(MockZeroFieldsBase)); +} + +TEST(GeneratedMessageTest, ReservedSize) { + EXPECT_EQ(sizeof(protobuf_unittest::TestReservedFields), + sizeof(MockZeroFieldsBase)); +} + +TEST(GeneratedMessageTest, EmptyMessageWithExtensionsSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + MockExtensionSet extensions; // 24 bytes + int cached_size; // 4 bytes + // + 4 bytes of padding + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 48); + EXPECT_EQ(sizeof(protobuf_unittest::TestEmptyMessageWithExtensions), + sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, RecursiveMessageSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + void* a; // 8 bytes + int32_t i; // 4 bytes + // + 4 bytes padding + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 40); + EXPECT_EQ(sizeof(protobuf_unittest::TestRecursiveMessage), + sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, OneStringSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + void* data; // 8 bytes + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 32); + EXPECT_EQ(sizeof(protobuf_unittest::OneString), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, MoreStringSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + MockRepeatedPtrField data; // 24 bytes + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 48); + EXPECT_EQ(sizeof(protobuf_unittest::MoreString), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, Int32MessageSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + int32_t data; // 4 bytes + // + 4 bytes padding + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 32); + EXPECT_EQ(sizeof(protobuf_unittest::Int32Message), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, Int64MessageSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + int64_t data; // 8 bytes + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 32); + EXPECT_EQ(sizeof(protobuf_unittest::Int64Message), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, BoolMessageSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + bool data; // 1 byte + // + 3 bytes padding + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 32); + EXPECT_EQ(sizeof(protobuf_unittest::BoolMessage), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, OneofSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + void* foo; // 8 bytes + int cached_size; // 4 bytes + uint32_t oneof_case[1]; // 4 bytes + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 32); + EXPECT_EQ(sizeof(protobuf_unittest::TestOneof), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, Oneof2Size) { + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + void* baz_string; // 8 bytes + int32_t baz_int; // 4 bytes + // + 4 bytes padding + void* foo; // 8 bytes + void* bar; // 8 bytes + uint32_t oneof_case[2]; // 8 bytes + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 64); + EXPECT_EQ(sizeof(protobuf_unittest::TestOneof2), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, FieldOrderingsSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + MockExtensionSet extensions; // 24 bytes + void* my_string; // 8 bytes + void* optional_nested_message; // 8 bytes + int64_t my_int; // 8 bytes + float my_float; // 4 bytes + // + 4 bytes of padding + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 80); + EXPECT_EQ(sizeof(protobuf_unittest::TestFieldOrderings), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, TestMessageSize) { + // We expect the message to contain (not in this order): + struct MockGenerated : public MockMessageBase { // 16 bytes + int has_bits[1]; // 4 bytes + int cached_size; // 4 bytes + void* m4; // 8 bytes + int64_t m2; // 8 bytes + bool m1; // 1 bytes + bool m3; // 1 bytes + // + 2 bytes padding + int m5; // 4 bytes + int64_t m6; // 8 bytes + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 56); + EXPECT_EQ(sizeof(protobuf_unittest::TestMessageSize), sizeof(MockGenerated)); +} + +TEST(GeneratedMessageTest, PackedTypesSize) { + struct MockGenerated : public MockMessageBase { // 16 bytes + MockRepeatedField packed_int32; // 16 bytes + int packed_int32_cached_byte_size; // 4 bytes + 4 bytes padding + MockRepeatedField packed_int64; // 16 bytes + int packed_int64_cached_byte_size; // 4 bytes + 4 bytes padding + MockRepeatedField packed_uint32; // 16 bytes + int packed_uint32_cached_byte_size; // 4 bytes + 4 bytes padding + MockRepeatedField packed_uint64; // 16 bytes + int packed_uint64_cached_byte_size; // 4 bytes + 4 bytes padding + MockRepeatedField packed_sint32; // 16 bytes + int packed_sint32_cached_byte_size; // 4 bytes + 4 bytes padding + MockRepeatedField packed_sint64; // 16 bytes + int packed_sint64_cached_byte_size; // 4 bytes + 4 bytes padding + MockRepeatedField packed_fixed32; // 16 bytes + MockRepeatedField packed_fixed64; // 16 bytes + MockRepeatedField packed_sfixed32; // 16 bytes + MockRepeatedField packed_sfixed64; // 16 bytes + MockRepeatedField packed_float; // 16 bytes + MockRepeatedField packed_double; // 16 bytes + MockRepeatedField packed_bool; // 16 bytes + MockRepeatedField packed_enum; // 16 bytes + int packed_enum_cached_byte_size; // 4 bytes + int cached_size; // 4 bytes + }; + GOOGLE_CHECK_MESSAGE_SIZE(MockGenerated, 16 * 15 + 8 * 6 + 8); + EXPECT_EQ(sizeof(protobuf_unittest::TestPackedTypes), sizeof(MockGenerated)); +} + +} // namespace cpp_unittest +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google
diff --git a/src/google/protobuf/compiler/cpp/metadata_test.cc b/src/google/protobuf/compiler/cpp/metadata_test.cc index c48a971..1ffd357 100644 --- a/src/google/protobuf/compiler/cpp/metadata_test.cc +++ b/src/google/protobuf/compiler/cpp/metadata_test.cc
@@ -32,13 +32,13 @@ #include <google/protobuf/testing/file.h> #include <google/protobuf/testing/file.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_generator.h> -#include <google/protobuf/compiler/annotation_test_util.h> +#include <google/protobuf/compiler/cpp/generator.h> #include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> +#include <google/protobuf/compiler/annotation_test_util.h> +#include <google/protobuf/compiler/cpp/helpers.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_move_unittest.cc b/src/google/protobuf/compiler/cpp/move_unittest.cc similarity index 100% rename from src/google/protobuf/compiler/cpp/cpp_move_unittest.cc rename to src/google/protobuf/compiler/cpp/move_unittest.cc
diff --git a/src/google/protobuf/compiler/cpp/cpp_names.h b/src/google/protobuf/compiler/cpp/names.h similarity index 95% rename from src/google/protobuf/compiler/cpp/cpp_names.h rename to src/google/protobuf/compiler/cpp/names.h index b27b596..7404ac5 100644 --- a/src/google/protobuf/compiler/cpp/cpp_names.h +++ b/src/google/protobuf/compiler/cpp/names.h
@@ -51,9 +51,9 @@ // // For example, if you had: // package foo.bar; -// message Baz { message Qux {} } +// message Baz { message Moo {} } // Then the non-qualified version would be: -// Baz_Qux +// Baz_Moo std::string ClassName(const Descriptor* descriptor); std::string ClassName(const EnumDescriptor* enum_descriptor); @@ -61,9 +61,9 @@ // // For example, if you had: // package foo.bar; -// message Baz { message Qux {} } -// Then the qualified ClassName for Qux would be: -// ::foo::bar::Baz_Qux +// message Baz { message Moo {} } +// Then the qualified ClassName for Moo would be: +// ::foo::bar::Baz_Moo std::string QualifiedClassName(const Descriptor* d); std::string QualifiedClassName(const EnumDescriptor* d); std::string QualifiedExtensionName(const FieldDescriptor* d);
diff --git a/src/google/protobuf/compiler/cpp/cpp_options.h b/src/google/protobuf/compiler/cpp/options.h similarity index 96% rename from src/google/protobuf/compiler/cpp/cpp_options.h rename to src/google/protobuf/compiler/cpp/options.h index c407c05..148866f 100644 --- a/src/google/protobuf/compiler/cpp/cpp_options.h +++ b/src/google/protobuf/compiler/cpp/options.h
@@ -79,9 +79,10 @@ bool opensource_runtime = false; bool annotate_accessor = false; bool unused_field_stripping = false; - bool unverified_lazy_message_sets = true; - bool eagerly_verified_lazy = true; + bool unverified_lazy_message_sets = false; + bool unverified_lazy = true; bool profile_driven_inline_string = true; + bool message_owned_arena_trial = false; bool force_split = false; #ifdef PROTOBUF_STABLE_EXPERIMENTS bool force_eagerly_verified_lazy = true;
diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc b/src/google/protobuf/compiler/cpp/padding_optimizer.cc similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc rename to src/google/protobuf/compiler/cpp/padding_optimizer.cc index f48ba71..2091052 100644 --- a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.cc +++ b/src/google/protobuf/compiler/cpp/padding_optimizer.cc
@@ -28,9 +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. -#include <google/protobuf/compiler/cpp/cpp_padding_optimizer.h> +#include <google/protobuf/compiler/cpp/padding_optimizer.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h b/src/google/protobuf/compiler/cpp/padding_optimizer.h similarity index 97% rename from src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h rename to src/google/protobuf/compiler/cpp/padding_optimizer.h index ebdb17d..9c76f38 100644 --- a/src/google/protobuf/compiler/cpp/cpp_padding_optimizer.h +++ b/src/google/protobuf/compiler/cpp/padding_optimizer.h
@@ -35,7 +35,7 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__ #define GOOGLE_PROTOBUF_COMPILER_CPP_PADDING_OPTIMIZER_H__ -#include <google/protobuf/compiler/cpp/cpp_message_layout_helper.h> +#include <google/protobuf/compiler/cpp/message_layout_helper.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc b/src/google/protobuf/compiler/cpp/parse_function_generator.cc similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc rename to src/google/protobuf/compiler/cpp/parse_function_generator.cc index f7dd629..41fc215 100644 --- a/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.cc +++ b/src/google/protobuf/compiler/cpp/parse_function_generator.cc
@@ -28,7 +28,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/cpp/cpp_parse_function_generator.h> +#include <google/protobuf/compiler/cpp/parse_function_generator.h> #include <algorithm> #include <limits> @@ -36,7 +36,7 @@ #include <utility> #include <google/protobuf/wire_format.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> namespace google { namespace protobuf { @@ -231,8 +231,7 @@ break; case FieldDescriptor::TYPE_ENUM: - if (field->is_repeated() && - !HasPreservingUnknownEnumSemantics(field)) { + if (field->is_repeated() && !HasPreservingUnknownEnumSemantics(field)) { // TODO(b/206890171): handle packed repeated closed enums // Non-packed repeated can be handled using tables, but we still // need to generate fallback code for all repeated enums in order to @@ -244,15 +243,15 @@ } break; - case FieldDescriptor::TYPE_BYTES: - case FieldDescriptor::TYPE_STRING: - if (IsStringInlined(field, options)) { - // TODO(b/198211897): support InilnedStringField. - handled = false; - } else { - handled = true; - } - break; + case FieldDescriptor::TYPE_BYTES: + case FieldDescriptor::TYPE_STRING: + if (IsStringInlined(field, options)) { + // TODO(b/198211897): support InilnedStringField. + handled = false; + } else { + handled = true; + } + break; case FieldDescriptor::TYPE_MESSAGE: case FieldDescriptor::TYPE_GROUP: @@ -291,8 +290,9 @@ GOOGLE_LOG_IF(DFATAL, ordered_fields.empty()) << "Invalid message: " << descriptor->full_name() << " has " << oneof_count << " oneof declarations, but no fields"; - aux_entries.push_back(StrCat( - "_fl::Offset{offsetof(", ClassName(descriptor), ", _oneof_case_)}")); + aux_entries.push_back(StrCat("_fl::Offset{offsetof(", + ClassName(descriptor), + ", _impl_._oneof_case_)}")); } // If this message has any inlined string fields, store the donation state @@ -301,7 +301,7 @@ aux_entries.resize(2); // pad if necessary aux_entries[1] = StrCat("_fl::Offset{offsetof(", ClassName(descriptor), - ", _inlined_string_donated_)}"); + ", _impl_._inlined_string_donated_)}"); } // Fill in mini table entries. @@ -444,7 +444,7 @@ inlined_string_indices, scc_analyzer)); } SetCommonVars(options_, &variables_); - SetCommonMessageDataVariables(&variables_); + SetCommonMessageDataVariables(descriptor_, &variables_); SetUnknownFieldsVariable(descriptor_, options_, &variables_); variables_["classname"] = ClassName(descriptor, false); } @@ -547,13 +547,13 @@ if (num_hasbits_ > 0) { // Sync hasbits - format("typed_msg->_has_bits_[0] = hasbits;\n"); + format("typed_msg->_impl_._has_bits_[0] = hasbits;\n"); } format("uint32_t tag = data.tag();\n"); format.Set("msg", "typed_msg->"); format.Set("this", "typed_msg"); - format.Set("has_bits", "typed_msg->_has_bits_"); + format.Set("has_bits", "typed_msg->_impl_._has_bits_"); format.Set("next_tag", "goto next_tag"); GenerateParseIterationBody(format, descriptor_, tc_table_info_->fallback_fields); @@ -649,7 +649,7 @@ format("_Internal::HasBits has_bits{};\n"); format.Set("has_bits", "has_bits"); } else { - format.Set("has_bits", "_has_bits_"); + format.Set("has_bits", "_impl_._has_bits_"); } format.Set("next_tag", "continue"); format("while (!ctx->Done(&ptr)) {\n"); @@ -665,7 +665,7 @@ format.Outdent(); format("message_done:\n"); - if (hasbits_size) format(" _has_bits_.Or(has_bits);\n"); + if (hasbits_size) format(" _impl_._has_bits_.Or(has_bits);\n"); format( " return ptr;\n" @@ -774,7 +774,7 @@ { auto header_scope = format.ScopedIndent(); if (num_hasbits_ > 0 || IsMapEntryMessage(descriptor_)) { - format("PROTOBUF_FIELD_OFFSET($classname$, _has_bits_),\n"); + format("PROTOBUF_FIELD_OFFSET($classname$, _impl_._has_bits_),\n"); } else { format("0, // no _has_bits_\n"); }
diff --git a/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.h b/src/google/protobuf/compiler/cpp/parse_function_generator.h similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_parse_function_generator.h rename to src/google/protobuf/compiler/cpp/parse_function_generator.h index d98f085..542a15a 100644 --- a/src/google/protobuf/compiler/cpp/cpp_parse_function_generator.h +++ b/src/google/protobuf/compiler/cpp/parse_function_generator.h
@@ -38,8 +38,8 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/wire_format_lite.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc b/src/google/protobuf/compiler/cpp/plugin_unittest.cc similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc rename to src/google/protobuf/compiler/cpp/plugin_unittest.cc index 5bc419d..f023dcf 100644 --- a/src/google/protobuf/compiler/cpp/cpp_plugin_unittest.cc +++ b/src/google/protobuf/compiler/cpp/plugin_unittest.cc
@@ -38,7 +38,7 @@ #include <google/protobuf/testing/file.h> #include <google/protobuf/testing/file.h> -#include <google/protobuf/compiler/cpp/cpp_generator.h> +#include <google/protobuf/compiler/cpp/generator.h> #include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> @@ -198,7 +198,7 @@ " ctype = CORD\n" " ];\n" "\n" - " oneof Qux {\n" + " oneof Moo {\n" " int64 oneOfInt = 20;\n" " string oneOfString = 21;\n" " Baz oneOfMessage = 22;\n"
diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc b/src/google/protobuf/compiler/cpp/primitive_field.cc similarity index 90% rename from src/google/protobuf/compiler/cpp/cpp_primitive_field.cc rename to src/google/protobuf/compiler/cpp/primitive_field.cc index cef623c..9ffbe76 100644 --- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc +++ b/src/google/protobuf/compiler/cpp/primitive_field.cc
@@ -32,12 +32,12 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_primitive_field.h> +#include <google/protobuf/compiler/cpp/primitive_field.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> namespace google { namespace protobuf { @@ -186,12 +186,6 @@ format("swap($field$, other->$field$);\n"); } -void PrimitiveFieldGenerator::GenerateConstructorCode( - io::Printer* printer) const { - Formatter format(printer, variables_); - format("$field$ = $default$;\n"); -} - void PrimitiveFieldGenerator::GenerateCopyConstructorCode( io::Printer* printer) const { Formatter format(printer, variables_); @@ -230,10 +224,22 @@ } } -void PrimitiveFieldGenerator::GenerateConstinitInitializer( +void PrimitiveFieldGenerator::GenerateConstexprAggregateInitializer( io::Printer* printer) const { Formatter format(printer, variables_); - format("$name$_($default$)"); + format("/*decltype($field$)*/$default$"); +} + +void PrimitiveFieldGenerator::GenerateAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){$default$}"); +} + +void PrimitiveFieldGenerator::GenerateCopyAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){}"); } // =================================================================== @@ -407,6 +413,12 @@ format("$field$.InternalSwap(&other->$field$);\n"); } +void RepeatedPrimitiveFieldGenerator::GenerateDestructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$field$.~RepeatedField();\n"); +} + void RepeatedPrimitiveFieldGenerator::GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const { Formatter format(printer, variables_); @@ -460,7 +472,8 @@ format( "if (data_size > 0) {\n" " total_size += $tag_size$ +\n" - " ::_pbi::WireFormatLite::Int32Size(static_cast<$int32$>(data_size));\n" + " " + "::_pbi::WireFormatLite::Int32Size(static_cast<$int32$>(data_size));\n" "}\n"); if (FixedSize(descriptor_->type()) == -1) { format( @@ -480,13 +493,37 @@ format("}\n"); } -void RepeatedPrimitiveFieldGenerator::GenerateConstinitInitializer( +void RepeatedPrimitiveFieldGenerator::GenerateConstexprAggregateInitializer( io::Printer* printer) const { Formatter format(printer, variables_); - format("$name$_()"); + format("/*decltype($field$)*/{}"); if (descriptor_->is_packed() && FixedSize(descriptor_->type()) == -1 && HasGeneratedMethods(descriptor_->file(), options_)) { - format("\n, $cached_byte_size_name$(0)"); + format("\n, /*decltype($cached_byte_size_field$)*/{0}"); + } +} + +void RepeatedPrimitiveFieldGenerator::GenerateAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){arena}"); + if (descriptor_->is_packed() && FixedSize(descriptor_->type()) == -1 && + HasGeneratedMethods(descriptor_->file(), options_)) { + // std::atomic has no move constructor, which prevents explicit aggregate + // initialization pre-C++17. + format("\n, /*decltype($cached_byte_size_field$)*/{0}"); + } +} + +void RepeatedPrimitiveFieldGenerator::GenerateCopyAggregateInitializer( + io::Printer* printer) const { + + Formatter format(printer, variables_); + format("decltype($field$){from.$field$}"); + if (descriptor_->is_packed() && FixedSize(descriptor_->type()) == -1 && + HasGeneratedMethods(descriptor_->file(), options_)) { + // std::atomic has no move constructor. + format("\n, /*decltype($cached_byte_size_field$)*/{0}"); } }
diff --git a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h b/src/google/protobuf/compiler/cpp/primitive_field.h similarity index 89% rename from src/google/protobuf/compiler/cpp/cpp_primitive_field.h rename to src/google/protobuf/compiler/cpp/primitive_field.h index 77ac598..ec1fcc1 100644 --- a/src/google/protobuf/compiler/cpp/cpp_primitive_field.h +++ b/src/google/protobuf/compiler/cpp/primitive_field.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/cpp/cpp_field.h> +#include <google/protobuf/compiler/cpp/field.h> namespace google { namespace protobuf { @@ -58,12 +58,15 @@ void GenerateClearingCode(io::Printer* printer) const override; void GenerateMergingCode(io::Printer* printer) const override; void GenerateSwappingCode(io::Printer* printer) const override; - void GenerateConstructorCode(io::Printer* printer) const override; + void GenerateConstructorCode(io::Printer* printer) const override {} void GenerateCopyConstructorCode(io::Printer* printer) const override; void GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; + void GenerateConstexprAggregateInitializer( + io::Printer* printer) const override; + void GenerateAggregateInitializer(io::Printer* printer) const override; + void GenerateCopyAggregateInitializer(io::Printer* printer) const override; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); @@ -100,10 +103,14 @@ void GenerateSwappingCode(io::Printer* printer) const override; void GenerateConstructorCode(io::Printer* printer) const override {} void GenerateCopyConstructorCode(io::Printer* printer) const override {} + void GenerateDestructorCode(io::Printer* printer) const override; void GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; + void GenerateConstexprAggregateInitializer( + io::Printer* printer) const override; + void GenerateAggregateInitializer(io::Printer* printer) const override; + void GenerateCopyAggregateInitializer(io::Printer* printer) const override; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator);
diff --git a/src/google/protobuf/compiler/cpp/cpp_service.cc b/src/google/protobuf/compiler/cpp/service.cc similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_service.cc rename to src/google/protobuf/compiler/cpp/service.cc index c630e7f..7a0d480 100644 --- a/src/google/protobuf/compiler/cpp/cpp_service.cc +++ b/src/google/protobuf/compiler/cpp/service.cc
@@ -32,11 +32,11 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_service.h> +#include <google/protobuf/compiler/cpp/service.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_service.h b/src/google/protobuf/compiler/cpp/service.h similarity index 98% rename from src/google/protobuf/compiler/cpp/cpp_service.h rename to src/google/protobuf/compiler/cpp/service.h index 8b210af..b3bd2d7 100644 --- a/src/google/protobuf/compiler/cpp/cpp_service.h +++ b/src/google/protobuf/compiler/cpp/service.h
@@ -39,7 +39,7 @@ #include <string> #include <google/protobuf/descriptor.h> -#include <google/protobuf/compiler/cpp/cpp_options.h> +#include <google/protobuf/compiler/cpp/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.cc b/src/google/protobuf/compiler/cpp/string_field.cc similarity index 96% rename from src/google/protobuf/compiler/cpp/cpp_string_field.cc rename to src/google/protobuf/compiler/cpp/string_field.cc index 41daed2..8974b6a 100644 --- a/src/google/protobuf/compiler/cpp/cpp_string_field.cc +++ b/src/google/protobuf/compiler/cpp/string_field.cc
@@ -32,11 +32,11 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/cpp/cpp_string_field.h> +#include <google/protobuf/compiler/cpp/string_field.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/cpp/cpp_helpers.h> +#include <google/protobuf/compiler/cpp/helpers.h> #include <google/protobuf/descriptor.pb.h> @@ -118,7 +118,7 @@ // // `_init_inline_xxx` is used for initializing default instances. format( - "union { ::$proto_ns$::internal::InlinedStringField $name$_; };\n" + "::$proto_ns$::internal::InlinedStringField $name$_;\n" "static std::true_type _init_inline_$name$_;\n"); } } @@ -522,22 +522,38 @@ " this->_internal_$name$());\n"); } -void StringFieldGenerator::GenerateConstinitInitializer( +void StringFieldGenerator::GenerateConstexprAggregateInitializer( io::Printer* printer) const { Formatter format(printer, variables_); if (inlined_) { - format("$name$_(nullptr, false)"); + format("/*decltype($field$)*/{nullptr, false}"); return; } if (descriptor_->default_value_string().empty()) { format( - "$name$_(&::_pbi::fixed_address_empty_string, " - "::_pbi::ConstantInitialized{})"); + "/*decltype($field$)*/{&::_pbi::fixed_address_empty_string, " + "::_pbi::ConstantInitialized{}}"); } else { - format("$name$_(nullptr, ::_pbi::ConstantInitialized{})"); + format("/*decltype($field$)*/{nullptr, ::_pbi::ConstantInitialized{}}"); } } +void StringFieldGenerator::GenerateAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + if (!inlined_) { + format("decltype($field$){}"); + } else { + format("decltype($field$)(arena)"); + } +} + +void StringFieldGenerator::GenerateCopyAggregateInitializer( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("decltype($field$){}"); +} + // =================================================================== StringOneofFieldGenerator::StringOneofFieldGenerator( @@ -867,6 +883,12 @@ format("$field$.InternalSwap(&other->$field$);\n"); } +void RepeatedStringFieldGenerator::GenerateDestructorCode( + io::Printer* printer) const { + Formatter format(printer, variables_); + format("$field$.~RepeatedPtrField();\n"); +} + void RepeatedStringFieldGenerator::GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const { Formatter format(printer, variables_); @@ -899,12 +921,6 @@ "}\n"); } -void RepeatedStringFieldGenerator::GenerateConstinitInitializer( - io::Printer* printer) const { - Formatter format(printer, variables_); - format("$name$_()"); -} - } // namespace cpp } // namespace compiler } // namespace protobuf
diff --git a/src/google/protobuf/compiler/cpp/cpp_string_field.h b/src/google/protobuf/compiler/cpp/string_field.h similarity index 94% rename from src/google/protobuf/compiler/cpp/cpp_string_field.h rename to src/google/protobuf/compiler/cpp/string_field.h index 845bf07..0de0573 100644 --- a/src/google/protobuf/compiler/cpp/cpp_string_field.h +++ b/src/google/protobuf/compiler/cpp/string_field.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/cpp/cpp_field.h> +#include <google/protobuf/compiler/cpp/field.h> namespace google { namespace protobuf { @@ -69,7 +69,10 @@ void GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; + void GenerateConstexprAggregateInitializer( + io::Printer* printer) const override; + void GenerateAggregateInitializer(io::Printer* printer) const override; + void GenerateCopyAggregateInitializer(io::Printer* printer) const override; bool IsInlined() const override { return inlined_; } ArenaDtorNeeds NeedsArenaDestructor() const override; @@ -113,10 +116,10 @@ void GenerateSwappingCode(io::Printer* printer) const override; void GenerateConstructorCode(io::Printer* printer) const override {} void GenerateCopyConstructorCode(io::Printer* printer) const override {} + void GenerateDestructorCode(io::Printer* printer) const override; void GenerateSerializeWithCachedSizesToArray( io::Printer* printer) const override; void GenerateByteSize(io::Printer* printer) const override; - void GenerateConstinitInitializer(io::Printer* printer) const override; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedStringFieldGenerator);
diff --git a/src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto b/src/google/protobuf/compiler/cpp/test_bad_identifiers.proto similarity index 100% rename from src/google/protobuf/compiler/cpp/cpp_test_bad_identifiers.proto rename to src/google/protobuf/compiler/cpp/test_bad_identifiers.proto
diff --git a/src/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto b/src/google/protobuf/compiler/cpp/test_large_enum_value.proto similarity index 100% rename from src/google/protobuf/compiler/cpp/cpp_test_large_enum_value.proto rename to src/google/protobuf/compiler/cpp/test_large_enum_value.proto
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.cc b/src/google/protobuf/compiler/cpp/unittest.cc similarity index 97% rename from src/google/protobuf/compiler/cpp/cpp_unittest.cc rename to src/google/protobuf/compiler/cpp/unittest.cc index 74310a7..e2730d7 100644 --- a/src/google/protobuf/compiler/cpp/cpp_unittest.cc +++ b/src/google/protobuf/compiler/cpp/unittest.cc
@@ -44,12 +44,11 @@ // 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 <google/protobuf/compiler/cpp/unittest.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_embed_optimize_for.pb.h> #include <google/protobuf/unittest_optimize_for.pb.h> - #include <google/protobuf/test_util.h> #define MESSAGE_TEST_NAME MessageTest @@ -65,7 +64,7 @@ #define UNITTEST_IMPORT ::protobuf_unittest_import // Must include after the above macros. -#include <google/protobuf/compiler/cpp/cpp_unittest.inc> +#include <google/protobuf/compiler/cpp/unittest.inc> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.h b/src/google/protobuf/compiler/cpp/unittest.h similarity index 100% rename from src/google/protobuf/compiler/cpp/cpp_unittest.h rename to src/google/protobuf/compiler/cpp/unittest.h
diff --git a/src/google/protobuf/compiler/cpp/cpp_unittest.inc b/src/google/protobuf/compiler/cpp/unittest.inc similarity index 96% rename from src/google/protobuf/compiler/cpp/cpp_unittest.inc rename to src/google/protobuf/compiler/cpp/unittest.inc index cfaa8df..0b47176 100644 --- a/src/google/protobuf/compiler/cpp/cpp_unittest.inc +++ b/src/google/protobuf/compiler/cpp/unittest.inc
@@ -49,25 +49,25 @@ #include <memory> #include <vector> -#include <google/protobuf/compiler/cpp/cpp_unittest.h> +#include <google/protobuf/compiler/cpp/unittest.h> #include <google/protobuf/stubs/strutil.h> -#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) -// We exclude this large proto from cmake build because it's too large for +#ifndef _MSC_VER +// We exclude this large proto because it's too large for // visual studio to compile (report internal errors). #include <google/protobuf/unittest_enormous_descriptor.pb.h> #endif -#include <google/protobuf/compiler/cpp/cpp_helpers.h> -#include <google/protobuf/compiler/cpp/cpp_test_bad_identifiers.pb.h> -#include <google/protobuf/compiler/scc.h> -#include <google/protobuf/compiler/importer.h> -#include <google/protobuf/test_util2.h> +#include <google/protobuf/compiler/cpp/helpers.h> +#include <google/protobuf/compiler/cpp/test_bad_identifiers.pb.h> #include <google/protobuf/unittest_no_generic_services.pb.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/arena.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/dynamic_message.h> +#include <google/protobuf/compiler/scc.h> +#include <google/protobuf/compiler/importer.h> +#include <google/protobuf/io/coded_stream.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/test_util2.h> #include <google/protobuf/stubs/callback.h> #include <google/protobuf/stubs/common.h> @@ -138,7 +138,7 @@ generated_descriptor_proto.DebugString()); } -#if !defined(GOOGLE_PROTOBUF_CMAKE_BUILD) && !defined(_MSC_VER) +#ifndef _MSC_VER // Test that generated code has proper descriptors: // Touch a descriptor generated from an enormous message to validate special // handling for descriptors exceeding the C++ standard's recommended minimum @@ -339,19 +339,6 @@ TestUtil::SetAllFields(&message); message.Clear(); TestUtil::ExpectClear(message); - - // Unlike with the defaults test, we do NOT expect that requesting embedded - // messages will return a pointer to the default instance. Instead, they - // should return the objects that were created when mutable_blah() was - // called. - EXPECT_NE(&UNITTEST::TestAllTypes::OptionalGroup::default_instance(), - &message.optionalgroup()); - EXPECT_NE(&UNITTEST::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - EXPECT_NE(&UNITTEST::ForeignMessage::default_instance(), - &message.optional_foreign_message()); - EXPECT_NE(&UNITTEST_IMPORT::ImportMessage::default_instance(), - &message.optional_import_message()); } TEST(GENERATED_MESSAGE_TEST_NAME, EmbeddedNullsInBytesCharStar) { @@ -406,6 +393,7 @@ } +#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || defined(NDEBUG) TEST(GENERATED_MESSAGE_TEST_NAME, CopyFrom) { UNITTEST::TestAllTypes message1, message2; @@ -418,6 +406,20 @@ TestUtil::ExpectAllFieldsSet(message2); } +TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) { + UNITTEST::TestAllTypes message1; + TestUtil::SetAllFields(&message1); + + UNITTEST::TestAllTypes message2; + message2 = message1; + TestUtil::ExpectAllFieldsSet(message2); + + // Make sure that self-assignment does something sane. + message2.operator=(message2); + TestUtil::ExpectAllFieldsSet(message2); +} +#endif // !PROTOBUF_TEST_NO_DESCRIPTORS || NDEBUG + TEST(GENERATED_MESSAGE_TEST_NAME, SwapWithEmpty) { UNITTEST::TestAllTypes message1, message2; @@ -503,6 +505,9 @@ // Note the address of one of the repeated fields, to verify it was swapped // rather than copied. const int32_t* addr = &message1.repeated_int32().Get(0); +#ifdef PROTOBUF_FORCE_COPY_IN_SWAP + const int32_t value = *addr; +#endif using std::swap; swap(message1, message2); @@ -512,7 +517,7 @@ #ifdef PROTOBUF_FORCE_COPY_IN_SWAP EXPECT_NE(addr, &message2.repeated_int32().Get(0)); - EXPECT_EQ(*addr, message2.repeated_int32().Get(0)); + EXPECT_EQ(value, message2.repeated_int32().Get(0)); #else EXPECT_EQ(addr, &message2.repeated_int32().Get(0)); #endif @@ -589,20 +594,7 @@ TestUtil::ExpectAllFieldsSet(*message2_heap); } -TEST(GENERATED_MESSAGE_TEST_NAME, CopyAssignmentOperator) { - UNITTEST::TestAllTypes message1; - TestUtil::SetAllFields(&message1); - - UNITTEST::TestAllTypes message2; - message2 = message1; - TestUtil::ExpectAllFieldsSet(message2); - - // Make sure that self-assignment does something sane. - message2.operator=(message2); - TestUtil::ExpectAllFieldsSet(message2); -} - -#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI +#ifndef PROTOBUF_TEST_NO_DESCRIPTORS TEST(GENERATED_MESSAGE_TEST_NAME, UpcastCopyFrom) { // Test the CopyFrom method that takes in the generic const Message& // parameter. @@ -615,9 +607,6 @@ TestUtil::ExpectAllFieldsSet(message2); } -#endif - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS TEST(GENERATED_MESSAGE_TEST_NAME, DynamicMessageCopyFrom) { // Test copying from a DynamicMessage, which must fall back to using @@ -834,7 +823,7 @@ message.mutable_messagefield()->set_c(6); message.add_repeatedprimitivefield(8); - message.add_repeatedstringfield("qux"); + message.add_repeatedstringfield("moo"); message.add_repeatedenumfield(UNITTEST::FOREIGN_BAR); message.add_repeatedmessagefield()->set_c(15); @@ -844,7 +833,7 @@ EXPECT_EQ(6, message.messagefield().c()); EXPECT_EQ(8, message.repeatedprimitivefield(0)); - EXPECT_EQ("qux", message.repeatedstringfield(0)); + EXPECT_EQ("moo", message.repeatedstringfield(0)); EXPECT_EQ(UNITTEST::FOREIGN_BAR, message.repeatedenumfield(0)); EXPECT_EQ(15, message.repeatedmessagefield(0).c()); } @@ -959,7 +948,6 @@ #endif // !PROTOBUF_TEST_NO_DESCRIPTORS - TEST(GENERATED_MESSAGE_TEST_NAME, FieldConstantValues) { UNITTEST::TestRequired message; EXPECT_EQ(UNITTEST::TestAllTypes_NestedMessage::kBbFieldNumber, 1); @@ -1484,7 +1472,7 @@ TestUtil::ExpectAtMostOneFieldSetInOneof(message); - message.set_foo_bytes("qux"); + message.set_foo_bytes("moo"); EXPECT_TRUE(message.has_foo_bytes()); TestUtil::ExpectAtMostOneFieldSetInOneof(message); @@ -1492,7 +1480,7 @@ EXPECT_TRUE(message.has_foo_enum()); TestUtil::ExpectAtMostOneFieldSetInOneof(message); - message.mutable_foo_message()->set_qux_int(234); + message.mutable_foo_message()->set_moo_int(234); EXPECT_TRUE(message.has_foo_message()); TestUtil::ExpectAtMostOneFieldSetInOneof(message); @@ -1515,11 +1503,11 @@ ExpectEnumCasesWork(message); message.set_foo_string("foo"); ExpectEnumCasesWork(message); - message.set_foo_bytes("qux"); + message.set_foo_bytes("moo"); ExpectEnumCasesWork(message); message.set_foo_enum(UNITTEST::TestOneof2::FOO); ExpectEnumCasesWork(message); - message.mutable_foo_message()->set_qux_int(234); + message.mutable_foo_message()->set_moo_int(234); ExpectEnumCasesWork(message); message.mutable_foogroup()->set_a(345); ExpectEnumCasesWork(message); @@ -1569,15 +1557,15 @@ EXPECT_FALSE(message.has_foo_string()); - message.set_foo_string("qux", 3); + message.set_foo_string("moo", 3); EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "qux"); + EXPECT_EQ(message.foo_string(), "moo"); message.clear_foo_string(); EXPECT_FALSE(message.has_foo_string()); - message.mutable_foo_string()->assign("quux"); + message.mutable_foo_string()->assign("mooo"); EXPECT_TRUE(message.has_foo_string()); - EXPECT_EQ(message.foo_string(), "quux"); + EXPECT_EQ(message.foo_string(), "mooo"); message.clear_foo_string(); EXPECT_FALSE(message.has_foo_string()); @@ -1653,11 +1641,11 @@ // Unset field returns default instance EXPECT_EQ(&message.foo_message(), &UNITTEST::TestOneof2_NestedMessage::default_instance()); - EXPECT_EQ(message.foo_message().qux_int(), 0); + EXPECT_EQ(message.foo_message().moo_int(), 0); - message.mutable_foo_message()->set_qux_int(234); + message.mutable_foo_message()->set_moo_int(234); EXPECT_TRUE(message.has_foo_message()); - EXPECT_EQ(message.foo_message().qux_int(), 234); + EXPECT_EQ(message.foo_message().moo_int(), 234); message.clear_foo_message(); EXPECT_FALSE(message.has_foo_message()); } @@ -1670,13 +1658,13 @@ EXPECT_EQ(nullptr, message.release_foo_message()); EXPECT_FALSE(message.has_foo_message()); - message.mutable_foo_message()->set_qux_int(1); + message.mutable_foo_message()->set_moo_int(1); EXPECT_TRUE(message.has_foo_message()); std::unique_ptr<UNITTEST::TestOneof2_NestedMessage> mes( message.release_foo_message()); EXPECT_FALSE(message.has_foo_message()); ASSERT_TRUE(mes != nullptr); - EXPECT_EQ(1, mes->qux_int()); + EXPECT_EQ(1, mes->moo_int()); EXPECT_EQ(nullptr, message.release_foo_message()); EXPECT_FALSE(message.has_foo_message()); @@ -1688,7 +1676,7 @@ EXPECT_FALSE(message.has_foo_message()); - message.mutable_foo_message()->set_qux_int(1); + message.mutable_foo_message()->set_moo_int(1); EXPECT_TRUE(message.has_foo_message()); message.set_allocated_foo_message(nullptr); @@ -1696,14 +1684,14 @@ EXPECT_EQ(&message.foo_message(), &UNITTEST::TestOneof2_NestedMessage::default_instance()); - message.mutable_foo_message()->set_qux_int(1); + message.mutable_foo_message()->set_moo_int(1); UNITTEST::TestOneof2_NestedMessage* mes = message.release_foo_message(); ASSERT_TRUE(mes != nullptr); EXPECT_FALSE(message.has_foo_message()); message.set_allocated_foo_message(mes); EXPECT_TRUE(message.has_foo_message()); - EXPECT_EQ(1, message.foo_message().qux_int()); + EXPECT_EQ(1, message.foo_message().moo_int()); } @@ -1733,7 +1721,7 @@ EXPECT_EQ(message.foo_enum(), 1); EXPECT_FALSE(message.has_foo_message()); - EXPECT_EQ(message.foo_message().qux_int(), 0); + EXPECT_EQ(message.foo_message().moo_int(), 0); EXPECT_FALSE(message.has_foogroup()); EXPECT_EQ(message.foogroup().a(), 0); @@ -1777,14 +1765,14 @@ message1.set_foo_string("FOO"); EXPECT_TRUE(message1.has_foo_string()); - message2.mutable_foo_message()->set_qux_int(1); + message2.mutable_foo_message()->set_moo_int(1); EXPECT_TRUE(message2.has_foo_message()); message1.Swap(&message2); EXPECT_FALSE(message1.has_foo_string()); EXPECT_FALSE(message2.has_foo_message()); EXPECT_TRUE(message1.has_foo_message()); - EXPECT_EQ(message1.foo_message().qux_int(), 1); + EXPECT_EQ(message1.foo_message().moo_int(), 1); EXPECT_TRUE(message2.has_foo_string()); EXPECT_EQ(message2.foo_string(), "FOO"); } @@ -1815,16 +1803,16 @@ TEST_F(OneofTest, CopyAssignmentOperator) { UNITTEST::TestOneof2 message1; - message1.mutable_foo_message()->set_qux_int(123); + message1.mutable_foo_message()->set_moo_int(123); EXPECT_TRUE(message1.has_foo_message()); UNITTEST::TestOneof2 message2; message2 = message1; - EXPECT_EQ(message2.foo_message().qux_int(), 123); + EXPECT_EQ(message2.foo_message().moo_int(), 123); // Make sure that self-assignment does something sane. message2 = *&message2; // Avoid -Wself-assign. - EXPECT_EQ(message2.foo_message().qux_int(), 123); + EXPECT_EQ(message2.foo_message().moo_int(), 123); } TEST_F(OneofTest, UpcastCopyFrom) { @@ -1879,14 +1867,14 @@ { UNITTEST::TestOneof2 message1, message2; std::string data; - message1.set_foo_bytes("qux"); + message1.set_foo_bytes("moo"); int size = message1.ByteSizeLong(); data.resize(size); uint8_t* start = reinterpret_cast<uint8_t*>(::google::protobuf::string_as_array(&data)); uint8_t* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_bytes(), "qux"); + EXPECT_EQ(message2.foo_bytes(), "moo"); } // Enum @@ -1907,14 +1895,14 @@ { UNITTEST::TestOneof2 message1, message2; std::string data; - message1.mutable_foo_message()->set_qux_int(234); + message1.mutable_foo_message()->set_moo_int(234); int size = message1.ByteSizeLong(); data.resize(size); uint8_t* start = reinterpret_cast<uint8_t*>(::google::protobuf::string_as_array(&data)); uint8_t* end = message1.SerializeWithCachedSizesToArray(start); EXPECT_EQ(size, end - start); EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_message().qux_int(), 234); + EXPECT_EQ(message2.foo_message().moo_int(), 234); } // Group @@ -1986,7 +1974,7 @@ { UNITTEST::TestOneof2 message1, message2; std::string data; - message1.set_foo_bytes("qux"); + message1.set_foo_bytes("moo"); int size = message1.ByteSizeLong(); data.resize(size); @@ -2000,7 +1988,7 @@ } EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_bytes(), "qux"); + EXPECT_EQ(message2.foo_bytes(), "moo"); } // Enum @@ -2028,7 +2016,7 @@ { UNITTEST::TestOneof2 message1, message2; std::string data; - message1.mutable_foo_message()->set_qux_int(234); + message1.mutable_foo_message()->set_moo_int(234); int size = message1.ByteSizeLong(); data.resize(size); @@ -2042,7 +2030,7 @@ } EXPECT_TRUE(message2.ParseFromString(data)); - EXPECT_EQ(message2.foo_message().qux_int(), 234); + EXPECT_EQ(message2.foo_message().moo_int(), 234); } // Group @@ -2084,11 +2072,11 @@ EXPECT_EQ(message2.foo_string(), "foo"); - message1.set_foo_bytes("qux"); + message1.set_foo_bytes("moo"); message2.MergeFrom(message1); TestUtil::ExpectAtMostOneFieldSetInOneof(message2); EXPECT_TRUE(message2.has_foo_bytes()); - EXPECT_EQ(message2.foo_bytes(), "qux"); + EXPECT_EQ(message2.foo_bytes(), "moo"); message1.set_foo_enum(UNITTEST::TestOneof2::FOO); message2.MergeFrom(message1); @@ -2096,11 +2084,11 @@ EXPECT_TRUE(message2.has_foo_enum()); EXPECT_EQ(message2.foo_enum(), UNITTEST::TestOneof2::FOO); - message1.mutable_foo_message()->set_qux_int(234); + message1.mutable_foo_message()->set_moo_int(234); message2.MergeFrom(message1); TestUtil::ExpectAtMostOneFieldSetInOneof(message2); EXPECT_TRUE(message2.has_foo_message()); - EXPECT_EQ(message2.foo_message().qux_int(), 234); + EXPECT_EQ(message2.foo_message().moo_int(), 234); message1.mutable_foogroup()->set_a(345); message2.MergeFrom(message1);
diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc index 186fa27..55fb60c 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc
@@ -109,7 +109,7 @@ printer->Print( variables_, "$oneof_name$_ = input.ReadEnum();\n" - "$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); + "$oneof_name$Case_ = $oneof_property_name$OneofCase.$oneof_case_name$;\n"); } void EnumOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) {
diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc index 146ca9e..17847e3 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc
@@ -130,8 +130,9 @@ } else { (*variables)["has_property_check"] = oneof_name() + "Case_ == " + oneof_property_name() + - "OneofCase." + property_name(); + "OneofCase." + oneof_case_name(); } + (*variables)["oneof_case_name"] = oneof_case_name(); (*variables)["oneof_property_name"] = oneof_property_name(); } @@ -187,6 +188,10 @@ WriteGeneratedCodeAttributes(printer); } +std::string FieldGeneratorBase::oneof_case_name() { + return GetOneofCaseName(descriptor_); +} + std::string FieldGeneratorBase::oneof_property_name() { return UnderscoresToCamelCase(descriptor_->containing_oneof()->name(), true); }
diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.h b/src/google/protobuf/compiler/csharp/csharp_field_base.h index f875fa1..c7b7469 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.h +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.h
@@ -85,6 +85,7 @@ std::map<std::string, std::string>* variables); std::string oneof_property_name(); + std::string oneof_case_name(); std::string oneof_name(); std::string property_name(); std::string name();
diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.cc b/src/google/protobuf/compiler/csharp/csharp_helpers.cc index 32ef399..73ca868 100644 --- a/src/google/protobuf/compiler/csharp/csharp_helpers.cc +++ b/src/google/protobuf/compiler/csharp/csharp_helpers.cc
@@ -393,6 +393,13 @@ return property_name; } +std::string GetOneofCaseName(const FieldDescriptor* descriptor) { + // The name in a oneof case enum is the same as for the property, but as we always have a "None" + // value as well, we need to reserve that by appending an underscore. + std::string property_name = GetPropertyName(descriptor); + return property_name == "None" ? "None_" : property_name; +} + std::string GetOutputFile(const FileDescriptor* descriptor, const std::string file_extension, const bool generate_directories,
diff --git a/src/google/protobuf/compiler/csharp/csharp_helpers.h b/src/google/protobuf/compiler/csharp/csharp_helpers.h index 619e7db..836bd5d 100644 --- a/src/google/protobuf/compiler/csharp/csharp_helpers.h +++ b/src/google/protobuf/compiler/csharp/csharp_helpers.h
@@ -87,6 +87,8 @@ std::string GetPropertyName(const FieldDescriptor* descriptor); +std::string GetOneofCaseName(const FieldDescriptor* descriptor); + int GetFixedSize(FieldDescriptor::Type type); std::string UnderscoresToCamelCase(const std::string& input,
diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc index 9dbce03..a119bdd 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message.cc
@@ -238,8 +238,8 @@ printer->Print("None = 0,\n"); 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), + printer->Print("$oneof_case_name$ = $index$,\n", + "oneof_case_name", GetOneofCaseName(field), "index", StrCat(field->number())); } printer->Outdent(); @@ -403,10 +403,10 @@ 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); + vars["oneof_case_name"] = GetOneofCaseName(field); printer->Print( vars, - "case $property_name$OneofCase.$field_property_name$:\n"); + "case $property_name$OneofCase.$oneof_case_name$:\n"); printer->Indent(); generator->GenerateCloningCode(printer); printer->Print("break;\n"); @@ -635,10 +635,10 @@ printer->Indent(); for (int j = 0; j < oneof->field_count(); j++) { const FieldDescriptor* field = oneof->field(j); - vars["field_property_name"] = GetPropertyName(field); + vars["oneof_case_name"] = GetOneofCaseName(field); printer->Print( vars, - "case $property_name$OneofCase.$field_property_name$:\n"); + "case $property_name$OneofCase.$oneof_case_name$:\n"); printer->Indent(); std::unique_ptr<FieldGeneratorBase> generator(CreateFieldGeneratorInternal(field)); generator->GenerateMergingCode(printer);
diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc index 034fbd9..487d01d 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc
@@ -225,7 +225,7 @@ " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : null; }\n" " set {\n" " $oneof_name$_ = value;\n" - " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$oneof_case_name$;\n" " }\n" "}\n"); if (SupportsPresenceApi(descriptor_)) { @@ -236,7 +236,7 @@ printer->Print( variables_, "$access_level$ bool Has$property_name$ {\n" - " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$oneof_case_name$; }\n" "}\n"); printer->Print( variables_,
diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index 9df1dd6..e7d5116 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc
@@ -296,7 +296,7 @@ } printer->Print( variables_, - " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$oneof_case_name$;\n" " }\n" "}\n"); if (SupportsPresenceApi(descriptor_)) { @@ -307,7 +307,7 @@ printer->Print( variables_, "$access_level$ bool Has$property_name$ {\n" - " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$oneof_case_name$; }\n" "}\n"); printer->Print( variables_,
diff --git a/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc b/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc index 578f54b..e638dd8 100644 --- a/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc
@@ -233,7 +233,7 @@ " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : ($type_name$) null; }\n" " set {\n" " $oneof_name$_ = value;\n" - " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$oneof_case_name$;\n" " }\n" "}\n"); if (SupportsPresenceApi(descriptor_)) { @@ -244,7 +244,7 @@ printer->Print( variables_, "$access_level$ bool Has$property_name$ {\n" - " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$property_name$; }\n" + " get { return $oneof_name$Case_ == $oneof_property_name$OneofCase.$oneof_case_name$; }\n" "}\n"); printer->Print( variables_,
diff --git a/src/google/protobuf/compiler/java/java_context.cc b/src/google/protobuf/compiler/java/context.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_context.cc rename to src/google/protobuf/compiler/java/context.cc index 19cb631..cdc0d44 100644 --- a/src/google/protobuf/compiler/java/java_context.cc +++ b/src/google/protobuf/compiler/java/context.cc
@@ -28,13 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/java/java_context.h> +#include <google/protobuf/compiler/java/context.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_field.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/compiler/java/field.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> #include <google/protobuf/stubs/map_util.h> namespace google {
diff --git a/src/google/protobuf/compiler/java/java_context.h b/src/google/protobuf/compiler/java/context.h similarity index 98% rename from src/google/protobuf/compiler/java/java_context.h rename to src/google/protobuf/compiler/java/context.h index 3fa6af1..c224ab7 100644 --- a/src/google/protobuf/compiler/java/java_context.h +++ b/src/google/protobuf/compiler/java/context.h
@@ -36,7 +36,7 @@ #include <vector> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/java/java_options.h> +#include <google/protobuf/compiler/java/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_doc_comment.cc b/src/google/protobuf/compiler/java/doc_comment.cc similarity index 99% rename from src/google/protobuf/compiler/java/java_doc_comment.cc rename to src/google/protobuf/compiler/java/doc_comment.cc index d0e0184..066bff6 100644 --- a/src/google/protobuf/compiler/java/java_doc_comment.cc +++ b/src/google/protobuf/compiler/java/doc_comment.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_doc_comment.h> +#include <google/protobuf/compiler/java/doc_comment.h> #include <vector>
diff --git a/src/google/protobuf/compiler/java/java_doc_comment.h b/src/google/protobuf/compiler/java/doc_comment.h similarity index 100% rename from src/google/protobuf/compiler/java/java_doc_comment.h rename to src/google/protobuf/compiler/java/doc_comment.h
diff --git a/src/google/protobuf/compiler/java/java_doc_comment_unittest.cc b/src/google/protobuf/compiler/java/doc_comment_unittest.cc similarity index 75% rename from src/google/protobuf/compiler/java/java_doc_comment_unittest.cc rename to src/google/protobuf/compiler/java/doc_comment_unittest.cc index ae582ea..3fcdf07 100644 --- a/src/google/protobuf/compiler/java/java_doc_comment_unittest.cc +++ b/src/google/protobuf/compiler/java/doc_comment_unittest.cc
@@ -30,7 +30,7 @@ // Author: kenton@google.com (Kenton Varda) -#include <google/protobuf/compiler/java/java_doc_comment.h> +#include <google/protobuf/compiler/java/doc_comment.h> #include <gtest/gtest.h> @@ -49,17 +49,6 @@ EXPECT_EQ("@deprecated", EscapeJavadoc("@deprecated")); } -// TODO(kenton): It's hard to write a robust test of the doc comments -- we -// can only really compare the output against a golden value, which is a -// fairly tedious and fragile testing strategy. If we want to go that route, -// it probably makes sense to bite the bullet and write a test that compares -// the whole generated output for unittest.proto against a golden value, with -// a very simple script that can be run to regenerate it with the latest code. -// This would mean that updates to the golden file would have to be included -// in any change to the code generator, which would actually be fairly useful -// as it allows the reviewer to see clearly how the generated code is -// changing. - } // namespace } // namespace java } // namespace compiler
diff --git a/src/google/protobuf/compiler/java/java_enum.cc b/src/google/protobuf/compiler/java/enum.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_enum.cc rename to src/google/protobuf/compiler/java/enum.cc index 0d9a71b..0cab93c 100644 --- a/src/google/protobuf/compiler/java/java_enum.cc +++ b/src/google/protobuf/compiler/java/enum.cc
@@ -32,19 +32,22 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_enum.h> +#include <google/protobuf/compiler/java/enum.h> #include <map> #include <string> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> #include <google/protobuf/descriptor.pb.h> +// Must be last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace compiler { @@ -390,3 +393,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_enum.h b/src/google/protobuf/compiler/java/enum.h similarity index 100% rename from src/google/protobuf/compiler/java/java_enum.h rename to src/google/protobuf/compiler/java/enum.h
diff --git a/src/google/protobuf/compiler/java/java_enum_field.cc b/src/google/protobuf/compiler/java/enum_field.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_enum_field.cc rename to src/google/protobuf/compiler/java/enum_field.cc index 0e6fb44..ed3594c 100644 --- a/src/google/protobuf/compiler/java/java_enum_field.cc +++ b/src/google/protobuf/compiler/java/enum_field.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_enum_field.h> +#include <google/protobuf/compiler/java/enum_field.h> #include <cstdint> #include <map> @@ -43,10 +43,13 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -280,7 +283,7 @@ io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$public var $kt_name$: $kt_type$\n" + "$kt_deprecation$ var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -291,7 +294,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false); printer->Print(variables_, - "public fun ${$clear$kt_capitalized_name$$}$() {\n" + "fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -299,7 +302,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print( variables_, - "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -859,7 +862,7 @@ "}\n"); printer->Annotate("{", "}", descriptor_); WriteFieldEnumValueAccessorDocComment(printer, descriptor_, - LIST_INDEXED_GETTER, + LIST_INDEXED_SETTER, /* builder */ true); printer->Print( variables_, @@ -1082,12 +1085,12 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$ public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -1100,7 +1103,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -1112,7 +1115,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -1123,7 +1126,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -1136,7 +1139,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -1148,7 +1151,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "public operator fun com.google.protobuf.kotlin.DslList" + "operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -1159,7 +1162,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" @@ -1174,3 +1177,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_enum_field.h b/src/google/protobuf/compiler/java/enum_field.h similarity index 99% rename from src/google/protobuf/compiler/java/java_enum_field.h rename to src/google/protobuf/compiler/java/enum_field.h index abdc188..d2bc8d6 100644 --- a/src/google/protobuf/compiler/java/java_enum_field.h +++ b/src/google/protobuf/compiler/java/enum_field.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.cc b/src/google/protobuf/compiler/java/enum_field_lite.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_enum_field_lite.cc rename to src/google/protobuf/compiler/java/enum_field_lite.cc index 27b62ac..6fe683f 100644 --- a/src/google/protobuf/compiler/java/java_enum_field_lite.cc +++ b/src/google/protobuf/compiler/java/enum_field_lite.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_enum_field_lite.h> +#include <google/protobuf/compiler/java/enum_field_lite.h> #include <cstdint> #include <map> @@ -43,10 +43,13 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -285,7 +288,7 @@ io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$public var $kt_name$: $kt_type$\n" + "$kt_deprecation$var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -296,7 +299,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false); printer->Print(variables_, - "public fun ${$clear$kt_capitalized_name$$}$() {\n" + "fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -304,7 +307,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print( variables_, - "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -824,12 +827,12 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$ public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -842,7 +845,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -854,7 +857,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -865,7 +868,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -878,7 +881,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -890,7 +893,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "public operator fun com.google.protobuf.kotlin.DslList" + "operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -901,7 +904,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" @@ -916,3 +919,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_enum_field_lite.h b/src/google/protobuf/compiler/java/enum_field_lite.h similarity index 98% rename from src/google/protobuf/compiler/java/java_enum_field_lite.h rename to src/google/protobuf/compiler/java/enum_field_lite.h index 6ed11c9..492b268 100644 --- a/src/google/protobuf/compiler/java/java_enum_field_lite.h +++ b/src/google/protobuf/compiler/java/enum_field_lite.h
@@ -39,7 +39,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_enum_lite.cc b/src/google/protobuf/compiler/java/enum_lite.cc similarity index 96% rename from src/google/protobuf/compiler/java/java_enum_lite.cc rename to src/google/protobuf/compiler/java/enum_lite.cc index 5d7955c..4387090 100644 --- a/src/google/protobuf/compiler/java/java_enum_lite.cc +++ b/src/google/protobuf/compiler/java/enum_lite.cc
@@ -32,17 +32,17 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_enum_lite.h> +#include <google/protobuf/compiler/java/enum_lite.h> #include <map> #include <string> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/stubs/map_util.h>
diff --git a/src/google/protobuf/compiler/java/java_enum_lite.h b/src/google/protobuf/compiler/java/enum_lite.h similarity index 100% rename from src/google/protobuf/compiler/java/java_enum_lite.h rename to src/google/protobuf/compiler/java/enum_lite.h
diff --git a/src/google/protobuf/compiler/java/java_extension.cc b/src/google/protobuf/compiler/java/extension.cc similarity index 94% rename from src/google/protobuf/compiler/java/java_extension.cc rename to src/google/protobuf/compiler/java/extension.cc index 6ebca41..8b93eb1 100644 --- a/src/google/protobuf/compiler/java/java_extension.cc +++ b/src/google/protobuf/compiler/java/extension.cc
@@ -32,14 +32,17 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_extension.h> +#include <google/protobuf/compiler/java/extension.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -170,3 +173,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_extension.h b/src/google/protobuf/compiler/java/extension.h similarity index 100% rename from src/google/protobuf/compiler/java/java_extension.h rename to src/google/protobuf/compiler/java/extension.h
diff --git a/src/google/protobuf/compiler/java/java_extension_lite.cc b/src/google/protobuf/compiler/java/extension_lite.cc similarity index 92% rename from src/google/protobuf/compiler/java/java_extension_lite.cc rename to src/google/protobuf/compiler/java/extension_lite.cc index d84ee27..bffb1d6 100644 --- a/src/google/protobuf/compiler/java/java_extension_lite.cc +++ b/src/google/protobuf/compiler/java/extension_lite.cc
@@ -28,14 +28,17 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/java/java_extension_lite.h> +#include <google/protobuf/compiler/java/extension_lite.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -113,3 +116,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_extension_lite.h b/src/google/protobuf/compiler/java/extension_lite.h similarity index 98% rename from src/google/protobuf/compiler/java/java_extension_lite.h rename to src/google/protobuf/compiler/java/extension_lite.h index 54dc437..264230c 100644 --- a/src/google/protobuf/compiler/java/java_extension_lite.h +++ b/src/google/protobuf/compiler/java/extension_lite.h
@@ -35,7 +35,7 @@ #include <string> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/java/java_extension.h> +#include <google/protobuf/compiler/java/extension.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_field.cc b/src/google/protobuf/compiler/java/field.cc similarity index 93% rename from src/google/protobuf/compiler/java/java_field.cc rename to src/google/protobuf/compiler/java/field.cc index cd08d60..6313a2a 100644 --- a/src/google/protobuf/compiler/java/java_field.cc +++ b/src/google/protobuf/compiler/java/field.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> #include <memory> @@ -41,18 +41,18 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_enum_field.h> -#include <google/protobuf/compiler/java/java_enum_field_lite.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_map_field.h> -#include <google/protobuf/compiler/java/java_map_field_lite.h> -#include <google/protobuf/compiler/java/java_message_field.h> -#include <google/protobuf/compiler/java/java_message_field_lite.h> -#include <google/protobuf/compiler/java/java_primitive_field.h> -#include <google/protobuf/compiler/java/java_primitive_field_lite.h> -#include <google/protobuf/compiler/java/java_string_field.h> -#include <google/protobuf/compiler/java/java_string_field_lite.h> +#include <google/protobuf/compiler/java/context.h> +#include <google/protobuf/compiler/java/enum_field.h> +#include <google/protobuf/compiler/java/enum_field_lite.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/map_field.h> +#include <google/protobuf/compiler/java/map_field_lite.h> +#include <google/protobuf/compiler/java/message_field.h> +#include <google/protobuf/compiler/java/message_field_lite.h> +#include <google/protobuf/compiler/java/primitive_field.h> +#include <google/protobuf/compiler/java/primitive_field_lite.h> +#include <google/protobuf/compiler/java/string_field.h> +#include <google/protobuf/compiler/java/string_field_lite.h> namespace google {
diff --git a/src/google/protobuf/compiler/java/java_field.h b/src/google/protobuf/compiler/java/field.h similarity index 100% rename from src/google/protobuf/compiler/java/java_field.h rename to src/google/protobuf/compiler/java/field.h
diff --git a/src/google/protobuf/compiler/java/java_file.cc b/src/google/protobuf/compiler/java/file.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_file.cc rename to src/google/protobuf/compiler/java/file.cc index 7dbf64d..cf27703 100644 --- a/src/google/protobuf/compiler/java/java_file.cc +++ b/src/google/protobuf/compiler/java/file.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_file.h> +#include <google/protobuf/compiler/java/file.h> #include <memory> #include <set> @@ -42,18 +42,21 @@ #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/dynamic_message.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_enum.h> -#include <google/protobuf/compiler/java/java_enum_lite.h> -#include <google/protobuf/compiler/java/java_extension.h> -#include <google/protobuf/compiler/java/java_generator_factory.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_message.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> -#include <google/protobuf/compiler/java/java_service.h> -#include <google/protobuf/compiler/java/java_shared_code_generator.h> +#include <google/protobuf/compiler/java/context.h> +#include <google/protobuf/compiler/java/enum.h> +#include <google/protobuf/compiler/java/enum_lite.h> +#include <google/protobuf/compiler/java/extension.h> +#include <google/protobuf/compiler/java/generator_factory.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/message.h> +#include <google/protobuf/compiler/java/name_resolver.h> +#include <google/protobuf/compiler/java/service.h> +#include <google/protobuf/compiler/java/shared_code_generator.h> #include <google/protobuf/descriptor.pb.h> +// Must be last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace compiler { @@ -247,7 +250,7 @@ << "generate full runtime code for Java. To use Java Lite runtime, " << "users should use the Java Lite plugin instead. See:\n" << " " - "https://github.com/protocolbuffers/protobuf/blob/master/java/" + "https://github.com/protocolbuffers/protobuf/blob/main/java/" "lite.md"; } return true; @@ -732,3 +735,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_file.h b/src/google/protobuf/compiler/java/file.h similarity index 98% rename from src/google/protobuf/compiler/java/java_file.h rename to src/google/protobuf/compiler/java/file.h index 79ee630..b2e0373 100644 --- a/src/google/protobuf/compiler/java/java_file.h +++ b/src/google/protobuf/compiler/java/file.h
@@ -40,7 +40,7 @@ #include <vector> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/java/java_options.h> +#include <google/protobuf/compiler/java/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_generator.cc b/src/google/protobuf/compiler/java/generator.cc similarity index 94% rename from src/google/protobuf/compiler/java/java_generator.cc rename to src/google/protobuf/compiler/java/generator.cc index f75f8b3..85e3991 100644 --- a/src/google/protobuf/compiler/java/java_generator.cc +++ b/src/google/protobuf/compiler/java/generator.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_generator.h> +#include <google/protobuf/compiler/java/generator.h> #include <memory> @@ -40,12 +40,12 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/stubs/stringprintf.h> -#include <google/protobuf/compiler/java/java_file.h> -#include <google/protobuf/compiler/java/java_generator_factory.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> -#include <google/protobuf/compiler/java/java_options.h> -#include <google/protobuf/compiler/java/java_shared_code_generator.h> +#include <google/protobuf/compiler/java/file.h> +#include <google/protobuf/compiler/java/generator_factory.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> +#include <google/protobuf/compiler/java/options.h> +#include <google/protobuf/compiler/java/shared_code_generator.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/stubs/strutil.h>
diff --git a/src/google/protobuf/compiler/java/java_generator.h b/src/google/protobuf/compiler/java/generator.h similarity index 100% rename from src/google/protobuf/compiler/java/java_generator.h rename to src/google/protobuf/compiler/java/generator.h
diff --git a/src/google/protobuf/compiler/java/java_generator_factory.cc b/src/google/protobuf/compiler/java/generator_factory.cc similarity index 83% rename from src/google/protobuf/compiler/java/java_generator_factory.cc rename to src/google/protobuf/compiler/java/generator_factory.cc index 3a62adb..dd526ba 100644 --- a/src/google/protobuf/compiler/java/java_generator_factory.cc +++ b/src/google/protobuf/compiler/java/generator_factory.cc
@@ -30,17 +30,17 @@ // Author: liujisi@google.com (Pherl Liu) -#include <google/protobuf/compiler/java/java_generator_factory.h> +#include <google/protobuf/compiler/java/generator_factory.h> -#include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_enum_field.h> -#include <google/protobuf/compiler/java/java_extension.h> -#include <google/protobuf/compiler/java/java_extension_lite.h> -#include <google/protobuf/compiler/java/java_field.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_message.h> -#include <google/protobuf/compiler/java/java_message_lite.h> -#include <google/protobuf/compiler/java/java_service.h> +#include <google/protobuf/compiler/java/context.h> +#include <google/protobuf/compiler/java/enum_field.h> +#include <google/protobuf/compiler/java/extension.h> +#include <google/protobuf/compiler/java/extension_lite.h> +#include <google/protobuf/compiler/java/field.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/message.h> +#include <google/protobuf/compiler/java/message_lite.h> +#include <google/protobuf/compiler/java/service.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_generator_factory.h b/src/google/protobuf/compiler/java/generator_factory.h similarity index 100% rename from src/google/protobuf/compiler/java/java_generator_factory.h rename to src/google/protobuf/compiler/java/generator_factory.h
diff --git a/src/google/protobuf/compiler/java/java_helpers.cc b/src/google/protobuf/compiler/java/helpers.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_helpers.cc rename to src/google/protobuf/compiler/java/helpers.cc index 3d9dc40..3cbcaca 100644 --- a/src/google/protobuf/compiler/java/java_helpers.cc +++ b/src/google/protobuf/compiler/java/helpers.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_helpers.h> +#include <google/protobuf/compiler/java/helpers.h> #include <algorithm> #include <cstdint> @@ -44,11 +44,14 @@ #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/stringprintf.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> -#include <google/protobuf/compiler/java/java_names.h> +#include <google/protobuf/compiler/java/name_resolver.h> +#include <google/protobuf/compiler/java/names.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/stubs/hash.h> // for hash<T *> +// Must be last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace compiler { @@ -261,18 +264,18 @@ return name; } +// Names that should be avoided as field names in Kotlin. +// All Kotlin hard keywords are in this list. +const std::unordered_set<std::string>* kKotlinForbiddenNames = + new std::unordered_set<std::string>({ + "as", "as?", "break", "class", "continue", "do", "else", + "false", "for", "fun", "if", "in", "!in", "interface", + "is", "!is", "null", "object", "package", "return", "super", + "this", "throw", "true", "try", "typealias", "typeof", "val", + "var", "when", "while", + }); + bool IsForbiddenKotlin(const std::string& field_name) { - // Names that should be avoided as field names in Kotlin. - // All Kotlin hard keywords are in this list. - const std::unordered_set<std::string>* kKotlinForbiddenNames = - new std::unordered_set<std::string>({ - "as", "as?", "break", "class", "continue", "do", - "else", "false", "for", "fun", "if", "in", - "!in", "interface", "is", "!is", "null", "object", - "package", "return", "super", "this", "throw", "true", - "try", "typealias", "typeof", "val", "var", "when", - "while", - }); return kKotlinForbiddenNames->find(field_name) != kKotlinForbiddenNames->end(); } @@ -1109,3 +1112,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_helpers.h b/src/google/protobuf/compiler/java/helpers.h similarity index 99% rename from src/google/protobuf/compiler/java/java_helpers.h rename to src/google/protobuf/compiler/java/helpers.h index dd947bc..9f1a557 100644 --- a/src/google/protobuf/compiler/java/java_helpers.h +++ b/src/google/protobuf/compiler/java/helpers.h
@@ -40,7 +40,7 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/descriptor.h> -#include <google/protobuf/compiler/java/java_context.h> +#include <google/protobuf/compiler/java/context.h> #include <google/protobuf/descriptor.pb.h> namespace google {
diff --git a/src/google/protobuf/compiler/java/java_kotlin_generator.cc b/src/google/protobuf/compiler/java/kotlin_generator.cc similarity index 95% rename from src/google/protobuf/compiler/java/java_kotlin_generator.cc rename to src/google/protobuf/compiler/java/kotlin_generator.cc index aa54bb2..1af548a 100644 --- a/src/google/protobuf/compiler/java/java_kotlin_generator.cc +++ b/src/google/protobuf/compiler/java/kotlin_generator.cc
@@ -28,13 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/java/java_kotlin_generator.h> +#include <google/protobuf/compiler/java/kotlin_generator.h> #include <google/protobuf/compiler/code_generator.h> -#include <google/protobuf/compiler/java/java_file.h> -#include <google/protobuf/compiler/java/java_generator.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_options.h> +#include <google/protobuf/compiler/java/file.h> +#include <google/protobuf/compiler/java/generator.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_kotlin_generator.h b/src/google/protobuf/compiler/java/kotlin_generator.h similarity index 100% rename from src/google/protobuf/compiler/java/java_kotlin_generator.h rename to src/google/protobuf/compiler/java/kotlin_generator.h
diff --git a/src/google/protobuf/compiler/java/java_map_field.cc b/src/google/protobuf/compiler/java/map_field.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_map_field.cc rename to src/google/protobuf/compiler/java/map_field.cc index 606d26e..bc48f61 100644 --- a/src/google/protobuf/compiler/java/java_map_field.cc +++ b/src/google/protobuf/compiler/java/map_field.cc
@@ -28,13 +28,16 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/java/java_map_field.h> +#include <google/protobuf/compiler/java/map_field.h> #include <google/protobuf/io/printer.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -695,13 +698,13 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, - "$kt_deprecation$ public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -714,7 +717,7 @@ printer->Print( variables_, "@JvmName(\"put$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslMap" + "fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .put(key: $kt_key_type$, value: $kt_value_type$) {\n" " $kt_dsl_builder$.${$put$capitalized_name$$}$(key, value)\n" @@ -726,7 +729,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"set$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslMap" + "inline operator fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .set(key: $kt_key_type$, value: $kt_value_type$) {\n" " put(key, value)\n" @@ -737,7 +740,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"remove$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslMap" + "fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .remove(key: $kt_key_type$) {\n" " $kt_dsl_builder$.${$remove$capitalized_name$$}$(key)\n" @@ -748,7 +751,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"putAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslMap" + "fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .putAll(map: kotlin.collections.Map<$kt_key_type$, $kt_value_type$>) " "{\n" @@ -760,7 +763,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslMap" + "fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" @@ -887,3 +890,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_map_field.h b/src/google/protobuf/compiler/java/map_field.h similarity index 98% rename from src/google/protobuf/compiler/java/java_map_field.h rename to src/google/protobuf/compiler/java/map_field.h index 98d9249..7fee10a 100644 --- a/src/google/protobuf/compiler/java/java_map_field.h +++ b/src/google/protobuf/compiler/java/map_field.h
@@ -31,7 +31,7 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_H__ #define GOOGLE_PROTOBUF_COMPILER_JAVA_MAP_FIELD_H__ -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.cc b/src/google/protobuf/compiler/java/map_field_lite.cc similarity index 98% rename from src/google/protobuf/compiler/java/java_map_field_lite.cc rename to src/google/protobuf/compiler/java/map_field_lite.cc index f624522..4f2766e 100644 --- a/src/google/protobuf/compiler/java/java_map_field_lite.cc +++ b/src/google/protobuf/compiler/java/map_field_lite.cc
@@ -28,15 +28,18 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/java/java_map_field_lite.h> +#include <google/protobuf/compiler/java/map_field_lite.h> #include <cstdint> #include <google/protobuf/io/printer.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -835,13 +838,13 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print( variables_, - "$kt_deprecation$ public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -854,7 +857,7 @@ printer->Print( variables_, "@JvmName(\"put$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslMap" + "fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .put(key: $kt_key_type$, value: $kt_value_type$) {\n" " $kt_dsl_builder$.${$put$capitalized_name$$}$(key, value)\n" @@ -866,7 +869,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"set$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslMap" + "inline operator fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .set(key: $kt_key_type$, value: $kt_value_type$) {\n" " put(key, value)\n" @@ -877,7 +880,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"remove$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslMap" + "fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .remove(key: $kt_key_type$) {\n" " $kt_dsl_builder$.${$remove$capitalized_name$$}$(key)\n" @@ -888,7 +891,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"putAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslMap" + "fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .putAll(map: kotlin.collections.Map<$kt_key_type$, $kt_value_type$>) " "{\n" @@ -900,7 +903,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslMap" + "fun com.google.protobuf.kotlin.DslMap" "<$kt_key_type$, $kt_value_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " .clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" @@ -920,3 +923,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_map_field_lite.h b/src/google/protobuf/compiler/java/map_field_lite.h similarity index 98% rename from src/google/protobuf/compiler/java/java_map_field_lite.h rename to src/google/protobuf/compiler/java/map_field_lite.h index da046b2..964f098 100644 --- a/src/google/protobuf/compiler/java/java_map_field_lite.h +++ b/src/google/protobuf/compiler/java/map_field_lite.h
@@ -33,7 +33,7 @@ #include <cstdint> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_message.cc b/src/google/protobuf/compiler/java/message.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_message.cc rename to src/google/protobuf/compiler/java/message.cc index 9918abc..0cc6171 100644 --- a/src/google/protobuf/compiler/java/java_message.cc +++ b/src/google/protobuf/compiler/java/message.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_message.h> +#include <google/protobuf/compiler/java/message.h> #include <algorithm> #include <cstdint> @@ -45,17 +45,20 @@ #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_doc_comment.h> -#include <google/protobuf/compiler/java/java_enum.h> -#include <google/protobuf/compiler/java/java_extension.h> -#include <google/protobuf/compiler/java/java_generator_factory.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_message_builder.h> -#include <google/protobuf/compiler/java/java_message_builder_lite.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/compiler/java/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/enum.h> +#include <google/protobuf/compiler/java/extension.h> +#include <google/protobuf/compiler/java/generator_factory.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/message_builder.h> +#include <google/protobuf/compiler/java/message_builder_lite.h> +#include <google/protobuf/compiler/java/name_resolver.h> #include <google/protobuf/descriptor.pb.h> +// Must be last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace compiler { @@ -1410,10 +1413,10 @@ "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" "@com.google.protobuf.kotlin.ProtoDslMarker\n"); printer->Print( - "public class Dsl private constructor(\n" + "class Dsl private constructor(\n" " private val _builder: $message$.Builder\n" ") {\n" - " public companion object {\n" + " companion object {\n" " @kotlin.jvm.JvmSynthetic\n" " @kotlin.PublishedApi\n" " internal fun _create(builder: $message$.Builder): Dsl = " @@ -1435,10 +1438,10 @@ for (auto oneof : oneofs_) { printer->Print( - "public val $oneof_name$Case: $message$.$oneof_capitalized_name$Case\n" + "val $oneof_name$Case: $message$.$oneof_capitalized_name$Case\n" " @JvmName(\"get$oneof_capitalized_name$Case\")\n" " get() = _builder.get$oneof_capitalized_name$Case()\n\n" - "public fun clear$oneof_capitalized_name$() {\n" + "fun clear$oneof_capitalized_name$() {\n" " _builder.clear$oneof_capitalized_name$()\n" "}\n", "oneof_name", context_->GetOneofGeneratorInfo(oneof)->name, @@ -1459,7 +1462,7 @@ io::Printer* printer) const { printer->Print( "@kotlin.jvm.JvmName(\"-initialize$camelcase_name$\")\n" - "public inline fun $camelcase_name$(block: $message_kt$.Dsl.() -> " + "inline fun $camelcase_name$(block: $message_kt$.Dsl.() -> " "kotlin.Unit): " "$message$ " "=\n" @@ -1469,7 +1472,7 @@ "message_kt", name_resolver_->GetKotlinExtensionsClassName(descriptor_), "message", name_resolver_->GetClassName(descriptor_, true)); - printer->Print("public object $name$Kt {\n", "name", descriptor_->name()); + printer->Print("object $name$Kt {\n", "name", descriptor_->name()); printer->Indent(); GenerateKotlinDsl(printer); for (int i = 0; i < descriptor_->nested_type_count(); i++) { @@ -1485,7 +1488,7 @@ io::Printer* printer) const { printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public inline fun $message$.copy(block: $message_kt$.Dsl.() -> " + "inline fun $message$.copy(block: $message_kt$.Dsl.() -> " "kotlin.Unit): " "$message$ =\n" " $message_kt$.Dsl._create(this.toBuilder()).apply { block() " @@ -1525,7 +1528,7 @@ printer->Print( "@Suppress(\"UNCHECKED_CAST\")\n" "@kotlin.jvm.JvmSynthetic\n" - "public operator fun <T : kotlin.Any> get(extension: " + "operator fun <T : kotlin.Any> get(extension: " "com.google.protobuf.ExtensionLite<$message$, T>): T {\n" " return if (extension.isRepeated) {\n" " get(extension as com.google.protobuf.ExtensionLite<$message$, " @@ -1541,7 +1544,7 @@ "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" "@kotlin.jvm.JvmName(\"-getRepeatedExtension\")\n" - "public operator fun <E : kotlin.Any> get(\n" + "operator fun <E : kotlin.Any> get(\n" " extension: com.google.protobuf.ExtensionLite<$message$, List<E>>\n" "): com.google.protobuf.kotlin.ExtensionList<E, $message$> {\n" " return com.google.protobuf.kotlin.ExtensionList(extension, " @@ -1551,7 +1554,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public operator fun contains(extension: " + "operator fun contains(extension: " "com.google.protobuf.ExtensionLite<$message$, *>): " "Boolean {\n" " return _builder.hasExtension(extension)\n" @@ -1560,7 +1563,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public fun clear(extension: " + "fun clear(extension: " "com.google.protobuf.ExtensionLite<$message$, *>) " "{\n" " _builder.clearExtension(extension)\n" @@ -1580,7 +1583,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun <T : Comparable<T>> set(\n" + "inline operator fun <T : Comparable<T>> set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" ") {\n" @@ -1591,7 +1594,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun set(\n" + "inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, " "com.google.protobuf.ByteString>,\n" " value: com.google.protobuf.ByteString\n" @@ -1603,7 +1606,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun <T : com.google.protobuf.MessageLite> set(\n" + "inline operator fun <T : com.google.protobuf.MessageLite> set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" ") {\n" @@ -1613,7 +1616,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public fun <E : kotlin.Any> com.google.protobuf.kotlin.ExtensionList<E, " + "fun <E : kotlin.Any> com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.add(value: E) {\n" " _builder.addExtension(this.extension, value)\n" "}\n\n", @@ -1622,7 +1625,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun <E : kotlin.Any> " + "inline operator fun <E : kotlin.Any> " "com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.plusAssign" "(value: E) {\n" @@ -1632,7 +1635,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public fun <E : kotlin.Any> com.google.protobuf.kotlin.ExtensionList<E, " + "fun <E : kotlin.Any> com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.addAll(values: Iterable<E>) {\n" " for (value in values) {\n" " add(value)\n" @@ -1643,7 +1646,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun <E : kotlin.Any> " + "inline operator fun <E : kotlin.Any> " "com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.plusAssign(values: " "Iterable<E>) {\n" @@ -1653,7 +1656,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public operator fun <E : kotlin.Any> " + "operator fun <E : kotlin.Any> " "com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.set(index: Int, value: " "E) {\n" @@ -1664,7 +1667,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline fun com.google.protobuf.kotlin.ExtensionList<*, " + "inline fun com.google.protobuf.kotlin.ExtensionList<*, " "$message$>.clear() {\n" " clear(extension)\n" "}\n\n", @@ -1749,3 +1752,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_message.h b/src/google/protobuf/compiler/java/message.h similarity index 98% rename from src/google/protobuf/compiler/java/java_message.h rename to src/google/protobuf/compiler/java/message.h index cc24d73..2dbd0dd 100644 --- a/src/google/protobuf/compiler/java/java_message.h +++ b/src/google/protobuf/compiler/java/message.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_message_builder.cc b/src/google/protobuf/compiler/java/message_builder.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_message_builder.cc rename to src/google/protobuf/compiler/java/message_builder.cc index 4d46669..2366c0c 100644 --- a/src/google/protobuf/compiler/java/java_message_builder.cc +++ b/src/google/protobuf/compiler/java/message_builder.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_message_builder.h> +#include <google/protobuf/compiler/java/message_builder.h> #include <algorithm> #include <map> @@ -44,15 +44,18 @@ #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_doc_comment.h> -#include <google/protobuf/compiler/java/java_enum.h> -#include <google/protobuf/compiler/java/java_extension.h> -#include <google/protobuf/compiler/java/java_generator_factory.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/compiler/java/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/enum.h> +#include <google/protobuf/compiler/java/extension.h> +#include <google/protobuf/compiler/java/generator_factory.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> #include <google/protobuf/descriptor.pb.h> +// Must be last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace compiler { @@ -710,3 +713,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_message_builder.h b/src/google/protobuf/compiler/java/message_builder.h similarity index 98% rename from src/google/protobuf/compiler/java/java_message_builder.h rename to src/google/protobuf/compiler/java/message_builder.h index 619bf9e..f9c9a00 100644 --- a/src/google/protobuf/compiler/java/java_message_builder.h +++ b/src/google/protobuf/compiler/java/message_builder.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_message_builder_lite.cc b/src/google/protobuf/compiler/java/message_builder_lite.cc similarity index 90% rename from src/google/protobuf/compiler/java/java_message_builder_lite.cc rename to src/google/protobuf/compiler/java/message_builder_lite.cc index b8136e3..526f949 100644 --- a/src/google/protobuf/compiler/java/java_message_builder_lite.cc +++ b/src/google/protobuf/compiler/java/message_builder_lite.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_message_builder_lite.h> +#include <google/protobuf/compiler/java/message_builder_lite.h> #include <algorithm> #include <map> @@ -44,15 +44,18 @@ #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_doc_comment.h> -#include <google/protobuf/compiler/java/java_enum.h> -#include <google/protobuf/compiler/java/java_extension.h> -#include <google/protobuf/compiler/java/java_generator_factory.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/compiler/java/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/enum.h> +#include <google/protobuf/compiler/java/extension.h> +#include <google/protobuf/compiler/java/generator_factory.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> #include <google/protobuf/descriptor.pb.h> +// Must be last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace compiler { @@ -149,3 +152,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_message_builder_lite.h b/src/google/protobuf/compiler/java/message_builder_lite.h similarity index 98% rename from src/google/protobuf/compiler/java/java_message_builder_lite.h rename to src/google/protobuf/compiler/java/message_builder_lite.h index 03ecbf8..0d895fc 100644 --- a/src/google/protobuf/compiler/java/java_message_builder_lite.h +++ b/src/google/protobuf/compiler/java/message_builder_lite.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_message_field.cc b/src/google/protobuf/compiler/java/message_field.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_message_field.cc rename to src/google/protobuf/compiler/java/message_field.cc index 694218c..f3833e9 100644 --- a/src/google/protobuf/compiler/java/java_message_field.cc +++ b/src/google/protobuf/compiler/java/message_field.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_message_field.h> +#include <google/protobuf/compiler/java/message_field.h> #include <map> #include <string> @@ -40,10 +40,13 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -418,7 +421,7 @@ io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$public var $kt_name$: $kt_type$\n" + "$kt_deprecation$var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -429,14 +432,14 @@ WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false); printer->Print(variables_, - "public fun ${$clear$kt_capitalized_name$$}$() {\n" + "fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print( variables_, - "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); @@ -446,7 +449,7 @@ void ImmutableMessageFieldGenerator::GenerateKotlinOrNull(io::Printer* printer) const { if (descriptor_->has_optional_keyword()) { printer->Print(variables_, - "public val $classname$Kt.Dsl.$name$OrNull: $kt_type$?\n" + "val $classname$Kt.Dsl.$name$OrNull: $kt_type$?\n" " get() = $kt_dsl_builder$.$name$OrNull\n"); } } @@ -1416,12 +1419,12 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$ public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -1434,7 +1437,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -1446,7 +1449,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -1457,7 +1460,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -1470,7 +1473,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -1482,7 +1485,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "public operator fun com.google.protobuf.kotlin.DslList" + "operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -1493,7 +1496,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" @@ -1504,3 +1507,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_message_field.h b/src/google/protobuf/compiler/java/message_field.h similarity index 99% rename from src/google/protobuf/compiler/java/java_message_field.h rename to src/google/protobuf/compiler/java/message_field.h index be1fb20..32dd4f0 100644 --- a/src/google/protobuf/compiler/java/java_message_field.h +++ b/src/google/protobuf/compiler/java/message_field.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_message_field_lite.cc b/src/google/protobuf/compiler/java/message_field_lite.cc similarity index 96% rename from src/google/protobuf/compiler/java/java_message_field_lite.cc rename to src/google/protobuf/compiler/java/message_field_lite.cc index 4f4265f..eb37ca6 100644 --- a/src/google/protobuf/compiler/java/java_message_field_lite.cc +++ b/src/google/protobuf/compiler/java/message_field_lite.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_message_field_lite.h> +#include <google/protobuf/compiler/java/message_field_lite.h> #include <cstdint> #include <map> @@ -41,10 +41,13 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -287,7 +290,7 @@ io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$public var $kt_name$: $kt_type$\n" + "$kt_deprecation$var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -298,14 +301,14 @@ WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false); printer->Print(variables_, - "public fun ${$clear$kt_capitalized_name$$}$() {\n" + "fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print( variables_, - "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); GenerateKotlinOrNull(printer); @@ -314,7 +317,7 @@ void ImmutableMessageFieldLiteGenerator::GenerateKotlinOrNull(io::Printer* printer) const { if (descriptor_->has_optional_keyword()) { printer->Print(variables_, - "public val $classname$Kt.Dsl.$name$OrNull: $kt_type$?\n" + "val $classname$Kt.Dsl.$name$OrNull: $kt_type$?\n" " get() = $kt_dsl_builder$.$name$OrNull\n"); } } @@ -803,12 +806,12 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$ public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -821,7 +824,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -833,7 +836,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -844,7 +847,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -857,7 +860,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -869,7 +872,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "public operator fun com.google.protobuf.kotlin.DslList" + "operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -880,7 +883,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" @@ -891,3 +894,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_message_field_lite.h b/src/google/protobuf/compiler/java/message_field_lite.h similarity index 98% rename from src/google/protobuf/compiler/java/java_message_field_lite.h rename to src/google/protobuf/compiler/java/message_field_lite.h index 313a409..4253acc 100644 --- a/src/google/protobuf/compiler/java/java_message_field_lite.h +++ b/src/google/protobuf/compiler/java/message_field_lite.h
@@ -39,7 +39,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_message_lite.cc b/src/google/protobuf/compiler/java/message_lite.cc similarity index 95% rename from src/google/protobuf/compiler/java/java_message_lite.cc rename to src/google/protobuf/compiler/java/message_lite.cc index 8073bac..a42ae3f 100644 --- a/src/google/protobuf/compiler/java/java_message_lite.cc +++ b/src/google/protobuf/compiler/java/message_lite.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_message_lite.h> +#include <google/protobuf/compiler/java/message_lite.h> #include <algorithm> #include <cstdint> @@ -45,17 +45,20 @@ #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/java/java_context.h> -#include <google/protobuf/compiler/java/java_doc_comment.h> -#include <google/protobuf/compiler/java/java_enum_lite.h> -#include <google/protobuf/compiler/java/java_extension_lite.h> -#include <google/protobuf/compiler/java/java_generator_factory.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_message_builder.h> -#include <google/protobuf/compiler/java/java_message_builder_lite.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/compiler/java/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/enum_lite.h> +#include <google/protobuf/compiler/java/extension_lite.h> +#include <google/protobuf/compiler/java/generator_factory.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/message_builder.h> +#include <google/protobuf/compiler/java/message_builder_lite.h> +#include <google/protobuf/compiler/java/name_resolver.h> #include <google/protobuf/descriptor.pb.h> +// Must be last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace compiler { @@ -731,10 +734,10 @@ "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" "@com.google.protobuf.kotlin.ProtoDslMarker\n"); printer->Print( - "public class Dsl private constructor(\n" + "class Dsl private constructor(\n" " private val _builder: $message$.Builder\n" ") {\n" - " public companion object {\n" + " companion object {\n" " @kotlin.jvm.JvmSynthetic\n" " @kotlin.PublishedApi\n" " internal fun _create(builder: $message$.Builder): Dsl = " @@ -756,10 +759,10 @@ for (auto oneof : oneofs_) { printer->Print( - "public val $oneof_name$Case: $message$.$oneof_capitalized_name$Case\n" + "val $oneof_name$Case: $message$.$oneof_capitalized_name$Case\n" " @JvmName(\"get$oneof_capitalized_name$Case\")\n" " get() = _builder.get$oneof_capitalized_name$Case()\n\n" - "public fun clear$oneof_capitalized_name$() {\n" + "fun clear$oneof_capitalized_name$() {\n" " _builder.clear$oneof_capitalized_name$()\n" "}\n", "oneof_name", context_->GetOneofGeneratorInfo(oneof)->name, @@ -780,7 +783,7 @@ io::Printer* printer) const { printer->Print( "@kotlin.jvm.JvmName(\"-initialize$camelcase_name$\")\n" - "public inline fun $camelcase_name$(block: $message_kt$.Dsl.() -> " + "inline fun $camelcase_name$(block: $message_kt$.Dsl.() -> " "kotlin.Unit): " "$message$ =\n" " $message_kt$.Dsl._create($message$.newBuilder()).apply { block() " @@ -789,7 +792,7 @@ "message_kt", name_resolver_->GetKotlinExtensionsClassName(descriptor_), "message", name_resolver_->GetClassName(descriptor_, true)); - printer->Print("public object $name$Kt {\n", "name", descriptor_->name()); + printer->Print("object $name$Kt {\n", "name", descriptor_->name()); printer->Indent(); GenerateKotlinDsl(printer); for (int i = 0; i < descriptor_->nested_type_count(); i++) { @@ -804,7 +807,7 @@ void ImmutableMessageLiteGenerator::GenerateTopLevelKotlinMembers( io::Printer* printer) const { printer->Print( - "public inline fun $message$.copy(block: $message_kt$.Dsl.() -> " + "inline fun $message$.copy(block: $message_kt$.Dsl.() -> " "kotlin.Unit): " "$message$ =\n" " $message_kt$.Dsl._create(this.toBuilder()).apply { block() " @@ -846,7 +849,7 @@ printer->Print( "@Suppress(\"UNCHECKED_CAST\")\n" "@kotlin.jvm.JvmSynthetic\n" - "public operator fun <T : kotlin.Any> get(extension: " + "operator fun <T : kotlin.Any> get(extension: " "com.google.protobuf.ExtensionLite<$message$, T>): T {\n" " return if (extension.isRepeated) {\n" " get(extension as com.google.protobuf.ExtensionLite<$message$, " @@ -862,7 +865,7 @@ "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" "@kotlin.jvm.JvmName(\"-getRepeatedExtension\")\n" - "public operator fun <E : kotlin.Any> get(\n" + "operator fun <E : kotlin.Any> get(\n" " extension: com.google.protobuf.ExtensionLite<$message$, List<E>>\n" "): com.google.protobuf.kotlin.ExtensionList<E, $message$> {\n" " return com.google.protobuf.kotlin.ExtensionList(extension, " @@ -872,7 +875,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public operator fun contains(extension: " + "operator fun contains(extension: " "com.google.protobuf.ExtensionLite<$message$, *>): " "Boolean {\n" " return _builder.hasExtension(extension)\n" @@ -881,7 +884,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public fun clear(extension: " + "fun clear(extension: " "com.google.protobuf.ExtensionLite<$message$, *>) " "{\n" " _builder.clearExtension(extension)\n" @@ -901,7 +904,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun <T : Comparable<T>> set(\n" + "inline operator fun <T : Comparable<T>> set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" ") {\n" @@ -912,7 +915,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun set(\n" + "inline operator fun set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, " "com.google.protobuf.ByteString>,\n" " value: com.google.protobuf.ByteString\n" @@ -924,7 +927,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun <T : com.google.protobuf.MessageLite> set(\n" + "inline operator fun <T : com.google.protobuf.MessageLite> set(\n" " extension: com.google.protobuf.ExtensionLite<$message$, T>,\n" " value: T\n" ") {\n" @@ -934,7 +937,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public fun<E : kotlin.Any> com.google.protobuf.kotlin.ExtensionList<E, " + "fun<E : kotlin.Any> com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.add(value: E) {\n" " _builder.addExtension(this.extension, value)\n" "}\n\n", @@ -943,7 +946,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun <E : kotlin.Any> " + "inline operator fun <E : kotlin.Any> " "com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.plusAssign" "(value: E) {\n" @@ -953,7 +956,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public fun<E : kotlin.Any> com.google.protobuf.kotlin.ExtensionList<E, " + "fun<E : kotlin.Any> com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.addAll(values: Iterable<E>) {\n" " for (value in values) {\n" " add(value)\n" @@ -964,7 +967,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun <E : kotlin.Any> " + "inline operator fun <E : kotlin.Any> " "com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.plusAssign(values: " "Iterable<E>) {\n" @@ -974,7 +977,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" - "public operator fun <E : kotlin.Any> " + "operator fun <E : kotlin.Any> " "com.google.protobuf.kotlin.ExtensionList<E, " "$message$>.set(index: Int, value: " "E) {\n" @@ -985,7 +988,7 @@ printer->Print( "@kotlin.jvm.JvmSynthetic\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline fun com.google.protobuf.kotlin.ExtensionList<*, " + "inline fun com.google.protobuf.kotlin.ExtensionList<*, " "$message$>.clear() {\n" " clear(extension)\n" "}\n\n", @@ -996,3 +999,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_message_lite.h b/src/google/protobuf/compiler/java/message_lite.h similarity index 96% rename from src/google/protobuf/compiler/java/java_message_lite.h rename to src/google/protobuf/compiler/java/message_lite.h index c0afbc9..3999132 100644 --- a/src/google/protobuf/compiler/java/java_message_lite.h +++ b/src/google/protobuf/compiler/java/message_lite.h
@@ -38,8 +38,8 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> -#include <google/protobuf/compiler/java/java_message.h> +#include <google/protobuf/compiler/java/field.h> +#include <google/protobuf/compiler/java/message.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_name_resolver.cc b/src/google/protobuf/compiler/java/name_resolver.cc similarity index 98% rename from src/google/protobuf/compiler/java/java_name_resolver.cc rename to src/google/protobuf/compiler/java/name_resolver.cc index 08c009b..06a637e 100644 --- a/src/google/protobuf/compiler/java/java_name_resolver.cc +++ b/src/google/protobuf/compiler/java/name_resolver.cc
@@ -28,15 +28,18 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/java/java_name_resolver.h> +#include <google/protobuf/compiler/java/name_resolver.h> #include <map> #include <string> #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/stubs/substitute.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_names.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/names.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -378,3 +381,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_name_resolver.h b/src/google/protobuf/compiler/java/name_resolver.h similarity index 98% rename from src/google/protobuf/compiler/java/java_name_resolver.h rename to src/google/protobuf/compiler/java/name_resolver.h index eddf23b..103cace 100644 --- a/src/google/protobuf/compiler/java/java_name_resolver.h +++ b/src/google/protobuf/compiler/java/name_resolver.h
@@ -36,6 +36,9 @@ #include <google/protobuf/stubs/common.h> +// Must be last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { class Descriptor; @@ -151,4 +154,6 @@ } // namespace protobuf } // namespace google +#include <google/protobuf/port_undef.inc> + #endif // GOOGLE_PROTOBUF_COMPILER_JAVA_NAME_RESOLVER_H__
diff --git a/src/google/protobuf/compiler/java/java_names.h b/src/google/protobuf/compiler/java/names.h similarity index 100% rename from src/google/protobuf/compiler/java/java_names.h rename to src/google/protobuf/compiler/java/names.h
diff --git a/src/google/protobuf/compiler/java/java_options.h b/src/google/protobuf/compiler/java/options.h similarity index 100% rename from src/google/protobuf/compiler/java/java_options.h rename to src/google/protobuf/compiler/java/options.h
diff --git a/src/google/protobuf/compiler/java/java_plugin_unittest.cc b/src/google/protobuf/compiler/java/plugin_unittest.cc similarity index 85% rename from src/google/protobuf/compiler/java/java_plugin_unittest.cc rename to src/google/protobuf/compiler/java/plugin_unittest.cc index 56b5fc7..8135f86 100644 --- a/src/google/protobuf/compiler/java/java_plugin_unittest.cc +++ b/src/google/protobuf/compiler/java/plugin_unittest.cc
@@ -29,19 +29,17 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) -// -// TODO(kenton): Share code with the versions of this test in other languages? -// It seemed like parameterizing it would add more complexity than it is -// worth. #include <memory> +#include <string> #include <google/protobuf/testing/file.h> #include <google/protobuf/testing/file.h> -#include <google/protobuf/compiler/java/java_generator.h> +#include <google/protobuf/compiler/java/generator.h> #include <google/protobuf/compiler/command_line_interface.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> +#include <google/protobuf/stubs/strutil.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> @@ -109,6 +107,26 @@ test_out.c_str(), "test.proto"}; EXPECT_EQ(0, cli.Run(5, argv)); + + // Loop over the lines of the generated code and verify that we find what we + // expect + + std::string output; + GOOGLE_CHECK_OK(File::GetContents(TestTempDir() + "/Test.java", &output, + true)); + std::vector<std::string> lines = Split(output, "\n"); + bool found_generated_annotation = false; + bool found_do_not_edit = false; + for (const auto& line : lines) { + if (line.find(" DO NOT EDIT!") != std::string::npos) { + found_do_not_edit = true; + } + if (line.find("@com.google.protobuf.Generated") != std::string::npos) { + found_generated_annotation = true; + } + } + EXPECT_TRUE(found_do_not_edit); + (void)found_generated_annotation; } } // namespace
diff --git a/src/google/protobuf/compiler/java/java_primitive_field.cc b/src/google/protobuf/compiler/java/primitive_field.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_primitive_field.cc rename to src/google/protobuf/compiler/java/primitive_field.cc index 3a338ee..9ec99f9 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field.cc +++ b/src/google/protobuf/compiler/java/primitive_field.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_primitive_field.h> +#include <google/protobuf/compiler/java/primitive_field.h> #include <cstdint> #include <map> @@ -43,10 +43,10 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> namespace google { namespace protobuf { @@ -320,7 +320,7 @@ io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$public var $kt_name$: $kt_type$\n" + "$kt_deprecation$var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -331,7 +331,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false); printer->Print(variables_, - "public fun ${$clear$kt_capitalized_name$$}$() {\n" + "fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -339,7 +339,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print( variables_, - "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -849,12 +849,12 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$ public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -867,7 +867,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -879,7 +879,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -890,7 +890,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -903,7 +903,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -915,7 +915,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "public operator fun com.google.protobuf.kotlin.DslList" + "operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -926,7 +926,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n"
diff --git a/src/google/protobuf/compiler/java/java_primitive_field.h b/src/google/protobuf/compiler/java/primitive_field.h similarity index 99% rename from src/google/protobuf/compiler/java/java_primitive_field.h rename to src/google/protobuf/compiler/java/primitive_field.h index 2eb1b23..f8ffc56 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field.h +++ b/src/google/protobuf/compiler/java/primitive_field.h
@@ -38,7 +38,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc b/src/google/protobuf/compiler/java/primitive_field_lite.cc similarity index 96% rename from src/google/protobuf/compiler/java/java_primitive_field_lite.cc rename to src/google/protobuf/compiler/java/primitive_field_lite.cc index 2da5f0d..e323fef 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field_lite.cc +++ b/src/google/protobuf/compiler/java/primitive_field_lite.cc
@@ -32,7 +32,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_primitive_field_lite.h> +#include <google/protobuf/compiler/java/primitive_field_lite.h> #include <cstdint> #include <map> @@ -43,10 +43,10 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> namespace google { namespace protobuf { @@ -325,7 +325,7 @@ io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$public var $kt_name$: $kt_type$\n" + "$kt_deprecation$var $kt_name$: $kt_type$\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -336,7 +336,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false); printer->Print(variables_, - "public fun ${$clear$kt_capitalized_name$$}$() {\n" + "fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -344,7 +344,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print( variables_, - "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -671,12 +671,12 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$ public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -689,7 +689,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "add(value: $kt_type$) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -701,7 +701,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: $kt_type$) {\n" " add(value)\n" @@ -712,7 +712,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<$kt_type$>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -725,7 +725,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<$kt_type$>) {\n" " addAll(values)\n" @@ -737,7 +737,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "public operator fun com.google.protobuf.kotlin.DslList" + "operator fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: $kt_type$) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -748,7 +748,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<$kt_type$, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n"
diff --git a/src/google/protobuf/compiler/java/java_primitive_field_lite.h b/src/google/protobuf/compiler/java/primitive_field_lite.h similarity index 98% rename from src/google/protobuf/compiler/java/java_primitive_field_lite.h rename to src/google/protobuf/compiler/java/primitive_field_lite.h index d277436..2da0cd8 100644 --- a/src/google/protobuf/compiler/java/java_primitive_field_lite.h +++ b/src/google/protobuf/compiler/java/primitive_field_lite.h
@@ -39,7 +39,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_service.cc b/src/google/protobuf/compiler/java/service.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_service.cc rename to src/google/protobuf/compiler/java/service.cc index 68b915b..9e20620 100644 --- a/src/google/protobuf/compiler/java/java_service.cc +++ b/src/google/protobuf/compiler/java/service.cc
@@ -32,14 +32,17 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_service.h> +#include <google/protobuf/compiler/java/service.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> + +// Must be last. +#include <google/protobuf/port_def.inc> namespace google { namespace protobuf { @@ -472,3 +475,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/compiler/java/java_service.h b/src/google/protobuf/compiler/java/service.h similarity index 100% rename from src/google/protobuf/compiler/java/java_service.h rename to src/google/protobuf/compiler/java/service.h
diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.cc b/src/google/protobuf/compiler/java/shared_code_generator.cc similarity index 96% rename from src/google/protobuf/compiler/java/java_shared_code_generator.cc rename to src/google/protobuf/compiler/java/shared_code_generator.cc index e527234..39b96ee 100644 --- a/src/google/protobuf/compiler/java/java_shared_code_generator.cc +++ b/src/google/protobuf/compiler/java/shared_code_generator.cc
@@ -30,7 +30,7 @@ // Author: xiaofeng@google.com (Feng Xiao) -#include <google/protobuf/compiler/java/java_shared_code_generator.h> +#include <google/protobuf/compiler/java/shared_code_generator.h> #include <memory> @@ -39,9 +39,9 @@ #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_helpers.h> -#include <google/protobuf/compiler/java/java_name_resolver.h> -#include <google/protobuf/compiler/java/java_names.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> +#include <google/protobuf/compiler/java/names.h> #include <google/protobuf/descriptor.pb.h> namespace google {
diff --git a/src/google/protobuf/compiler/java/java_shared_code_generator.h b/src/google/protobuf/compiler/java/shared_code_generator.h similarity index 98% rename from src/google/protobuf/compiler/java/java_shared_code_generator.h rename to src/google/protobuf/compiler/java/shared_code_generator.h index 7c79abe..b1f6eb3 100644 --- a/src/google/protobuf/compiler/java/java_shared_code_generator.h +++ b/src/google/protobuf/compiler/java/shared_code_generator.h
@@ -40,7 +40,7 @@ #include <vector> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/java/java_options.h> +#include <google/protobuf/compiler/java/options.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_string_field.cc b/src/google/protobuf/compiler/java/string_field.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_string_field.cc rename to src/google/protobuf/compiler/java/string_field.cc index 409d528..3228da6 100644 --- a/src/google/protobuf/compiler/java/java_string_field.cc +++ b/src/google/protobuf/compiler/java/string_field.cc
@@ -33,7 +33,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_string_field.h> +#include <google/protobuf/compiler/java/string_field.h> #include <cstdint> #include <map> @@ -44,10 +44,10 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> namespace google { namespace protobuf { @@ -379,7 +379,7 @@ io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$public var $kt_name$: kotlin.String\n" + "$kt_deprecation$var $kt_name$: kotlin.String\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -390,7 +390,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false); printer->Print(variables_, - "public fun ${$clear$kt_capitalized_name$$}$() {\n" + "fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -398,7 +398,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print( variables_, - "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -963,13 +963,13 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); // property for List<String> WriteFieldAccessorDocComment(printer, descriptor_, LIST_GETTER); printer->Print(variables_, - "$kt_deprecation$public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>\n" " @kotlin.jvm.JvmSynthetic\n" @@ -983,7 +983,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "add(value: kotlin.String) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -996,7 +996,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: kotlin.String) {\n" " add(value)\n" @@ -1009,7 +1009,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<kotlin.String>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -1023,7 +1023,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<kotlin.String>) {\n" " addAll(values)\n" @@ -1036,7 +1036,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "public operator fun com.google.protobuf.kotlin.DslList" + "operator fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: kotlin.String) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -1047,7 +1047,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n"
diff --git a/src/google/protobuf/compiler/java/java_string_field.h b/src/google/protobuf/compiler/java/string_field.h similarity index 99% rename from src/google/protobuf/compiler/java/java_string_field.h rename to src/google/protobuf/compiler/java/string_field.h index 3112887..b38d8e1 100644 --- a/src/google/protobuf/compiler/java/java_string_field.h +++ b/src/google/protobuf/compiler/java/string_field.h
@@ -39,7 +39,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.cc b/src/google/protobuf/compiler/java/string_field_lite.cc similarity index 97% rename from src/google/protobuf/compiler/java/java_string_field_lite.cc rename to src/google/protobuf/compiler/java/string_field_lite.cc index d010634..8e5b230 100644 --- a/src/google/protobuf/compiler/java/java_string_field_lite.cc +++ b/src/google/protobuf/compiler/java/string_field_lite.cc
@@ -33,7 +33,7 @@ // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. -#include <google/protobuf/compiler/java/java_string_field_lite.h> +#include <google/protobuf/compiler/java/string_field_lite.h> #include <cstdint> #include <map> @@ -44,10 +44,10 @@ #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/compiler/java/java_context.h> -#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/context.h> +#include <google/protobuf/compiler/java/doc_comment.h> +#include <google/protobuf/compiler/java/helpers.h> +#include <google/protobuf/compiler/java/name_resolver.h> namespace google { namespace protobuf { @@ -313,7 +313,7 @@ io::Printer* printer) const { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, - "$kt_deprecation$public var $kt_name$: kotlin.String\n" + "$kt_deprecation$var $kt_name$: kotlin.String\n" " @JvmName(\"${$get$kt_capitalized_name$$}$\")\n" " get() = $kt_dsl_builder$.${$get$capitalized_name$$}$()\n" " @JvmName(\"${$set$kt_capitalized_name$$}$\")\n" @@ -324,7 +324,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, CLEARER, /* builder */ false); printer->Print(variables_, - "public fun ${$clear$kt_capitalized_name$$}$() {\n" + "fun ${$clear$kt_capitalized_name$$}$() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n" "}\n"); @@ -332,7 +332,7 @@ WriteFieldAccessorDocComment(printer, descriptor_, HAZZER); printer->Print( variables_, - "public fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" + "fun ${$has$kt_capitalized_name$$}$(): kotlin.Boolean {\n" " return $kt_dsl_builder$.${$has$capitalized_name$$}$()\n" "}\n"); } @@ -748,17 +748,17 @@ " */\n" "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" - "public class ${$$kt_capitalized_name$Proxy$}$ private constructor()" + "class ${$$kt_capitalized_name$Proxy$}$ private constructor()" " : com.google.protobuf.kotlin.DslProxy()\n"); // property for List<String> WriteFieldAccessorDocComment(printer, descriptor_, LIST_GETTER); printer->Print( variables_, - "$kt_deprecation$public val $kt_name$: " + "$kt_deprecation$ val $kt_name$: " "com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>\n" - " @kotlin.OptIn" + "@kotlin.OptIn" "(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)\n" " get() = com.google.protobuf.kotlin.DslList(\n" " $kt_dsl_builder$.${$get$capitalized_name$List$}$()\n" @@ -770,7 +770,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"add$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "add(value: kotlin.String) {\n" " $kt_dsl_builder$.${$add$capitalized_name$$}$(value)\n" @@ -783,7 +783,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssign$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(value: kotlin.String) {\n" " add(value)\n" @@ -796,7 +796,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"addAll$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "addAll(values: kotlin.collections.Iterable<kotlin.String>) {\n" " $kt_dsl_builder$.${$addAll$capitalized_name$$}$(values)\n" @@ -810,7 +810,7 @@ "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"plusAssignAll$kt_capitalized_name$\")\n" "@Suppress(\"NOTHING_TO_INLINE\")\n" - "public inline operator fun com.google.protobuf.kotlin.DslList" + "inline operator fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "plusAssign(values: kotlin.collections.Iterable<kotlin.String>) {\n" " addAll(values)\n" @@ -823,7 +823,7 @@ variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"set$kt_capitalized_name$\")\n" - "public operator fun com.google.protobuf.kotlin.DslList" + "operator fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "set(index: kotlin.Int, value: kotlin.String) {\n" " $kt_dsl_builder$.${$set$capitalized_name$$}$(index, value)\n" @@ -834,7 +834,7 @@ printer->Print(variables_, "@kotlin.jvm.JvmSynthetic\n" "@kotlin.jvm.JvmName(\"clear$kt_capitalized_name$\")\n" - "public fun com.google.protobuf.kotlin.DslList" + "fun com.google.protobuf.kotlin.DslList" "<kotlin.String, ${$$kt_capitalized_name$Proxy$}$>." "clear() {\n" " $kt_dsl_builder$.${$clear$capitalized_name$$}$()\n"
diff --git a/src/google/protobuf/compiler/java/java_string_field_lite.h b/src/google/protobuf/compiler/java/string_field_lite.h similarity index 98% rename from src/google/protobuf/compiler/java/java_string_field_lite.h rename to src/google/protobuf/compiler/java/string_field_lite.h index 85ec602..b6ad1ea 100644 --- a/src/google/protobuf/compiler/java/java_string_field_lite.h +++ b/src/google/protobuf/compiler/java/string_field_lite.h
@@ -40,7 +40,7 @@ #include <map> #include <string> -#include <google/protobuf/compiler/java/java_field.h> +#include <google/protobuf/compiler/java/field.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/main.cc b/src/google/protobuf/compiler/main.cc index 08d77a6..dacab7c 100644 --- a/src/google/protobuf/compiler/main.cc +++ b/src/google/protobuf/compiler/main.cc
@@ -28,16 +28,16 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/cpp/cpp_generator.h> -#include <google/protobuf/compiler/java/java_generator.h> -#include <google/protobuf/compiler/java/java_kotlin_generator.h> +#include <google/protobuf/compiler/cpp/generator.h> +#include <google/protobuf/compiler/java/generator.h> +#include <google/protobuf/compiler/java/kotlin_generator.h> #include <google/protobuf/compiler/js/js_generator.h> #include <google/protobuf/compiler/command_line_interface.h> -#include <google/protobuf/compiler/python/python_generator.h> -#include <google/protobuf/compiler/python/python_pyi_generator.h> #include <google/protobuf/compiler/csharp/csharp_generator.h> #include <google/protobuf/compiler/objectivec/objectivec_generator.h> #include <google/protobuf/compiler/php/php_generator.h> +#include <google/protobuf/compiler/python/generator.h> +#include <google/protobuf/compiler/python/pyi_generator.h> #include <google/protobuf/compiler/ruby/ruby_generator.h> // Must be included last.
diff --git a/src/google/protobuf/compiler/mock_code_generator.cc b/src/google/protobuf/compiler/mock_code_generator.cc index 53f6118..4d04511 100644 --- a/src/google/protobuf/compiler/mock_code_generator.cc +++ b/src/google/protobuf/compiler/mock_code_generator.cc
@@ -47,13 +47,13 @@ #include <google/protobuf/testing/file.h> #include <google/protobuf/testing/file.h> #include <google/protobuf/compiler/plugin.pb.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/text_format.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/io/printer.h> +#include <google/protobuf/io/zero_copy_stream.h> +#include <google/protobuf/text_format.h> #ifdef major #undef major
diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index 0bb96ac..5bd37d1 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc
@@ -64,32 +64,33 @@ typedef std::unordered_map<std::string, FieldDescriptorProto::Type> TypeNameMap; -TypeNameMap MakeTypeNameTable() { - TypeNameMap result; +const TypeNameMap& GetTypeNameTable() { + static auto* table = new auto([]() { + TypeNameMap result; - result["double"] = FieldDescriptorProto::TYPE_DOUBLE; - result["float"] = FieldDescriptorProto::TYPE_FLOAT; - result["uint64"] = FieldDescriptorProto::TYPE_UINT64; - result["fixed64"] = FieldDescriptorProto::TYPE_FIXED64; - result["fixed32"] = FieldDescriptorProto::TYPE_FIXED32; - result["bool"] = FieldDescriptorProto::TYPE_BOOL; - result["string"] = FieldDescriptorProto::TYPE_STRING; - result["group"] = FieldDescriptorProto::TYPE_GROUP; + result["double"] = FieldDescriptorProto::TYPE_DOUBLE; + result["float"] = FieldDescriptorProto::TYPE_FLOAT; + result["uint64"] = FieldDescriptorProto::TYPE_UINT64; + result["fixed64"] = FieldDescriptorProto::TYPE_FIXED64; + result["fixed32"] = FieldDescriptorProto::TYPE_FIXED32; + result["bool"] = FieldDescriptorProto::TYPE_BOOL; + result["string"] = FieldDescriptorProto::TYPE_STRING; + result["group"] = FieldDescriptorProto::TYPE_GROUP; - result["bytes"] = FieldDescriptorProto::TYPE_BYTES; - result["uint32"] = FieldDescriptorProto::TYPE_UINT32; - result["sfixed32"] = FieldDescriptorProto::TYPE_SFIXED32; - result["sfixed64"] = FieldDescriptorProto::TYPE_SFIXED64; - result["int32"] = FieldDescriptorProto::TYPE_INT32; - result["int64"] = FieldDescriptorProto::TYPE_INT64; - result["sint32"] = FieldDescriptorProto::TYPE_SINT32; - result["sint64"] = FieldDescriptorProto::TYPE_SINT64; + result["bytes"] = FieldDescriptorProto::TYPE_BYTES; + result["uint32"] = FieldDescriptorProto::TYPE_UINT32; + result["sfixed32"] = FieldDescriptorProto::TYPE_SFIXED32; + result["sfixed64"] = FieldDescriptorProto::TYPE_SFIXED64; + result["int32"] = FieldDescriptorProto::TYPE_INT32; + result["int64"] = FieldDescriptorProto::TYPE_INT64; + result["sint32"] = FieldDescriptorProto::TYPE_SINT32; + result["sint64"] = FieldDescriptorProto::TYPE_SINT64; - return result; + return result; + }()); + return *table; } -const TypeNameMap kTypeNames = MakeTypeNameTable(); - // Camel-case the field name and append "Entry" for generated map entry name. // e.g. map<KeyType, ValueType> foo_map => FooMapEntry std::string MapEntryName(const std::string& field_name) { @@ -976,37 +977,14 @@ if (TryConsume("map")) { if (LookingAt("<")) { map_field.is_map_field = true; + DO(ParseMapType(&map_field, field, location)); } else { // False positive type_parsed = true; type_name = "map"; } } - if (map_field.is_map_field) { - if (field->has_oneof_index()) { - AddError("Map fields are not allowed in oneofs."); - return false; - } - if (field->has_label()) { - AddError( - "Field labels (required/optional/repeated) are not allowed on " - "map fields."); - return false; - } - if (field->has_extendee()) { - AddError("Map fields are not allowed to be extensions."); - return false; - } - field->set_label(FieldDescriptorProto::LABEL_REPEATED); - DO(Consume("<")); - DO(ParseType(&map_field.key_type, &map_field.key_type_name)); - DO(Consume(",")); - DO(ParseType(&map_field.value_type, &map_field.value_type_name)); - DO(Consume(">")); - // Defer setting of the type name of the map field until the - // field name is parsed. Add the source location though. - location.AddPath(FieldDescriptorProto::kTypeNameFieldNumber); - } else { + if (!map_field.is_map_field) { // Handle the case where no explicit label is given for a non-map field. if (!field->has_label() && DefaultToOptionalFields()) { field->set_label(FieldDescriptorProto::LABEL_OPTIONAL); @@ -1018,8 +996,8 @@ field->set_label(FieldDescriptorProto::LABEL_OPTIONAL); } - // Handle the case where the actual type is a message or enum named "map", - // which we already consumed in the code above. + // Handle the case where the actual type is a message or enum named + // "map", which we already consumed in the code above. if (!type_parsed) { DO(ParseType(&type, &type_name)); } @@ -1127,6 +1105,34 @@ return true; } +bool Parser::ParseMapType(MapField* map_field, FieldDescriptorProto* field, + LocationRecorder& type_name_location) { + if (field->has_oneof_index()) { + AddError("Map fields are not allowed in oneofs."); + return false; + } + if (field->has_label()) { + AddError( + "Field labels (required/optional/repeated) are not allowed on " + "map fields."); + return false; + } + if (field->has_extendee()) { + AddError("Map fields are not allowed to be extensions."); + return false; + } + field->set_label(FieldDescriptorProto::LABEL_REPEATED); + DO(Consume("<")); + DO(ParseType(&map_field->key_type, &map_field->key_type_name)); + DO(Consume(",")); + DO(ParseType(&map_field->value_type, &map_field->value_type_name)); + DO(Consume(">")); + // Defer setting of the type name of the map field until the + // field name is parsed. Add the source location though. + type_name_location.AddPath(FieldDescriptorProto::kTypeNameFieldNumber); + return true; +} + void Parser::GenerateMapEntry(const MapField& map_field, FieldDescriptorProto* field, RepeatedPtrField<DescriptorProto>* messages) { @@ -2265,8 +2271,9 @@ bool Parser::ParseType(FieldDescriptorProto::Type* type, std::string* type_name) { - TypeNameMap::const_iterator iter = kTypeNames.find(input_->current().text); - if (iter != kTypeNames.end()) { + const auto& type_names_table = GetTypeNameTable(); + auto iter = type_names_table.find(input_->current().text); + if (iter != type_names_table.end()) { *type = iter->second; input_->Next(); } else { @@ -2278,8 +2285,9 @@ bool Parser::ParseUserDefinedType(std::string* type_name) { type_name->clear(); - TypeNameMap::const_iterator iter = kTypeNames.find(input_->current().text); - if (iter != kTypeNames.end()) { + const auto& type_names_table = GetTypeNameTable(); + auto iter = type_names_table.find(input_->current().text); + if (iter != type_names_table.end()) { // Note: The only place enum types are allowed is for field types, but // if we are parsing a field type then we would not get here because // primitives are allowed there as well. So this error message doesn't
diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index 7b42677..d4eb763 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h
@@ -122,6 +122,7 @@ private: class LocationRecorder; + struct MapField; // ================================================================= // Error recovery helpers @@ -378,6 +379,9 @@ const LocationRecorder& field_location, const FileDescriptorProto* containing_file); + bool ParseMapType(MapField* map_field, FieldDescriptorProto* field, + LocationRecorder& type_name_location); + // Parse an "extensions" declaration. bool ParseExtensions(DescriptorProto* message, const LocationRecorder& extensions_location, @@ -480,7 +484,7 @@ // Parses a single part of a multipart option name. A multipart name consists // of names separated by dots. Each name is either an identifier or a series // of identifiers separated by dots and enclosed in parentheses. E.g., - // "foo.(bar.baz).qux". + // "foo.(bar.baz).moo". bool ParseOptionNamePart(UninterpretedOption* uninterpreted_option, const LocationRecorder& part_location, const FileDescriptorProto* containing_file);
diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index 9027891..2d681d9 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc
@@ -1861,7 +1861,8 @@ "message Foo {\n" " optional int32 bar = 0;\n" "}\n", - "1:23: Field numbers must be positive integers.\n"); + "1:23: Field numbers must be positive integers.\n" + "1:23: Suggested field numbers for Foo: 1\n"); } TEST_F(ParserValidationErrorTest, FieldExtendeeError) { @@ -1926,7 +1927,8 @@ "message Foo {\n" " extensions 0;\n" "}\n", - "1:13: Extension numbers must be positive integers.\n"); + "1:13: Extension numbers must be positive integers.\n" + "1:13: Suggested field numbers for Foo: 1\n"); } TEST_F(ParserValidationErrorTest, Proto3ExtensionError) {
diff --git a/src/google/protobuf/compiler/php/php_generator.cc b/src/google/protobuf/compiler/php/php_generator.cc index b911044..1426112 100644 --- a/src/google/protobuf/compiler/php/php_generator.cc +++ b/src/google/protobuf/compiler/php/php_generator.cc
@@ -48,29 +48,29 @@ const std::string kDescriptorDirName = "Google/Protobuf/Internal"; const std::string kDescriptorPackageName = "Google\\Protobuf\\Internal"; const char* const kReservedNames[] = { - "abstract", "and", "array", "as", "break", - "callable", "case", "catch", "class", "clone", - "const", "continue", "declare", "default", "die", - "do", "echo", "else", "elseif", "empty", - "enddeclare", "endfor", "endforeach", "endif", "endswitch", - "endwhile", "eval", "exit", "extends", "final", - "finally", "fn", "for", "foreach", "function", - "global", "goto", "if", "implements", "include", - "include_once", "instanceof", "insteadof", "interface", "isset", - "list", "match", "namespace", "new", "or", - "parent", "print", "private", "protected", "public", - "require", "require_once", "return", "self", "static", - "switch", "throw", "trait", "try", "unset", - "use", "var", "while", "xor", "yield", - "int", "float", "bool", "string", "true", - "false", "null", "void", "iterable"}; + "abstract", "and", "array", "as", "break", + "callable", "case", "catch", "class", "clone", + "const", "continue", "declare", "default", "die", + "do", "echo", "else", "elseif", "empty", + "enddeclare", "endfor", "endforeach", "endif", "endswitch", + "endwhile", "eval", "exit", "extends", "final", + "finally", "fn", "for", "foreach", "function", + "global", "goto", "if", "implements", "include", + "include_once", "instanceof", "insteadof", "interface", "isset", + "list", "match", "namespace", "new", "or", + "parent", "print", "private", "protected", "public", + "readonly", "require", "require_once", "return", "self", + "static", "switch", "throw", "trait", "try", + "unset", "use", "var", "while", "xor", + "yield", "int", "float", "bool", "string", + "true", "false", "null", "void", "iterable"}; const char* const kValidConstantNames[] = { "int", "float", "bool", "string", "true", "false", "null", "void", "iterable", "parent", - "self" + "self", "readonly" }; -const int kReservedNamesSize = 79; -const int kValidConstantNamesSize = 11; +const int kReservedNamesSize = 80; +const int kValidConstantNamesSize = 12; const int kFieldSetter = 1; const int kFieldGetter = 2; const int kFieldProperty = 3; @@ -420,6 +420,16 @@ return result + ".php"; } +template <typename DescriptorType> +std::string LegacyReadOnlyGeneratedClassFileName(const DescriptorType* desc, + const Options& options) { + std::string php_namespace = RootPhpNamespace(desc, options); + if (!php_namespace.empty()) { + return php_namespace + "/" + desc->name() + ".php"; + } + return desc->name() + ".php"; +} + std::string GeneratedServiceFileName(const ServiceDescriptor* service, const Options& options) { std::string result = FullClassName(service, options) + "Interface"; @@ -490,9 +500,9 @@ // accommodate for edge case with multiple types. size_t start_pos = type.find("|"); if (start_pos != std::string::npos) { - type.replace(start_pos, 1, "[]|"); + type.replace(start_pos, 1, ">|array<"); } - type += "[]|\\Google\\Protobuf\\Internal\\RepeatedField"; + type = "array<" + type + ">|\\Google\\Protobuf\\Internal\\RepeatedField"; } return type; } @@ -1302,6 +1312,32 @@ "fullname", newname); } +template <typename DescriptorType> +void LegacyReadOnlyGenerateClassFile(const FileDescriptor* file, + const DescriptorType* desc, const Options& options, + GeneratorContext* generator_context) { + std::string filename = LegacyReadOnlyGeneratedClassFileName(desc, options); + std::unique_ptr<io::ZeroCopyOutputStream> output( + generator_context->Open(filename)); + io::Printer printer(output.get(), '^'); + + GenerateHead(file, &printer); + + std::string php_namespace = RootPhpNamespace(desc, options); + if (!php_namespace.empty()) { + printer.Print( + "namespace ^name^;\n\n", + "name", php_namespace); + } + std::string newname = FullClassName(desc, options); + printer.Print("class_exists(^new^::class);\n", + "new", GeneratedClassNameImpl(desc)); + printer.Print("@trigger_error(__NAMESPACE__ . '\\^old^ is deprecated and will be removed in " + "the next major release. Use ^fullname^ instead', E_USER_DEPRECATED);\n\n", + "old", desc->name(), + "fullname", newname); +} + void GenerateEnumFile(const FileDescriptor* file, const EnumDescriptor* en, const Options& options, GeneratorContext* generator_context) { @@ -1405,6 +1441,19 @@ "old", LegacyFullClassName(en, options)); LegacyGenerateClassFile(file, en, options, generator_context); } + + // Write legacy file for backwards compatibility with "readonly" keywword + std::string lower = en->name(); + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + if (lower == "readonly") { + printer.Print( + "// Adding a class alias for backwards compatibility with the \"readonly\" keyword.\n"); + printer.Print( + "class_alias(^new^::class, __NAMESPACE__ . '\\^old^');\n\n", + "new", fullname, + "old", en->name()); + LegacyReadOnlyGenerateClassFile(file, en, options, generator_context); + } } void GenerateMessageFile(const FileDescriptor* file, const Descriptor* message, @@ -1521,6 +1570,19 @@ LegacyGenerateClassFile(file, message, options, generator_context); } + // Write legacy file for backwards compatibility with "readonly" keywword + std::string lower = message->name(); + std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); + if (lower == "readonly") { + printer.Print( + "// Adding a class alias for backwards compatibility with the \"readonly\" keyword.\n"); + printer.Print( + "class_alias(^new^::class, __NAMESPACE__ . '\\^old^');\n\n", + "new", fullname, + "old", message->name()); + LegacyReadOnlyGenerateClassFile(file, message, options, generator_context); + } + // Nested messages and enums. for (int i = 0; i < message->nested_type_count(); i++) { GenerateMessageFile(file, message->nested_type(i), options,
diff --git a/src/google/protobuf/compiler/plugin.cc b/src/google/protobuf/compiler/plugin.cc index 25ca5f0..0a32384 100644 --- a/src/google/protobuf/compiler/plugin.cc +++ b/src/google/protobuf/compiler/plugin.cc
@@ -45,9 +45,10 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/compiler/plugin.pb.h> #include <google/protobuf/compiler/code_generator.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/descriptor.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/io_win32.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> namespace google {
diff --git a/src/google/protobuf/compiler/plugin.pb.cc b/src/google/protobuf/compiler/plugin.pb.cc index 61a6700..0a25b0c 100644 --- a/src/google/protobuf/compiler/plugin.pb.cc +++ b/src/google/protobuf/compiler/plugin.pb.cc
@@ -23,11 +23,13 @@ PROTOBUF_NAMESPACE_OPEN namespace compiler { PROTOBUF_CONSTEXPR Version::Version( - ::_pbi::ConstantInitialized) - : suffix_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , major_(0) - , minor_(0) - , patch_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.suffix_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.major_)*/0 + , /*decltype(_impl_.minor_)*/0 + , /*decltype(_impl_.patch_)*/0} {} struct VersionDefaultTypeInternal { PROTOBUF_CONSTEXPR VersionDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -38,11 +40,13 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 VersionDefaultTypeInternal _Version_default_instance_; PROTOBUF_CONSTEXPR CodeGeneratorRequest::CodeGeneratorRequest( - ::_pbi::ConstantInitialized) - : file_to_generate_() - , proto_file_() - , parameter_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , compiler_version_(nullptr){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.file_to_generate_)*/{} + , /*decltype(_impl_.proto_file_)*/{} + , /*decltype(_impl_.parameter_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.compiler_version_)*/nullptr} {} struct CodeGeneratorRequestDefaultTypeInternal { PROTOBUF_CONSTEXPR CodeGeneratorRequestDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -53,11 +57,13 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 CodeGeneratorRequestDefaultTypeInternal _CodeGeneratorRequest_default_instance_; PROTOBUF_CONSTEXPR CodeGeneratorResponse_File::CodeGeneratorResponse_File( - ::_pbi::ConstantInitialized) - : name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , insertion_point_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , content_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , generated_code_info_(nullptr){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.insertion_point_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.content_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.generated_code_info_)*/nullptr} {} struct CodeGeneratorResponse_FileDefaultTypeInternal { PROTOBUF_CONSTEXPR CodeGeneratorResponse_FileDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -68,10 +74,12 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 CodeGeneratorResponse_FileDefaultTypeInternal _CodeGeneratorResponse_File_default_instance_; PROTOBUF_CONSTEXPR CodeGeneratorResponse::CodeGeneratorResponse( - ::_pbi::ConstantInitialized) - : file_() - , error_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , supported_features_(uint64_t{0u}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.file_)*/{} + , /*decltype(_impl_.error_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.supported_features_)*/uint64_t{0u}} {} struct CodeGeneratorResponseDefaultTypeInternal { PROTOBUF_CONSTEXPR CodeGeneratorResponseDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -88,57 +96,57 @@ static constexpr ::_pb::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fcompiler_2fplugin_2eproto = nullptr; const uint32_t TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, major_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, minor_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, patch_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, suffix_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, _impl_.major_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, _impl_.minor_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, _impl_.patch_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::Version, _impl_.suffix_), 1, 2, 3, 0, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, file_to_generate_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, parameter_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, proto_file_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, compiler_version_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _impl_.file_to_generate_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _impl_.parameter_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _impl_.proto_file_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorRequest, _impl_.compiler_version_), ~0u, 0, ~0u, 1, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, insertion_point_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, content_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, generated_code_info_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _impl_.insertion_point_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _impl_.content_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File, _impl_.generated_code_info_), 0, 1, 2, 3, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - 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_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, _impl_.error_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, _impl_.supported_features_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse, _impl_.file_), 0, 1, ~0u, @@ -225,7 +233,7 @@ class Version::_Internal { public: - using HasBits = decltype(std::declval<Version>()._has_bits_); + using HasBits = decltype(std::declval<Version>()._impl_._has_bits_); static void set_has_major(HasBits* has_bits) { (*has_bits)[0] |= 2u; } @@ -243,36 +251,50 @@ Version::Version(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.compiler.Version) } Version::Version(const Version& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.suffix_){} + , decltype(_impl_.major_){} + , decltype(_impl_.minor_){} + , decltype(_impl_.patch_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - suffix_.InitDefault(); + _impl_.suffix_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - suffix_.Set("", GetArenaForAllocation()); + _impl_.suffix_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_suffix()) { - suffix_.Set(from._internal_suffix(), + _impl_.suffix_.Set(from._internal_suffix(), GetArenaForAllocation()); } - ::memcpy(&major_, &from.major_, - static_cast<size_t>(reinterpret_cast<char*>(&patch_) - - reinterpret_cast<char*>(&major_)) + sizeof(patch_)); + ::memcpy(&_impl_.major_, &from._impl_.major_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.patch_) - + reinterpret_cast<char*>(&_impl_.major_)) + sizeof(_impl_.patch_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.Version) } -inline void Version::SharedCtor() { -suffix_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - suffix_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&major_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&patch_) - - reinterpret_cast<char*>(&major_)) + sizeof(patch_)); +inline void Version::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.suffix_){} + , decltype(_impl_.major_){0} + , decltype(_impl_.minor_){0} + , decltype(_impl_.patch_){0} + }; + _impl_.suffix_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.suffix_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Version::~Version() { @@ -286,11 +308,11 @@ inline void Version::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - suffix_.Destroy(); + _impl_.suffix_.Destroy(); } void Version::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Version::Clear() { @@ -299,16 +321,16 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000001u) { - suffix_.ClearNonDefaultToEmpty(); + _impl_.suffix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x0000000eu) { - ::memset(&major_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&patch_) - - reinterpret_cast<char*>(&major_)) + sizeof(patch_)); + ::memset(&_impl_.major_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.patch_) - + reinterpret_cast<char*>(&_impl_.major_)) + sizeof(_impl_.patch_)); } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -323,7 +345,7 @@ case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { _Internal::set_has_major(&has_bits); - major_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.major_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -332,7 +354,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_minor(&has_bits); - minor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.minor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -341,7 +363,7 @@ case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) { _Internal::set_has_patch(&has_bits); - patch_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.patch_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -374,7 +396,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -388,7 +410,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional int32 major = 1; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); @@ -433,7 +455,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { // optional string suffix = 4; if (cached_has_bits & 0x00000001u) { @@ -458,11 +480,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Version::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Version::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Version::GetClassData() const { return &_class_data_; } @@ -480,21 +502,21 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { _internal_set_suffix(from._internal_suffix()); } if (cached_has_bits & 0x00000002u) { - major_ = from.major_; + _impl_.major_ = from._impl_.major_; } if (cached_has_bits & 0x00000004u) { - minor_ = from.minor_; + _impl_.minor_ = from._impl_.minor_; } if (cached_has_bits & 0x00000008u) { - patch_ = from.patch_; + _impl_.patch_ = from._impl_.patch_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -515,17 +537,17 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &suffix_, lhs_arena, - &other->suffix_, rhs_arena + &_impl_.suffix_, lhs_arena, + &other->_impl_.suffix_, rhs_arena ); ::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_FIELD_OFFSET(Version, _impl_.patch_) + + sizeof(Version::_impl_.patch_) + - PROTOBUF_FIELD_OFFSET(Version, _impl_.major_)>( + reinterpret_cast<char*>(&_impl_.major_), + reinterpret_cast<char*>(&other->_impl_.major_)); } ::PROTOBUF_NAMESPACE_ID::Metadata Version::GetMetadata() const { @@ -538,7 +560,7 @@ class CodeGeneratorRequest::_Internal { public: - using HasBits = decltype(std::declval<CodeGeneratorRequest>()._has_bits_); + using HasBits = decltype(std::declval<CodeGeneratorRequest>()._impl_._has_bits_); static void set_has_parameter(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -550,47 +572,58 @@ const ::PROTOBUF_NAMESPACE_ID::compiler::Version& CodeGeneratorRequest::_Internal::compiler_version(const CodeGeneratorRequest* msg) { - return *msg->compiler_version_; + return *msg->_impl_.compiler_version_; } void CodeGeneratorRequest::clear_proto_file() { - proto_file_.Clear(); + _impl_.proto_file_.Clear(); } CodeGeneratorRequest::CodeGeneratorRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - file_to_generate_(arena), - proto_file_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.compiler.CodeGeneratorRequest) } CodeGeneratorRequest::CodeGeneratorRequest(const CodeGeneratorRequest& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - file_to_generate_(from.file_to_generate_), - proto_file_(from.proto_file_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.file_to_generate_){from._impl_.file_to_generate_} + , decltype(_impl_.proto_file_){from._impl_.proto_file_} + , decltype(_impl_.parameter_){} + , decltype(_impl_.compiler_version_){nullptr}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - parameter_.InitDefault(); + _impl_.parameter_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - parameter_.Set("", GetArenaForAllocation()); + _impl_.parameter_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_parameter()) { - parameter_.Set(from._internal_parameter(), + _impl_.parameter_.Set(from._internal_parameter(), GetArenaForAllocation()); } if (from._internal_has_compiler_version()) { - compiler_version_ = new ::PROTOBUF_NAMESPACE_ID::compiler::Version(*from.compiler_version_); - } else { - compiler_version_ = nullptr; + _impl_.compiler_version_ = new ::PROTOBUF_NAMESPACE_ID::compiler::Version(*from._impl_.compiler_version_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorRequest) } -inline void CodeGeneratorRequest::SharedCtor() { -parameter_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - parameter_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -compiler_version_ = nullptr; +inline void CodeGeneratorRequest::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.file_to_generate_){arena} + , decltype(_impl_.proto_file_){arena} + , decltype(_impl_.parameter_){} + , decltype(_impl_.compiler_version_){nullptr} + }; + _impl_.parameter_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.parameter_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } CodeGeneratorRequest::~CodeGeneratorRequest() { @@ -604,12 +637,14 @@ inline void CodeGeneratorRequest::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - parameter_.Destroy(); - if (this != internal_default_instance()) delete compiler_version_; + _impl_.file_to_generate_.~RepeatedPtrField(); + _impl_.proto_file_.~RepeatedPtrField(); + _impl_.parameter_.Destroy(); + if (this != internal_default_instance()) delete _impl_.compiler_version_; } void CodeGeneratorRequest::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void CodeGeneratorRequest::Clear() { @@ -618,19 +653,19 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - file_to_generate_.Clear(); - proto_file_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.file_to_generate_.Clear(); + _impl_.proto_file_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - parameter_.ClearNonDefaultToEmpty(); + _impl_.parameter_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(compiler_version_ != nullptr); - compiler_version_->Clear(); + GOOGLE_DCHECK(_impl_.compiler_version_ != nullptr); + _impl_.compiler_version_->Clear(); } } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -707,7 +742,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -731,7 +766,7 @@ target = stream->WriteString(1, s, target); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string parameter = 2; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -775,20 +810,20 @@ // repeated string file_to_generate = 1; total_size += 1 * - ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(file_to_generate_.size()); - for (int i = 0, n = file_to_generate_.size(); i < n; i++) { + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(_impl_.file_to_generate_.size()); + for (int i = 0, n = _impl_.file_to_generate_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( - file_to_generate_.Get(i)); + _impl_.file_to_generate_.Get(i)); } // repeated .google.protobuf.FileDescriptorProto proto_file = 15; total_size += 1UL * this->_internal_proto_file_size(); - for (const auto& msg : this->proto_file_) { + for (const auto& msg : this->_impl_.proto_file_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string parameter = 2; if (cached_has_bits & 0x00000001u) { @@ -801,15 +836,15 @@ if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *compiler_version_); + *_impl_.compiler_version_); } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData CodeGeneratorRequest::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, CodeGeneratorRequest::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*CodeGeneratorRequest::GetClassData() const { return &_class_data_; } @@ -827,9 +862,9 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - file_to_generate_.MergeFrom(from.file_to_generate_); - proto_file_.MergeFrom(from.proto_file_); - cached_has_bits = from._has_bits_[0]; + _impl_.file_to_generate_.MergeFrom(from._impl_.file_to_generate_); + _impl_.proto_file_.MergeFrom(from._impl_.proto_file_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_parameter(from._internal_parameter()); @@ -849,7 +884,7 @@ } bool CodeGeneratorRequest::IsInitialized() const { - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(proto_file_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.proto_file_)) return false; return true; } @@ -859,14 +894,14 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&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_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.file_to_generate_.InternalSwap(&other->_impl_.file_to_generate_); + _impl_.proto_file_.InternalSwap(&other->_impl_.proto_file_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - ¶meter_, lhs_arena, - &other->parameter_, rhs_arena + &_impl_.parameter_, lhs_arena, + &other->_impl_.parameter_, rhs_arena ); - swap(compiler_version_, other->compiler_version_); + swap(_impl_.compiler_version_, other->_impl_.compiler_version_); } ::PROTOBUF_NAMESPACE_ID::Metadata CodeGeneratorRequest::GetMetadata() const { @@ -879,7 +914,7 @@ class CodeGeneratorResponse_File::_Internal { public: - using HasBits = decltype(std::declval<CodeGeneratorResponse_File>()._has_bits_); + using HasBits = decltype(std::declval<CodeGeneratorResponse_File>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -897,68 +932,83 @@ const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo& CodeGeneratorResponse_File::_Internal::generated_code_info(const CodeGeneratorResponse_File* msg) { - return *msg->generated_code_info_; + return *msg->_impl_.generated_code_info_; } void CodeGeneratorResponse_File::clear_generated_code_info() { - if (generated_code_info_ != nullptr) generated_code_info_->Clear(); - _has_bits_[0] &= ~0x00000008u; + if (_impl_.generated_code_info_ != nullptr) _impl_.generated_code_info_->Clear(); + _impl_._has_bits_[0] &= ~0x00000008u; } CodeGeneratorResponse_File::CodeGeneratorResponse_File(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.compiler.CodeGeneratorResponse.File) } CodeGeneratorResponse_File::CodeGeneratorResponse_File(const CodeGeneratorResponse_File& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.insertion_point_){} + , decltype(_impl_.content_){} + , decltype(_impl_.generated_code_info_){nullptr}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - insertion_point_.InitDefault(); + _impl_.insertion_point_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - insertion_point_.Set("", GetArenaForAllocation()); + _impl_.insertion_point_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_insertion_point()) { - insertion_point_.Set(from._internal_insertion_point(), + _impl_.insertion_point_.Set(from._internal_insertion_point(), GetArenaForAllocation()); } - content_.InitDefault(); + _impl_.content_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - content_.Set("", GetArenaForAllocation()); + _impl_.content_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_content()) { - content_.Set(from._internal_content(), + _impl_.content_.Set(from._internal_content(), GetArenaForAllocation()); } if (from._internal_has_generated_code_info()) { - generated_code_info_ = new ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo(*from.generated_code_info_); - } else { - generated_code_info_ = nullptr; + _impl_.generated_code_info_ = new ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo(*from._impl_.generated_code_info_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse.File) } -inline void CodeGeneratorResponse_File::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -insertion_point_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - insertion_point_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -content_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - content_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -generated_code_info_ = nullptr; +inline void CodeGeneratorResponse_File::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.insertion_point_){} + , decltype(_impl_.content_){} + , decltype(_impl_.generated_code_info_){nullptr} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.insertion_point_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.insertion_point_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.content_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.content_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } CodeGeneratorResponse_File::~CodeGeneratorResponse_File() { @@ -972,14 +1022,14 @@ inline void CodeGeneratorResponse_File::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - insertion_point_.Destroy(); - content_.Destroy(); - if (this != internal_default_instance()) delete generated_code_info_; + _impl_.name_.Destroy(); + _impl_.insertion_point_.Destroy(); + _impl_.content_.Destroy(); + if (this != internal_default_instance()) delete _impl_.generated_code_info_; } void CodeGeneratorResponse_File::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void CodeGeneratorResponse_File::Clear() { @@ -988,23 +1038,23 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - insertion_point_.ClearNonDefaultToEmpty(); + _impl_.insertion_point_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - content_.ClearNonDefaultToEmpty(); + _impl_.content_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(generated_code_info_ != nullptr); - generated_code_info_->Clear(); + GOOGLE_DCHECK(_impl_.generated_code_info_ != nullptr); + _impl_.generated_code_info_->Clear(); } } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1075,7 +1125,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -1089,7 +1139,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -1143,7 +1193,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -1170,15 +1220,15 @@ if (cached_has_bits & 0x00000008u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *generated_code_info_); + *_impl_.generated_code_info_); } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData CodeGeneratorResponse_File::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, CodeGeneratorResponse_File::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*CodeGeneratorResponse_File::GetClassData() const { return &_class_data_; } @@ -1196,7 +1246,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -1230,20 +1280,20 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &insertion_point_, lhs_arena, - &other->insertion_point_, rhs_arena + &_impl_.insertion_point_, lhs_arena, + &other->_impl_.insertion_point_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &content_, lhs_arena, - &other->content_, rhs_arena + &_impl_.content_, lhs_arena, + &other->_impl_.content_, rhs_arena ); - swap(generated_code_info_, other->generated_code_info_); + swap(_impl_.generated_code_info_, other->_impl_.generated_code_info_); } ::PROTOBUF_NAMESPACE_ID::Metadata CodeGeneratorResponse_File::GetMetadata() const { @@ -1256,7 +1306,7 @@ class CodeGeneratorResponse::_Internal { public: - using HasBits = decltype(std::declval<CodeGeneratorResponse>()._has_bits_); + using HasBits = decltype(std::declval<CodeGeneratorResponse>()._impl_._has_bits_); static void set_has_error(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -1267,34 +1317,47 @@ CodeGeneratorResponse::CodeGeneratorResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - file_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.compiler.CodeGeneratorResponse) } CodeGeneratorResponse::CodeGeneratorResponse(const CodeGeneratorResponse& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - file_(from.file_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.file_){from._impl_.file_} + , decltype(_impl_.error_){} + , decltype(_impl_.supported_features_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - error_.InitDefault(); + _impl_.error_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - error_.Set("", GetArenaForAllocation()); + _impl_.error_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_error()) { - error_.Set(from._internal_error(), + _impl_.error_.Set(from._internal_error(), GetArenaForAllocation()); } - supported_features_ = from.supported_features_; + _impl_.supported_features_ = from._impl_.supported_features_; // @@protoc_insertion_point(copy_constructor:google.protobuf.compiler.CodeGeneratorResponse) } -inline void CodeGeneratorResponse::SharedCtor() { -error_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - error_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -supported_features_ = uint64_t{0u}; +inline void CodeGeneratorResponse::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.file_){arena} + , decltype(_impl_.error_){} + , decltype(_impl_.supported_features_){uint64_t{0u}} + }; + _impl_.error_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.error_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } CodeGeneratorResponse::~CodeGeneratorResponse() { @@ -1308,11 +1371,12 @@ inline void CodeGeneratorResponse::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - error_.Destroy(); + _impl_.file_.~RepeatedPtrField(); + _impl_.error_.Destroy(); } void CodeGeneratorResponse::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void CodeGeneratorResponse::Clear() { @@ -1321,13 +1385,13 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - file_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.file_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000001u) { - error_.ClearNonDefaultToEmpty(); + _impl_.error_.ClearNonDefaultToEmpty(); } - supported_features_ = uint64_t{0u}; - _has_bits_.Clear(); + _impl_.supported_features_ = uint64_t{0u}; + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1354,7 +1418,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_supported_features(&has_bits); - supported_features_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.supported_features_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -1388,7 +1452,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -1402,7 +1466,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string error = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -1445,12 +1509,12 @@ // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; total_size += 1UL * this->_internal_file_size(); - for (const auto& msg : this->file_) { + for (const auto& msg : this->_impl_.file_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string error = 1; if (cached_has_bits & 0x00000001u) { @@ -1465,11 +1529,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData CodeGeneratorResponse::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, CodeGeneratorResponse::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*CodeGeneratorResponse::GetClassData() const { return &_class_data_; } @@ -1487,16 +1551,16 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - file_.MergeFrom(from.file_); - cached_has_bits = from._has_bits_[0]; + _impl_.file_.MergeFrom(from._impl_.file_); + cached_has_bits = from._impl_._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_; + _impl_.supported_features_ = from._impl_.supported_features_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -1517,13 +1581,13 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - file_.InternalSwap(&other->file_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.file_.InternalSwap(&other->_impl_.file_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &error_, lhs_arena, - &other->error_, rhs_arena + &_impl_.error_, lhs_arena, + &other->_impl_.error_, rhs_arena ); - swap(supported_features_, other->supported_features_); + swap(_impl_.supported_features_, other->_impl_.supported_features_); } ::PROTOBUF_NAMESPACE_ID::Metadata CodeGeneratorResponse::GetMetadata() const {
diff --git a/src/google/protobuf/compiler/plugin.pb.h b/src/google/protobuf/compiler/plugin.pb.h index 616c595..07bbaa3 100644 --- a/src/google/protobuf/compiler/plugin.pb.h +++ b/src/google/protobuf/compiler/plugin.pb.h
@@ -200,10 +200,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Version* other); @@ -297,12 +297,15 @@ 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_; - int32_t major_; - int32_t minor_; - int32_t patch_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr suffix_; + int32_t major_; + int32_t minor_; + int32_t patch_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- @@ -405,10 +408,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorRequest* other); @@ -523,12 +526,15 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto > proto_file_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr parameter_; - ::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version_; + struct Impl_ { + ::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_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto > proto_file_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr parameter_; + ::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- @@ -631,10 +637,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse_File* other); @@ -743,12 +749,15 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr insertion_point_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr content_; - ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr insertion_point_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr content_; + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // ------------------------------------------------------------------- @@ -851,10 +860,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CodeGeneratorResponse* other); @@ -971,11 +980,14 @@ 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_; - uint64_t supported_features_; + struct Impl_ { + ::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_; + uint64_t supported_features_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fcompiler_2fplugin_2eproto; }; // =================================================================== @@ -991,26 +1003,26 @@ // optional int32 major = 1; inline bool Version::_internal_has_major() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool Version::has_major() const { return _internal_has_major(); } inline void Version::clear_major() { - major_ = 0; - _has_bits_[0] &= ~0x00000002u; + _impl_.major_ = 0; + _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t Version::_internal_major() const { - return major_; + return _impl_.major_; } inline int32_t Version::major() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.major) return _internal_major(); } inline void Version::_internal_set_major(int32_t value) { - _has_bits_[0] |= 0x00000002u; - major_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.major_ = value; } inline void Version::set_major(int32_t value) { _internal_set_major(value); @@ -1019,26 +1031,26 @@ // optional int32 minor = 2; inline bool Version::_internal_has_minor() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool Version::has_minor() const { return _internal_has_minor(); } inline void Version::clear_minor() { - minor_ = 0; - _has_bits_[0] &= ~0x00000004u; + _impl_.minor_ = 0; + _impl_._has_bits_[0] &= ~0x00000004u; } inline int32_t Version::_internal_minor() const { - return minor_; + return _impl_.minor_; } inline int32_t Version::minor() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.minor) return _internal_minor(); } inline void Version::_internal_set_minor(int32_t value) { - _has_bits_[0] |= 0x00000004u; - minor_ = value; + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.minor_ = value; } inline void Version::set_minor(int32_t value) { _internal_set_minor(value); @@ -1047,26 +1059,26 @@ // optional int32 patch = 3; inline bool Version::_internal_has_patch() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool Version::has_patch() const { return _internal_has_patch(); } inline void Version::clear_patch() { - patch_ = 0; - _has_bits_[0] &= ~0x00000008u; + _impl_.patch_ = 0; + _impl_._has_bits_[0] &= ~0x00000008u; } inline int32_t Version::_internal_patch() const { - return patch_; + return _impl_.patch_; } inline int32_t Version::patch() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.patch) return _internal_patch(); } inline void Version::_internal_set_patch(int32_t value) { - _has_bits_[0] |= 0x00000008u; - patch_ = value; + _impl_._has_bits_[0] |= 0x00000008u; + _impl_.patch_ = value; } inline void Version::set_patch(int32_t value) { _internal_set_patch(value); @@ -1075,15 +1087,15 @@ // optional string suffix = 4; inline bool Version::_internal_has_suffix() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool Version::has_suffix() const { return _internal_has_suffix(); } inline void Version::clear_suffix() { - suffix_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.suffix_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& Version::suffix() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.Version.suffix) @@ -1092,8 +1104,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void Version::set_suffix(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - suffix_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.suffix_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.Version.suffix) } inline std::string* Version::mutable_suffix() { @@ -1102,40 +1114,40 @@ return _s; } inline const std::string& Version::_internal_suffix() const { - return suffix_.Get(); + return _impl_.suffix_.Get(); } inline void Version::_internal_set_suffix(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - suffix_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.suffix_.Set(value, GetArenaForAllocation()); } inline std::string* Version::_internal_mutable_suffix() { - _has_bits_[0] |= 0x00000001u; - return suffix_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.suffix_.Mutable(GetArenaForAllocation()); } inline std::string* Version::release_suffix() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.Version.suffix) if (!_internal_has_suffix()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = suffix_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.suffix_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (suffix_.IsDefault()) { - suffix_.Set("", GetArenaForAllocation()); + if (_impl_.suffix_.IsDefault()) { + _impl_.suffix_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void Version::set_allocated_suffix(std::string* suffix) { if (suffix != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - suffix_.SetAllocated(suffix, GetArenaForAllocation()); + _impl_.suffix_.SetAllocated(suffix, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (suffix_.IsDefault()) { - suffix_.Set("", GetArenaForAllocation()); + if (_impl_.suffix_.IsDefault()) { + _impl_.suffix_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.Version.suffix) @@ -1147,13 +1159,13 @@ // repeated string file_to_generate = 1; inline int CodeGeneratorRequest::_internal_file_to_generate_size() const { - return file_to_generate_.size(); + return _impl_.file_to_generate_.size(); } inline int CodeGeneratorRequest::file_to_generate_size() const { return _internal_file_to_generate_size(); } inline void CodeGeneratorRequest::clear_file_to_generate() { - file_to_generate_.Clear(); + _impl_.file_to_generate_.Clear(); } inline std::string* CodeGeneratorRequest::add_file_to_generate() { std::string* _s = _internal_add_file_to_generate(); @@ -1161,7 +1173,7 @@ return _s; } inline const std::string& CodeGeneratorRequest::_internal_file_to_generate(int index) const { - return file_to_generate_.Get(index); + return _impl_.file_to_generate_.Get(index); } inline const std::string& CodeGeneratorRequest::file_to_generate(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) @@ -1169,68 +1181,68 @@ } inline std::string* CodeGeneratorRequest::mutable_file_to_generate(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) - return file_to_generate_.Mutable(index); + return _impl_.file_to_generate_.Mutable(index); } inline void CodeGeneratorRequest::set_file_to_generate(int index, const std::string& value) { - file_to_generate_.Mutable(index)->assign(value); + _impl_.file_to_generate_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } inline void CodeGeneratorRequest::set_file_to_generate(int index, std::string&& value) { - file_to_generate_.Mutable(index)->assign(std::move(value)); + _impl_.file_to_generate_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } inline void CodeGeneratorRequest::set_file_to_generate(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); - file_to_generate_.Mutable(index)->assign(value); + _impl_.file_to_generate_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } inline void CodeGeneratorRequest::set_file_to_generate(int index, const char* value, size_t size) { - file_to_generate_.Mutable(index)->assign( + _impl_.file_to_generate_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } inline std::string* CodeGeneratorRequest::_internal_add_file_to_generate() { - return file_to_generate_.Add(); + return _impl_.file_to_generate_.Add(); } inline void CodeGeneratorRequest::add_file_to_generate(const std::string& value) { - file_to_generate_.Add()->assign(value); + _impl_.file_to_generate_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } inline void CodeGeneratorRequest::add_file_to_generate(std::string&& value) { - file_to_generate_.Add(std::move(value)); + _impl_.file_to_generate_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } inline void CodeGeneratorRequest::add_file_to_generate(const char* value) { GOOGLE_DCHECK(value != nullptr); - file_to_generate_.Add()->assign(value); + _impl_.file_to_generate_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } inline void CodeGeneratorRequest::add_file_to_generate(const char* value, size_t size) { - file_to_generate_.Add()->assign(reinterpret_cast<const char*>(value), size); + _impl_.file_to_generate_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& CodeGeneratorRequest::file_to_generate() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) - return file_to_generate_; + return _impl_.file_to_generate_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* CodeGeneratorRequest::mutable_file_to_generate() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) - return &file_to_generate_; + return &_impl_.file_to_generate_; } // optional string parameter = 2; inline bool CodeGeneratorRequest::_internal_has_parameter() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CodeGeneratorRequest::has_parameter() const { return _internal_has_parameter(); } inline void CodeGeneratorRequest::clear_parameter() { - parameter_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.parameter_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CodeGeneratorRequest::parameter() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.parameter) @@ -1239,8 +1251,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CodeGeneratorRequest::set_parameter(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - parameter_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.parameter_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorRequest.parameter) } inline std::string* CodeGeneratorRequest::mutable_parameter() { @@ -1249,40 +1261,40 @@ return _s; } inline const std::string& CodeGeneratorRequest::_internal_parameter() const { - return parameter_.Get(); + return _impl_.parameter_.Get(); } inline void CodeGeneratorRequest::_internal_set_parameter(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - parameter_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.parameter_.Set(value, GetArenaForAllocation()); } inline std::string* CodeGeneratorRequest::_internal_mutable_parameter() { - _has_bits_[0] |= 0x00000001u; - return parameter_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.parameter_.Mutable(GetArenaForAllocation()); } inline std::string* CodeGeneratorRequest::release_parameter() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorRequest.parameter) if (!_internal_has_parameter()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = parameter_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.parameter_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (parameter_.IsDefault()) { - parameter_.Set("", GetArenaForAllocation()); + if (_impl_.parameter_.IsDefault()) { + _impl_.parameter_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CodeGeneratorRequest::set_allocated_parameter(std::string* parameter) { if (parameter != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - parameter_.SetAllocated(parameter, GetArenaForAllocation()); + _impl_.parameter_.SetAllocated(parameter, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (parameter_.IsDefault()) { - parameter_.Set("", GetArenaForAllocation()); + if (_impl_.parameter_.IsDefault()) { + _impl_.parameter_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.parameter) @@ -1290,29 +1302,29 @@ // repeated .google.protobuf.FileDescriptorProto proto_file = 15; inline int CodeGeneratorRequest::_internal_proto_file_size() const { - return proto_file_.size(); + return _impl_.proto_file_.size(); } inline int CodeGeneratorRequest::proto_file_size() const { return _internal_proto_file_size(); } inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* CodeGeneratorRequest::mutable_proto_file(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorRequest.proto_file) - return proto_file_.Mutable(index); + return _impl_.proto_file_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto >* CodeGeneratorRequest::mutable_proto_file() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file) - return &proto_file_; + return &_impl_.proto_file_; } inline const ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto& CodeGeneratorRequest::_internal_proto_file(int index) const { - return proto_file_.Get(index); + return _impl_.proto_file_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto& CodeGeneratorRequest::proto_file(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorRequest.proto_file) return _internal_proto_file(index); } inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* CodeGeneratorRequest::_internal_add_proto_file() { - return proto_file_.Add(); + return _impl_.proto_file_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* CodeGeneratorRequest::add_proto_file() { ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* _add = _internal_add_proto_file(); @@ -1322,24 +1334,24 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto >& CodeGeneratorRequest::proto_file() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorRequest.proto_file) - return proto_file_; + return _impl_.proto_file_; } // optional .google.protobuf.compiler.Version compiler_version = 3; inline bool CodeGeneratorRequest::_internal_has_compiler_version() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; - PROTOBUF_ASSUME(!value || compiler_version_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + PROTOBUF_ASSUME(!value || _impl_.compiler_version_ != nullptr); return value; } inline bool CodeGeneratorRequest::has_compiler_version() const { return _internal_has_compiler_version(); } inline void CodeGeneratorRequest::clear_compiler_version() { - if (compiler_version_ != nullptr) compiler_version_->Clear(); - _has_bits_[0] &= ~0x00000002u; + if (_impl_.compiler_version_ != nullptr) _impl_.compiler_version_->Clear(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const ::PROTOBUF_NAMESPACE_ID::compiler::Version& CodeGeneratorRequest::_internal_compiler_version() const { - const ::PROTOBUF_NAMESPACE_ID::compiler::Version* p = compiler_version_; + const ::PROTOBUF_NAMESPACE_ID::compiler::Version* p = _impl_.compiler_version_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::compiler::Version&>( ::PROTOBUF_NAMESPACE_ID::compiler::_Version_default_instance_); } @@ -1350,20 +1362,20 @@ inline void CodeGeneratorRequest::unsafe_arena_set_allocated_compiler_version( ::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(compiler_version_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.compiler_version_); } - compiler_version_ = compiler_version; + _impl_.compiler_version_ = compiler_version; if (compiler_version) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._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; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::compiler::Version* temp = _impl_.compiler_version_; + _impl_.compiler_version_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -1377,18 +1389,18 @@ } 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_; - compiler_version_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::compiler::Version* temp = _impl_.compiler_version_; + _impl_.compiler_version_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::_internal_mutable_compiler_version() { - _has_bits_[0] |= 0x00000002u; - if (compiler_version_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000002u; + if (_impl_.compiler_version_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::compiler::Version>(GetArenaForAllocation()); - compiler_version_ = p; + _impl_.compiler_version_ = p; } - return compiler_version_; + return _impl_.compiler_version_; } inline ::PROTOBUF_NAMESPACE_ID::compiler::Version* CodeGeneratorRequest::mutable_compiler_version() { ::PROTOBUF_NAMESPACE_ID::compiler::Version* _msg = _internal_mutable_compiler_version(); @@ -1398,7 +1410,7 @@ inline void CodeGeneratorRequest::set_allocated_compiler_version(::PROTOBUF_NAMESPACE_ID::compiler::Version* compiler_version) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete compiler_version_; + delete _impl_.compiler_version_; } if (compiler_version) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -1407,11 +1419,11 @@ compiler_version = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, compiler_version, submessage_arena); } - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - compiler_version_ = compiler_version; + _impl_.compiler_version_ = compiler_version; // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) } @@ -1421,15 +1433,15 @@ // optional string name = 1; inline bool CodeGeneratorResponse_File::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CodeGeneratorResponse_File::has_name() const { return _internal_has_name(); } inline void CodeGeneratorResponse_File::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CodeGeneratorResponse_File::name() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.name) @@ -1438,8 +1450,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CodeGeneratorResponse_File::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.name) } inline std::string* CodeGeneratorResponse_File::mutable_name() { @@ -1448,40 +1460,40 @@ return _s; } inline const std::string& CodeGeneratorResponse_File::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void CodeGeneratorResponse_File::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* CodeGeneratorResponse_File::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* CodeGeneratorResponse_File::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CodeGeneratorResponse_File::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.name) @@ -1489,15 +1501,15 @@ // optional string insertion_point = 2; inline bool CodeGeneratorResponse_File::_internal_has_insertion_point() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool CodeGeneratorResponse_File::has_insertion_point() const { return _internal_has_insertion_point(); } inline void CodeGeneratorResponse_File::clear_insertion_point() { - insertion_point_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000002u; + _impl_.insertion_point_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& CodeGeneratorResponse_File::insertion_point() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) @@ -1506,8 +1518,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CodeGeneratorResponse_File::set_insertion_point(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000002u; - insertion_point_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.insertion_point_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) } inline std::string* CodeGeneratorResponse_File::mutable_insertion_point() { @@ -1516,40 +1528,40 @@ return _s; } inline const std::string& CodeGeneratorResponse_File::_internal_insertion_point() const { - return insertion_point_.Get(); + return _impl_.insertion_point_.Get(); } inline void CodeGeneratorResponse_File::_internal_set_insertion_point(const std::string& value) { - _has_bits_[0] |= 0x00000002u; - insertion_point_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.insertion_point_.Set(value, GetArenaForAllocation()); } inline std::string* CodeGeneratorResponse_File::_internal_mutable_insertion_point() { - _has_bits_[0] |= 0x00000002u; - return insertion_point_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + return _impl_.insertion_point_.Mutable(GetArenaForAllocation()); } inline std::string* CodeGeneratorResponse_File::release_insertion_point() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) if (!_internal_has_insertion_point()) { return nullptr; } - _has_bits_[0] &= ~0x00000002u; - auto* p = insertion_point_.Release(); + _impl_._has_bits_[0] &= ~0x00000002u; + auto* p = _impl_.insertion_point_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (insertion_point_.IsDefault()) { - insertion_point_.Set("", GetArenaForAllocation()); + if (_impl_.insertion_point_.IsDefault()) { + _impl_.insertion_point_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CodeGeneratorResponse_File::set_allocated_insertion_point(std::string* insertion_point) { if (insertion_point != nullptr) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - insertion_point_.SetAllocated(insertion_point, GetArenaForAllocation()); + _impl_.insertion_point_.SetAllocated(insertion_point, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (insertion_point_.IsDefault()) { - insertion_point_.Set("", GetArenaForAllocation()); + if (_impl_.insertion_point_.IsDefault()) { + _impl_.insertion_point_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) @@ -1557,15 +1569,15 @@ // optional string content = 15; inline bool CodeGeneratorResponse_File::_internal_has_content() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool CodeGeneratorResponse_File::has_content() const { return _internal_has_content(); } inline void CodeGeneratorResponse_File::clear_content() { - content_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000004u; + _impl_.content_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000004u; } inline const std::string& CodeGeneratorResponse_File::content() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.File.content) @@ -1574,8 +1586,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CodeGeneratorResponse_File::set_content(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000004u; - content_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.content_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.File.content) } inline std::string* CodeGeneratorResponse_File::mutable_content() { @@ -1584,40 +1596,40 @@ return _s; } inline const std::string& CodeGeneratorResponse_File::_internal_content() const { - return content_.Get(); + return _impl_.content_.Get(); } inline void CodeGeneratorResponse_File::_internal_set_content(const std::string& value) { - _has_bits_[0] |= 0x00000004u; - content_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.content_.Set(value, GetArenaForAllocation()); } inline std::string* CodeGeneratorResponse_File::_internal_mutable_content() { - _has_bits_[0] |= 0x00000004u; - return content_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + return _impl_.content_.Mutable(GetArenaForAllocation()); } inline std::string* CodeGeneratorResponse_File::release_content() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.content) if (!_internal_has_content()) { return nullptr; } - _has_bits_[0] &= ~0x00000004u; - auto* p = content_.Release(); + _impl_._has_bits_[0] &= ~0x00000004u; + auto* p = _impl_.content_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (content_.IsDefault()) { - content_.Set("", GetArenaForAllocation()); + if (_impl_.content_.IsDefault()) { + _impl_.content_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CodeGeneratorResponse_File::set_allocated_content(std::string* content) { if (content != nullptr) { - _has_bits_[0] |= 0x00000004u; + _impl_._has_bits_[0] |= 0x00000004u; } else { - _has_bits_[0] &= ~0x00000004u; + _impl_._has_bits_[0] &= ~0x00000004u; } - content_.SetAllocated(content, GetArenaForAllocation()); + _impl_.content_.SetAllocated(content, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (content_.IsDefault()) { - content_.Set("", GetArenaForAllocation()); + if (_impl_.content_.IsDefault()) { + _impl_.content_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.content) @@ -1625,15 +1637,15 @@ // optional .google.protobuf.GeneratedCodeInfo generated_code_info = 16; inline bool CodeGeneratorResponse_File::_internal_has_generated_code_info() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; - PROTOBUF_ASSUME(!value || generated_code_info_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; + PROTOBUF_ASSUME(!value || _impl_.generated_code_info_ != nullptr); return value; } inline bool CodeGeneratorResponse_File::has_generated_code_info() const { return _internal_has_generated_code_info(); } inline const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo& CodeGeneratorResponse_File::_internal_generated_code_info() const { - const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* p = generated_code_info_; + const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* p = _impl_.generated_code_info_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo&>( ::PROTOBUF_NAMESPACE_ID::_GeneratedCodeInfo_default_instance_); } @@ -1644,20 +1656,20 @@ inline void CodeGeneratorResponse_File::unsafe_arena_set_allocated_generated_code_info( ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(generated_code_info_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.generated_code_info_); } - generated_code_info_ = generated_code_info; + _impl_.generated_code_info_ = generated_code_info; if (generated_code_info) { - _has_bits_[0] |= 0x00000008u; + _impl_._has_bits_[0] |= 0x00000008u; } else { - _has_bits_[0] &= ~0x00000008u; + _impl_._has_bits_[0] &= ~0x00000008u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) } inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* CodeGeneratorResponse_File::release_generated_code_info() { - _has_bits_[0] &= ~0x00000008u; - ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* temp = generated_code_info_; - generated_code_info_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000008u; + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* temp = _impl_.generated_code_info_; + _impl_.generated_code_info_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -1671,18 +1683,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* CodeGeneratorResponse_File::unsafe_arena_release_generated_code_info() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) - _has_bits_[0] &= ~0x00000008u; - ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* temp = generated_code_info_; - generated_code_info_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000008u; + ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* temp = _impl_.generated_code_info_; + _impl_.generated_code_info_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* CodeGeneratorResponse_File::_internal_mutable_generated_code_info() { - _has_bits_[0] |= 0x00000008u; - if (generated_code_info_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000008u; + if (_impl_.generated_code_info_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo>(GetArenaForAllocation()); - generated_code_info_ = p; + _impl_.generated_code_info_ = p; } - return generated_code_info_; + return _impl_.generated_code_info_; } inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* CodeGeneratorResponse_File::mutable_generated_code_info() { ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* _msg = _internal_mutable_generated_code_info(); @@ -1692,7 +1704,7 @@ inline void CodeGeneratorResponse_File::set_allocated_generated_code_info(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo* generated_code_info) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(generated_code_info_); + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.generated_code_info_); } if (generated_code_info) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -1702,11 +1714,11 @@ generated_code_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, generated_code_info, submessage_arena); } - _has_bits_[0] |= 0x00000008u; + _impl_._has_bits_[0] |= 0x00000008u; } else { - _has_bits_[0] &= ~0x00000008u; + _impl_._has_bits_[0] &= ~0x00000008u; } - generated_code_info_ = generated_code_info; + _impl_.generated_code_info_ = generated_code_info; // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) } @@ -1716,15 +1728,15 @@ // optional string error = 1; inline bool CodeGeneratorResponse::_internal_has_error() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool CodeGeneratorResponse::has_error() const { return _internal_has_error(); } inline void CodeGeneratorResponse::clear_error() { - error_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.error_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& CodeGeneratorResponse::error() const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.error) @@ -1733,8 +1745,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void CodeGeneratorResponse::set_error(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - error_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.error_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.compiler.CodeGeneratorResponse.error) } inline std::string* CodeGeneratorResponse::mutable_error() { @@ -1743,40 +1755,40 @@ return _s; } inline const std::string& CodeGeneratorResponse::_internal_error() const { - return error_.Get(); + return _impl_.error_.Get(); } inline void CodeGeneratorResponse::_internal_set_error(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - error_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.error_.Set(value, GetArenaForAllocation()); } inline std::string* CodeGeneratorResponse::_internal_mutable_error() { - _has_bits_[0] |= 0x00000001u; - return error_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.error_.Mutable(GetArenaForAllocation()); } inline std::string* CodeGeneratorResponse::release_error() { // @@protoc_insertion_point(field_release:google.protobuf.compiler.CodeGeneratorResponse.error) if (!_internal_has_error()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = error_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.error_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (error_.IsDefault()) { - error_.Set("", GetArenaForAllocation()); + if (_impl_.error_.IsDefault()) { + _impl_.error_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void CodeGeneratorResponse::set_allocated_error(std::string* error) { if (error != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - error_.SetAllocated(error, GetArenaForAllocation()); + _impl_.error_.SetAllocated(error, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (error_.IsDefault()) { - error_.Set("", GetArenaForAllocation()); + if (_impl_.error_.IsDefault()) { + _impl_.error_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.compiler.CodeGeneratorResponse.error) @@ -1784,26 +1796,26 @@ // optional uint64 supported_features = 2; inline bool CodeGeneratorResponse::_internal_has_supported_features() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._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_ = uint64_t{0u}; - _has_bits_[0] &= ~0x00000002u; + _impl_.supported_features_ = uint64_t{0u}; + _impl_._has_bits_[0] &= ~0x00000002u; } inline uint64_t CodeGeneratorResponse::_internal_supported_features() const { - return supported_features_; + return _impl_.supported_features_; } inline uint64_t 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(uint64_t value) { - _has_bits_[0] |= 0x00000002u; - supported_features_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.supported_features_ = value; } inline void CodeGeneratorResponse::set_supported_features(uint64_t value) { _internal_set_supported_features(value); @@ -1812,32 +1824,32 @@ // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; inline int CodeGeneratorResponse::_internal_file_size() const { - return file_.size(); + return _impl_.file_.size(); } inline int CodeGeneratorResponse::file_size() const { return _internal_file_size(); } inline void CodeGeneratorResponse::clear_file() { - file_.Clear(); + _impl_.file_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::mutable_file(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.compiler.CodeGeneratorResponse.file) - return file_.Mutable(index); + return _impl_.file_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >* CodeGeneratorResponse::mutable_file() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.compiler.CodeGeneratorResponse.file) - return &file_; + return &_impl_.file_; } inline const ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::_internal_file(int index) const { - return file_.Get(index); + return _impl_.file_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File& CodeGeneratorResponse::file(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.compiler.CodeGeneratorResponse.file) return _internal_file(index); } inline ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::_internal_add_file() { - return file_.Add(); + return _impl_.file_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* CodeGeneratorResponse::add_file() { ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File* _add = _internal_add_file(); @@ -1847,7 +1859,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::compiler::CodeGeneratorResponse_File >& CodeGeneratorResponse::file() const { // @@protoc_insertion_point(field_list:google.protobuf.compiler.CodeGeneratorResponse.file) - return file_; + return _impl_.file_; } #ifdef __GNUC__
diff --git a/src/google/protobuf/compiler/python/python_generator.cc b/src/google/protobuf/compiler/python/generator.cc similarity index 99% rename from src/google/protobuf/compiler/python/python_generator.cc rename to src/google/protobuf/compiler/python/generator.cc index 8f70925..d8d6d74 100644 --- a/src/google/protobuf/compiler/python/python_generator.cc +++ b/src/google/protobuf/compiler/python/generator.cc
@@ -42,7 +42,7 @@ // performance-minded Python code leverage the fast C++ implementation // directly. -#include <google/protobuf/compiler/python/python_generator.h> +#include <google/protobuf/compiler/python/generator.h> #include <algorithm> #include <limits> @@ -54,15 +54,15 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/compiler/python/python_helpers.h> -#include <google/protobuf/compiler/python/python_pyi_generator.h> -#include <google/protobuf/io/printer.h> -#include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/stringprintf.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/compiler/python/helpers.h> +#include <google/protobuf/compiler/python/pyi_generator.h> +#include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> +#include <google/protobuf/io/printer.h> +#include <google/protobuf/io/zero_copy_stream.h> namespace google { namespace protobuf { @@ -91,11 +91,6 @@ const char kDescriptorKey[] = "DESCRIPTOR"; -// Does the file have top-level enums? -inline bool HasTopLevelEnums(const FileDescriptor* file) { - return file->enum_type_count() > 0; -} - // file output by this generator. void PrintTopBoilerplate(io::Printer* printer, const FileDescriptor* file, bool descriptor_proto) {
diff --git a/src/google/protobuf/compiler/python/python_generator.h b/src/google/protobuf/compiler/python/generator.h similarity index 99% rename from src/google/protobuf/compiler/python/python_generator.h rename to src/google/protobuf/compiler/python/generator.h index a77cf33..f1fecbc 100644 --- a/src/google/protobuf/compiler/python/python_generator.h +++ b/src/google/protobuf/compiler/python/generator.h
@@ -37,8 +37,8 @@ #include <string> -#include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/stubs/mutex.h> +#include <google/protobuf/compiler/code_generator.h> // Must be included last. #include <google/protobuf/port_def.inc>
diff --git a/src/google/protobuf/compiler/python/python_helpers.cc b/src/google/protobuf/compiler/python/helpers.cc similarity index 97% rename from src/google/protobuf/compiler/python/python_helpers.cc rename to src/google/protobuf/compiler/python/helpers.cc index eae236f..e4d3c13 100644 --- a/src/google/protobuf/compiler/python/python_helpers.cc +++ b/src/google/protobuf/compiler/python/helpers.cc
@@ -28,13 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/python/python_helpers.h> +#include <google/protobuf/compiler/python/helpers.h> #include <algorithm> +#include <google/protobuf/stubs/strutil.h> #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/descriptor.h> -#include <google/protobuf/stubs/strutil.h> #include <google/protobuf/descriptor.pb.h> namespace google { @@ -62,7 +62,7 @@ "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", - "return", "try", "while", "with", "yield", "print", + "return", "try", "while", "with", "yield", }; const char* const* kKeywordsEnd = kKeywords + (sizeof(kKeywords) / sizeof(kKeywords[0]));
diff --git a/src/google/protobuf/compiler/python/python_helpers.h b/src/google/protobuf/compiler/python/helpers.h similarity index 100% rename from src/google/protobuf/compiler/python/python_helpers.h rename to src/google/protobuf/compiler/python/helpers.h
diff --git a/src/google/protobuf/compiler/python/python_plugin_unittest.cc b/src/google/protobuf/compiler/python/plugin_unittest.cc similarity index 95% rename from src/google/protobuf/compiler/python/python_plugin_unittest.cc rename to src/google/protobuf/compiler/python/plugin_unittest.cc index bc92b23..7f9589b 100644 --- a/src/google/protobuf/compiler/python/python_plugin_unittest.cc +++ b/src/google/protobuf/compiler/python/plugin_unittest.cc
@@ -29,17 +29,14 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) -// -// TODO(kenton): Share code with the versions of this test in other languages? -// It seemed like parameterizing it would add more complexity than it is -// worth. #include <memory> +#include <string> #include <google/protobuf/testing/file.h> #include <google/protobuf/testing/file.h> #include <google/protobuf/compiler/command_line_interface.h> -#include <google/protobuf/compiler/python/python_generator.h> +#include <google/protobuf/compiler/python/generator.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/stubs/strutil.h>
diff --git a/src/google/protobuf/compiler/python/python_pyi_generator.cc b/src/google/protobuf/compiler/python/pyi_generator.cc similarity index 72% rename from src/google/protobuf/compiler/python/python_pyi_generator.cc rename to src/google/protobuf/compiler/python/pyi_generator.cc index d78d766..1ccc9a2 100644 --- a/src/google/protobuf/compiler/python/python_pyi_generator.cc +++ b/src/google/protobuf/compiler/python/pyi_generator.cc
@@ -28,16 +28,16 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/compiler/python/python_pyi_generator.h> +#include <google/protobuf/compiler/python/pyi_generator.h> #include <string> -#include <google/protobuf/compiler/python/python_helpers.h> +#include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/compiler/python/helpers.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/descriptor.pb.h> namespace google { namespace protobuf { @@ -64,12 +64,21 @@ } template <typename DescriptorT> -std::string PyiGenerator::ModuleLevelName(const DescriptorT& descriptor) const { +std::string PyiGenerator::ModuleLevelName( + const DescriptorT& descriptor, + const std::map<std::string, std::string>& import_map) const { std::string name = NamePrefixedWithNestedTypes(descriptor, "."); if (descriptor.file() != file_) { - std::string module_name = ModuleName(descriptor.file()->name()); - std::vector<std::string> tokens = Split(module_name, "."); - name = "_" + tokens.back() + "." + name; + std::string module_alias; + std::string filename = descriptor.file()->name(); + if (import_map.find(filename) == import_map.end()) { + std::string module_name = ModuleName(descriptor.file()->name()); + std::vector<std::string> tokens = Split(module_name, "."); + module_alias = "_" + tokens.back(); + } else { + module_alias = import_map.at(filename); + } + name = module_alias + "." + name; } return name; } @@ -82,9 +91,22 @@ bool has_extendable = false; // _python_message bool has_mapping = false; // typing.Mapping bool has_optional = false; // typing.Optional - bool has_union = false; // typing.Uion + bool has_union = false; // typing.Union + bool has_well_known_type = false; }; +// Checks whether a descriptor name matches a well-known type. +bool IsWellKnownType(const std::string& name) { + // LINT.IfChange(wktbases) + return (name == "google.protobuf.Any" || + name == "google.protobuf.Duration" || + name == "google.protobuf.FieldMask" || + name == "google.protobuf.ListValue" || + name == "google.protobuf.Struct" || + name == "google.protobuf.Timestamp"); + // LINT.ThenChange(//depot/google3/net/proto2/python/internal/well_known_types.py:wktbases) +} + // Checks what modules should be imported for this message // descriptor. void CheckImportModules(const Descriptor* descriptor, @@ -95,6 +117,9 @@ if (descriptor->enum_type_count() > 0) { import_modules->has_enums = true; } + if (IsWellKnownType(descriptor->full_name())) { + import_modules->has_well_known_type = true; + } for (int i = 0; i < descriptor->field_count(); ++i) { const FieldDescriptor* field = descriptor->field(i); if (IsPythonKeyword(field->name())) { @@ -129,23 +154,44 @@ } } +void PyiGenerator::PrintImportForDescriptor( + const FileDescriptor& desc, + std::map<std::string, std::string>* import_map, + std::set<std::string>* seen_aliases) const { + const std::string& filename = desc.name(); + std::string module_name = StrippedModuleName(filename); + size_t last_dot_pos = module_name.rfind('.'); + std::string import_statement; + if (last_dot_pos == std::string::npos) { + import_statement = "import " + module_name; + } else { + import_statement = "from " + module_name.substr(0, last_dot_pos) + + " import " + module_name.substr(last_dot_pos + 1); + module_name = module_name.substr(last_dot_pos + 1); + } + std::string alias = "_" + module_name; + // Generate a unique alias by adding _1 suffixes until we get an unused alias. + while (seen_aliases->find(alias) != seen_aliases->end()) { + alias = alias + "_1"; + } + printer_->Print("$statement$ as $alias$\n", "statement", + import_statement, "alias", alias); + (*import_map)[filename] = alias; + seen_aliases->insert(alias); +} + void PyiGenerator::PrintImports( - std::map<std::string, std::string>* item_map) const { + std::map<std::string, std::string>* item_map, + std::map<std::string, std::string>* import_map) const { // Prints imported dependent _pb2 files. + std::set<std::string> seen_aliases; for (int i = 0; i < file_->dependency_count(); ++i) { - const std::string& filename = file_->dependency(i)->name(); - std::string module_name = StrippedModuleName(filename); - size_t last_dot_pos = module_name.rfind('.'); - std::string import_statement; - if (last_dot_pos == std::string::npos) { - import_statement = "import " + module_name; - } else { - import_statement = "from " + module_name.substr(0, last_dot_pos) + - " import " + module_name.substr(last_dot_pos + 1); - module_name = module_name.substr(last_dot_pos + 1); + const FileDescriptor* dep = file_->dependency(i); + PrintImportForDescriptor(*dep, import_map, &seen_aliases); + for (int j = 0; j < dep->public_dependency_count(); ++j) { + PrintImportForDescriptor( + *dep->public_dependency(j), import_map, &seen_aliases); } - printer_->Print("$statement$ as _$module_name$\n", "statement", - import_statement, "module_name", module_name); } // Checks what modules should be imported. @@ -177,6 +223,11 @@ "from google.protobuf.internal import python_message" " as _python_message\n"); } + if (import_modules.has_well_known_type) { + printer_->Print( + "from google.protobuf.internal import well_known_types" + " as _well_known_types\n"); + } printer_->Print( "from google.protobuf import" " descriptor as _descriptor\n"); @@ -190,21 +241,18 @@ " _service\n"); } printer_->Print("from typing import "); - printer_->Print("ClassVar"); + printer_->Print("ClassVar as _ClassVar"); if (import_modules.has_iterable) { - printer_->Print(", Iterable"); + printer_->Print(", Iterable as _Iterable"); } if (import_modules.has_mapping) { - printer_->Print(", Mapping"); + printer_->Print(", Mapping as _Mapping"); } if (import_modules.has_optional) { - printer_->Print(", Optional"); - } - if (file_->service_count() > 0) { - printer_->Print(", Text"); + printer_->Print(", Optional as _Optional"); } if (import_modules.has_union) { - printer_->Print(", Union"); + printer_->Print(", Union as _Union"); } printer_->Print("\n\n"); @@ -229,7 +277,7 @@ const EnumDescriptor* enum_descriptor = public_dep->enum_type(i); for (int j = 0; j < enum_descriptor->value_count(); ++j) { (*item_map)[enum_descriptor->value(j)->name()] = - ModuleLevelName(*enum_descriptor); + ModuleLevelName(*enum_descriptor, *import_map); } } // Top level extensions for public imports @@ -248,9 +296,10 @@ // Adds enum value to item map which will be ordered and printed later. void PyiGenerator::AddEnumValue( const EnumDescriptor& enum_descriptor, - std::map<std::string, std::string>* item_map) const { + std::map<std::string, std::string>* item_map, + const std::map<std::string, std::string>& import_map) const { // enum values - std::string module_enum_name = ModuleLevelName(enum_descriptor); + std::string module_enum_name = ModuleLevelName(enum_descriptor, import_map); for (int j = 0; j < enum_descriptor.value_count(); ++j) { const EnumValueDescriptor* value_descriptor = enum_descriptor.value(j); (*item_map)[value_descriptor->name()] = module_enum_name; @@ -275,13 +324,15 @@ const FieldDescriptor* extension_field = descriptor.extension(i); std::string constant_name = extension_field->name() + "_FIELD_NUMBER"; ToUpper(&constant_name); - (*item_map)[constant_name] = "ClassVar[int]"; + (*item_map)[constant_name] = "_ClassVar[int]"; (*item_map)[extension_field->name()] = "_descriptor.FieldDescriptor"; } } // Returns the string format of a field's cpp_type -std::string PyiGenerator::GetFieldType(const FieldDescriptor& field_des) const { +std::string PyiGenerator::GetFieldType( + const FieldDescriptor& field_des, const Descriptor& containing_des, + const std::map<std::string, std::string>& import_map) const { switch (field_des.cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: case FieldDescriptor::CPPTYPE_UINT32: @@ -294,29 +345,48 @@ case FieldDescriptor::CPPTYPE_BOOL: return "bool"; case FieldDescriptor::CPPTYPE_ENUM: - return ModuleLevelName(*field_des.enum_type()); + return ModuleLevelName(*field_des.enum_type(), import_map); case FieldDescriptor::CPPTYPE_STRING: if (field_des.type() == FieldDescriptor::TYPE_STRING) { return "str"; } else { return "bytes"; } - case FieldDescriptor::CPPTYPE_MESSAGE: - return ModuleLevelName(*field_des.message_type()); + case FieldDescriptor::CPPTYPE_MESSAGE: { + // If the field is inside a nested message and the nested message has the + // same name as a top-level message, then we need to prefix the field type + // with the module name for disambiguation. + std::string name = ModuleLevelName(*field_des.message_type(), import_map); + if ((containing_des.containing_type() != nullptr && + name == containing_des.name())) { + std::string module = ModuleName(field_des.file()->name()); + name = module + "." + name; + } + return name; + } default: - GOOGLE_LOG(FATAL) << "Unsuppoted field type."; + GOOGLE_LOG(FATAL) << "Unsupported field type."; } return ""; } -void PyiGenerator::PrintMessage(const Descriptor& message_descriptor, - bool is_nested) const { +void PyiGenerator::PrintMessage( + const Descriptor& message_descriptor, bool is_nested, + const std::map<std::string, std::string>& import_map) const { if (!is_nested) { printer_->Print("\n"); } std::string class_name = message_descriptor.name(); - printer_->Print("class $class_name$(_message.Message):\n", "class_name", - class_name); + std::string extra_base; + // A well-known type needs to inherit from its corresponding base class in + // net/proto2/python/internal/well_known_types. + if (IsWellKnownType(message_descriptor.full_name())) { + extra_base = ", _well_known_types." + message_descriptor.name(); + } else { + extra_base = ""; + } + printer_->Print("class $class_name$(_message.Message$extra_base$):\n", + "class_name", class_name, "extra_base", extra_base); printer_->Indent(); printer_->Indent(); @@ -361,7 +431,7 @@ for (const auto& entry : nested_enums) { PrintEnum(*entry); // Adds enum value to item_map which will be ordered and printed later - AddEnumValue(*entry, &item_map); + AddEnumValue(*entry, &item_map, import_map); } // Prints nested messages @@ -374,7 +444,7 @@ SortByName<Descriptor>()); for (const auto& entry : nested_messages) { - PrintMessage(*entry, true); + PrintMessage(*entry, true, import_map); } // Adds extensions to item_map which will be ordered and printed later @@ -384,7 +454,7 @@ for (int i = 0; i < message_descriptor.field_count(); ++i) { const FieldDescriptor& field_des = *message_descriptor.field(i); item_map[ToUpper(field_des.name()) + "_FIELD_NUMBER"] = - "ClassVar[int]"; + "_ClassVar[int]"; if (IsPythonKeyword(field_des.name())) { continue; } @@ -395,16 +465,16 @@ field_type = (value_des->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? "_containers.MessageMap[" : "_containers.ScalarMap["); - field_type += GetFieldType(*key_des); + field_type += GetFieldType(*key_des, message_descriptor, import_map); field_type += ", "; - field_type += GetFieldType(*value_des); + field_type += GetFieldType(*value_des, message_descriptor, import_map); } else { if (field_des.is_repeated()) { field_type = (field_des.cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE ? "_containers.RepeatedCompositeFieldContainer[" : "_containers.RepeatedScalarFieldContainer["); } - field_type += GetFieldType(field_des); + field_type += GetFieldType(field_des, message_descriptor, import_map); } if (field_des.is_repeated()) { @@ -437,26 +507,31 @@ printer_->Print(", $field_name$: ", "field_name", field_name); if (field_des->is_repeated() || field_des->cpp_type() != FieldDescriptor::CPPTYPE_BOOL) { - printer_->Print("Optional["); + printer_->Print("_Optional["); } if (field_des->is_map()) { const Descriptor* map_entry = field_des->message_type(); - printer_->Print("Mapping[$key_type$, $value_type$]", "key_type", - GetFieldType(*map_entry->field(0)), "value_type", - GetFieldType(*map_entry->field(1))); + printer_->Print( + "_Mapping[$key_type$, $value_type$]", "key_type", + GetFieldType(*map_entry->field(0), message_descriptor, import_map), + "value_type", + GetFieldType(*map_entry->field(1), message_descriptor, import_map)); } else { if (field_des->is_repeated()) { - printer_->Print("Iterable["); + printer_->Print("_Iterable["); } if (field_des->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - printer_->Print("Union[$type_name$, Mapping]", "type_name", - GetFieldType(*field_des)); + printer_->Print( + "_Union[$type_name$, _Mapping]", "type_name", + GetFieldType(*field_des, message_descriptor, import_map)); } else { if (field_des->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - printer_->Print("Union[$type_name$, str]", "type_name", - ModuleLevelName(*field_des->enum_type())); + printer_->Print("_Union[$type_name$, str]", "type_name", + ModuleLevelName(*field_des->enum_type(), import_map)); } else { - printer_->Print("$type_name$", "type_name", GetFieldType(*field_des)); + printer_->Print( + "$type_name$", "type_name", + GetFieldType(*field_des, message_descriptor, import_map)); } } if (field_des->is_repeated()) { @@ -478,8 +553,9 @@ printer_->Outdent(); } -void PyiGenerator::PrintMessages() const { - // Order the descriptors by name to have same output with proto_to_pyi.py +void PyiGenerator::PrintMessages( + const std::map<std::string, std::string>& import_map) const { + // Deterministically order the descriptors. std::vector<const Descriptor*> messages; messages.reserve(file_->message_type_count()); for (int i = 0; i < file_->message_type_count(); ++i) { @@ -488,7 +564,7 @@ std::sort(messages.begin(), messages.end(), SortByName<Descriptor>()); for (const auto& entry : messages) { - PrintMessage(*entry, false); + PrintMessage(*entry, false, import_map); } } @@ -517,9 +593,6 @@ MutexLock lock(&mutex_); // Calculate file name. file_ = file; - // proto_to_pyi.py may set the output file name directly. To replace - // proto_to_pyi.py in google3, protoc also accept --pyi_out to set - // the output file name. std::string filename = parameter.empty() ? GetFileName(file, ".pyi") : parameter; @@ -534,17 +607,22 @@ // Adds "DESCRIPTOR" into item_map. item_map["DESCRIPTOR"] = "_descriptor.FileDescriptor"; - PrintImports(&item_map); + + // import_map will be a mapping from filename to module alias, e.g. + // "google3/foo/bar.py" -> "_bar" + std::map<std::string, std::string> import_map; + + PrintImports(&item_map, &import_map); // Adds top level enum values to item_map. for (int i = 0; i < file_->enum_type_count(); ++i) { - AddEnumValue(*file_->enum_type(i), &item_map); + AddEnumValue(*file_->enum_type(i), &item_map, import_map); } // Adds top level extensions to item_map. AddExtensions(*file_, &item_map); // Prints item map PrintItemMap(item_map); - PrintMessages(); + PrintMessages(import_map); PrintTopLevelEnums(); if (HasGenericServices(file)) { PrintServices();
diff --git a/src/google/protobuf/compiler/python/python_pyi_generator.h b/src/google/protobuf/compiler/python/pyi_generator.h similarity index 78% rename from src/google/protobuf/compiler/python/python_pyi_generator.h rename to src/google/protobuf/compiler/python/pyi_generator.h index 5d382be..9611ed4 100644 --- a/src/google/protobuf/compiler/python/python_pyi_generator.h +++ b/src/google/protobuf/compiler/python/pyi_generator.h
@@ -36,10 +36,11 @@ #define GOOGLE_PROTOBUF_COMPILER_PYTHON_PYI_GENERATOR_H__ #include <map> +#include <set> #include <string> -#include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/stubs/mutex.h> +#include <google/protobuf/compiler/code_generator.h> // Must be included last. #include <google/protobuf/port_def.inc> @@ -65,26 +66,41 @@ ~PyiGenerator() override; // CodeGenerator methods. + uint64_t GetSupportedFeatures() const override { + // Code generators must explicitly support proto3 optional. + return CodeGenerator::FEATURE_PROTO3_OPTIONAL; + } bool Generate(const FileDescriptor* file, const std::string& parameter, GeneratorContext* generator_context, std::string* error) const override; private: - void PrintImports(std::map<std::string, std::string>* item_map) const; + void PrintImportForDescriptor(const FileDescriptor& desc, + std::map<std::string, std::string>* import_map, + std::set<std::string>* seen_aliases) const; + void PrintImports(std::map<std::string, std::string>* item_map, + std::map<std::string, std::string>* import_map) const; void PrintEnum(const EnumDescriptor& enum_descriptor) const; void AddEnumValue(const EnumDescriptor& enum_descriptor, - std::map<std::string, std::string>* item_map) const; + std::map<std::string, std::string>* item_map, + const std::map<std::string, std::string>& import_map) const; void PrintTopLevelEnums() const; template <typename DescriptorT> void AddExtensions(const DescriptorT& descriptor, std::map<std::string, std::string>* item_map) const; - void PrintMessages() const; - void PrintMessage(const Descriptor& message_descriptor, bool is_nested) const; + void PrintMessages( + const std::map<std::string, std::string>& import_map) const; + void PrintMessage(const Descriptor& message_descriptor, bool is_nested, + const std::map<std::string, std::string>& import_map) const; void PrintServices() const; void PrintItemMap(const std::map<std::string, std::string>& item_map) const; - std::string GetFieldType(const FieldDescriptor& field_des) const; + std::string GetFieldType( + const FieldDescriptor& field_des, const Descriptor& containing_des, + const std::map<std::string, std::string>& import_map) const; template <typename DescriptorT> - std::string ModuleLevelName(const DescriptorT& descriptor) const; + std::string ModuleLevelName( + const DescriptorT& descriptor, + const std::map<std::string, std::string>& import_map) const; // Very coarse-grained lock to ensure that Generate() is reentrant. // Guards file_ and printer_.
diff --git a/src/google/protobuf/compiler/subprocess.cc b/src/google/protobuf/compiler/subprocess.cc index 46d98a1..c591173 100644 --- a/src/google/protobuf/compiler/subprocess.cc +++ b/src/google/protobuf/compiler/subprocess.cc
@@ -45,8 +45,8 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/message.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/message.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/compiler/test_plugin.cc b/src/google/protobuf/compiler/test_plugin.cc index 6b56170..2556078 100644 --- a/src/google/protobuf/compiler/test_plugin.cc +++ b/src/google/protobuf/compiler/test_plugin.cc
@@ -34,7 +34,9 @@ // command_line_interface_unittest. #include <stdlib.h> + #include <string> + #include <google/protobuf/compiler/mock_code_generator.h> #include <google/protobuf/compiler/plugin.h>
diff --git a/src/google/protobuf/compiler/zip_writer.h b/src/google/protobuf/compiler/zip_writer.h index 0a8a773..5d7f69a 100644 --- a/src/google/protobuf/compiler/zip_writer.h +++ b/src/google/protobuf/compiler/zip_writer.h
@@ -29,6 +29,8 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) +#ifndef GOOGLE_PROTOBUF_COMPILER_ZIP_WRITER_H__ +#define GOOGLE_PROTOBUF_COMPILER_ZIP_WRITER_H__ #include <cstdint> #include <vector> @@ -63,3 +65,5 @@ } // namespace compiler } // namespace protobuf } // namespace google + +#endif // GOOGLE_PROTOBUF_COMPILER_ZIP_WRITER_H__
diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 0524fd4..123b22a 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc
@@ -41,6 +41,7 @@ #include <map> #include <memory> #include <set> +#include <sstream> #include <string> #include <type_traits> #include <unordered_map> @@ -1101,8 +1102,9 @@ std::set<std::string>* NewAllowedProto3Extendee() { auto allowed_proto3_extendees = new std::set<std::string>; const char* kOptionNames[] = { - "FileOptions", "MessageOptions", "FieldOptions", "EnumOptions", - "EnumValueOptions", "ServiceOptions", "MethodOptions", "OneofOptions"}; + "FileOptions", "MessageOptions", "FieldOptions", + "EnumOptions", "EnumValueOptions", "ServiceOptions", + "MethodOptions", "OneofOptions", "ExtensionRangeOptions"}; for (const char* option_name : kOptionNames) { // descriptor.proto has a different package name in opensource. We allow // both so the opensource protocol compiler can also compile internal @@ -3698,6 +3700,28 @@ FileDescriptorTables* file_tables_; std::set<const FileDescriptor*> dependencies_; + struct MessageHints { + int fields_to_suggest = 0; + const Message* first_reason = nullptr; + DescriptorPool::ErrorCollector::ErrorLocation first_reason_location = + DescriptorPool::ErrorCollector::ErrorLocation::OTHER; + + void RequestHintOnFieldNumbers( + const Message& reason, + DescriptorPool::ErrorCollector::ErrorLocation reason_location, + int fields_count = 1) { + constexpr int kMaxSuggestions = 3; + fields_to_suggest = + std::min(kMaxSuggestions, + fields_to_suggest + std::min(kMaxSuggestions, fields_count)); + if (first_reason) return; + first_reason = &reason; + first_reason_location = reason_location; + } + }; + + std::unordered_map<const Descriptor*, MessageHints> message_hints_; + // unused_dependency_ is used to record the unused imported files. // Note: public import is not considered. std::set<const FileDescriptor*> unused_dependency_; @@ -3772,9 +3796,9 @@ // Like FindSymbol(), but looks up the name relative to some other symbol // name. This first searches siblings of relative_to, then siblings of its - // parents, etc. For example, LookupSymbol("foo.bar", "baz.qux.corge") makes + // parents, etc. For example, LookupSymbol("foo.bar", "baz.moo.corge") makes // the following calls, returning the first non-null result: - // FindSymbol("baz.qux.foo.bar"), FindSymbol("baz.foo.bar"), + // FindSymbol("baz.moo.foo.bar"), FindSymbol("baz.foo.bar"), // FindSymbol("foo.bar"). If AllowUnknownDependencies() has been called // on the DescriptorPool, this will generate a placeholder type if // the name is not found (unless the name itself is malformed). The @@ -3911,6 +3935,8 @@ const ServiceDescriptorProto& proto); void CrossLinkMethod(MethodDescriptor* method, const MethodDescriptorProto& proto); + void SuggestFieldNumbers(FileDescriptor* file, + const FileDescriptorProto& proto); // Must be run only after cross-linking. void InterpretOptions(); @@ -5005,6 +5031,13 @@ } } + static const int kMaximumPackageLength = 511; + if (proto.package().size() > kMaximumPackageLength) { + AddError(proto.package(), proto, DescriptorPool::ErrorCollector::NAME, + "Package name is too long"); + return nullptr; + } + // If we have a fallback_database_, and we aren't doing lazy import building, // attempt to load all dependencies now, before checkpointing tables_. This // avoids confusion with recursive checkpoints. @@ -5266,6 +5299,10 @@ // Cross-link. CrossLinkFile(result, proto); + if (!message_hints_.empty()) { + SuggestFieldNumbers(result, proto); + } + // Interpret any remaining uninterpreted options gathered into // options_to_interpret_ during descriptor building. Cross-linking has made // extension options known, so all interpretations should now succeed. @@ -5440,6 +5477,8 @@ for (int j = 0; j < result->extension_range_count(); j++) { const Descriptor::ExtensionRange* range = result->extension_range(j); if (range->start <= field->number() && field->number() < range->end) { + message_hints_[result].RequestHintOnFieldNumbers( + proto.extension_range(j), DescriptorPool::ErrorCollector::NUMBER); AddError( field->full_name(), proto.extension_range(j), DescriptorPool::ErrorCollector::NUMBER, @@ -5451,6 +5490,8 @@ for (int j = 0; j < result->reserved_range_count(); j++) { const Descriptor::ReservedRange* range = result->reserved_range(j); if (range->start <= field->number() && field->number() < range->end) { + message_hints_[result].RequestHintOnFieldNumbers( + proto.reserved_range(j), DescriptorPool::ErrorCollector::NUMBER); AddError(field->full_name(), proto.reserved_range(j), DescriptorPool::ErrorCollector::NUMBER, strings::Substitute("Field \"$0\" uses reserved number $1.", @@ -5697,6 +5738,8 @@ } if (result->number() <= 0) { + message_hints_[parent].RequestHintOnFieldNumbers( + proto, DescriptorPool::ErrorCollector::NUMBER); AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, "Field numbers must be positive integers."); } else if (!is_extension && result->number() > FieldDescriptor::kMaxNumber) { @@ -5708,11 +5751,15 @@ // This avoids cross-linking issues that arise when attempting to check if // the extendee is a message_set_wire_format message, which has a higher max // on extension numbers. + message_hints_[parent].RequestHintOnFieldNumbers( + proto, DescriptorPool::ErrorCollector::NUMBER); AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, strings::Substitute("Field numbers cannot be greater than $0.", FieldDescriptor::kMaxNumber)); } else if (result->number() >= FieldDescriptor::kFirstReservedNumber && result->number() <= FieldDescriptor::kLastReservedNumber) { + message_hints_[parent].RequestHintOnFieldNumbers( + proto, DescriptorPool::ErrorCollector::NUMBER); AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, strings::Substitute( "Field numbers $0 through $1 are reserved for the protocol " @@ -5777,6 +5824,9 @@ result->start = proto.start(); result->end = proto.end(); if (result->start <= 0) { + message_hints_[parent].RequestHintOnFieldNumbers( + proto, DescriptorPool::ErrorCollector::NUMBER, + std::max(0, result->end - result->start)); AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, "Extension numbers must be positive integers."); } @@ -5814,6 +5864,9 @@ result->start = proto.start(); result->end = proto.end(); if (result->start <= 0) { + message_hints_[parent].RequestHintOnFieldNumbers( + proto, DescriptorPool::ErrorCollector::NUMBER, + std::max(0, result->end - result->start)); AddError(parent->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, "Reserved numbers must be positive integers."); } @@ -6648,6 +6701,78 @@ method->output_type_.Set(output_type.descriptor()); } } + +void DescriptorBuilder::SuggestFieldNumbers(FileDescriptor* file, + const FileDescriptorProto& proto) { + for (int message_index = 0; message_index < file->message_type_count(); + message_index++) { + const Descriptor* message = &file->message_types_[message_index]; + auto* hints = FindOrNull(message_hints_, message); + if (!hints) continue; + int fields_to_suggest = hints->fields_to_suggest; + if (fields_to_suggest <= 0) continue; + struct Range { + int from; + int to; + }; + std::vector<Range> used_ordinals; + auto add_ordinal = [&](int ordinal) { + if (!used_ordinals.empty() && + used_ordinals.back().to < FieldDescriptor::kMaxNumber && + ordinal == used_ordinals.back().to + 1) { + used_ordinals.back().to = ordinal; + } else { + used_ordinals.push_back({ordinal, ordinal}); + } + }; + auto add_range = [&](int from, int to) { + from = std::max(0, std::min(FieldDescriptor::kMaxNumber, from)); + to = std::max(0, std::min(FieldDescriptor::kMaxNumber, to)); + if (from > to) return; + used_ordinals.push_back({from, to}); + }; + for (int i = 0; i < message->field_count(); i++) { + add_ordinal(message->field(i)->number()); + } + for (int i = 0; i < message->extension_count(); i++) { + add_ordinal(message->extension(i)->number()); + } + for (int i = 0; i < message->reserved_range_count(); i++) { + auto range = message->reserved_range(i); + add_range(range->start, range->end - 1); + } + for (int i = 0; i < message->extension_range_count(); i++) { + auto range = message->extension_range(i); + add_range(range->start, range->end - 1); + } + used_ordinals.push_back( + {FieldDescriptor::kMaxNumber, std::numeric_limits<int>::max()}); + used_ordinals.push_back({FieldDescriptor::kFirstReservedNumber, + FieldDescriptor::kLastReservedNumber}); + std::sort(used_ordinals.begin(), used_ordinals.end(), + [](Range lhs, Range rhs) { + return std::tie(lhs.from, lhs.to) < std::tie(rhs.from, rhs.to); + }); + int current_ordinal = 1; + std::stringstream id_list; + id_list << "Suggested field numbers for " << message->full_name() << ": "; + const char* separator = ""; + for (auto& current_range : used_ordinals) { + while (current_ordinal < current_range.from && fields_to_suggest > 0) { + id_list << separator << current_ordinal++; + separator = ", "; + fields_to_suggest--; + } + if (fields_to_suggest == 0) break; + current_ordinal = std::max(current_ordinal, current_range.to + 1); + } + if (hints->first_reason) { + AddError(message->full_name(), *hints->first_reason, + hints->first_reason_location, id_list.str()); + } + } +} + // ------------------------------------------------------------------- #define VALIDATE_OPTIONS_FROM_ARRAY(descriptor, array_name, type) \
diff --git a/src/google/protobuf/descriptor.pb.cc b/src/google/protobuf/descriptor.pb.cc index 5f78034..535a439 100644 --- a/src/google/protobuf/descriptor.pb.cc +++ b/src/google/protobuf/descriptor.pb.cc
@@ -22,8 +22,9 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR FileDescriptorSet::FileDescriptorSet( - ::_pbi::ConstantInitialized) - : file_(){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.file_)*/{} + , /*decltype(_impl_._cached_size_)*/{}} {} struct FileDescriptorSetDefaultTypeInternal { PROTOBUF_CONSTEXPR FileDescriptorSetDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -34,19 +35,21 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FileDescriptorSetDefaultTypeInternal _FileDescriptorSet_default_instance_; PROTOBUF_CONSTEXPR FileDescriptorProto::FileDescriptorProto( - ::_pbi::ConstantInitialized) - : dependency_() - , message_type_() - , enum_type_() - , service_() - , extension_() - , public_dependency_() - , weak_dependency_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , package_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , syntax_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , options_(nullptr) - , source_code_info_(nullptr){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.dependency_)*/{} + , /*decltype(_impl_.message_type_)*/{} + , /*decltype(_impl_.enum_type_)*/{} + , /*decltype(_impl_.service_)*/{} + , /*decltype(_impl_.extension_)*/{} + , /*decltype(_impl_.public_dependency_)*/{} + , /*decltype(_impl_.weak_dependency_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.package_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.syntax_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.options_)*/nullptr + , /*decltype(_impl_.source_code_info_)*/nullptr} {} struct FileDescriptorProtoDefaultTypeInternal { PROTOBUF_CONSTEXPR FileDescriptorProtoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -57,10 +60,12 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FileDescriptorProtoDefaultTypeInternal _FileDescriptorProto_default_instance_; PROTOBUF_CONSTEXPR DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange( - ::_pbi::ConstantInitialized) - : options_(nullptr) - , start_(0) - , end_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.options_)*/nullptr + , /*decltype(_impl_.start_)*/0 + , /*decltype(_impl_.end_)*/0} {} struct DescriptorProto_ExtensionRangeDefaultTypeInternal { PROTOBUF_CONSTEXPR DescriptorProto_ExtensionRangeDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -71,9 +76,11 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 DescriptorProto_ExtensionRangeDefaultTypeInternal _DescriptorProto_ExtensionRange_default_instance_; PROTOBUF_CONSTEXPR DescriptorProto_ReservedRange::DescriptorProto_ReservedRange( - ::_pbi::ConstantInitialized) - : start_(0) - , end_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.start_)*/0 + , /*decltype(_impl_.end_)*/0} {} struct DescriptorProto_ReservedRangeDefaultTypeInternal { PROTOBUF_CONSTEXPR DescriptorProto_ReservedRangeDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -84,17 +91,19 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 DescriptorProto_ReservedRangeDefaultTypeInternal _DescriptorProto_ReservedRange_default_instance_; PROTOBUF_CONSTEXPR DescriptorProto::DescriptorProto( - ::_pbi::ConstantInitialized) - : field_() - , nested_type_() - , enum_type_() - , extension_range_() - , extension_() - , oneof_decl_() - , reserved_range_() - , reserved_name_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , options_(nullptr){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.field_)*/{} + , /*decltype(_impl_.nested_type_)*/{} + , /*decltype(_impl_.enum_type_)*/{} + , /*decltype(_impl_.extension_range_)*/{} + , /*decltype(_impl_.extension_)*/{} + , /*decltype(_impl_.oneof_decl_)*/{} + , /*decltype(_impl_.reserved_range_)*/{} + , /*decltype(_impl_.reserved_name_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.options_)*/nullptr} {} struct DescriptorProtoDefaultTypeInternal { PROTOBUF_CONSTEXPR DescriptorProtoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -105,8 +114,10 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 DescriptorProtoDefaultTypeInternal _DescriptorProto_default_instance_; PROTOBUF_CONSTEXPR ExtensionRangeOptions::ExtensionRangeOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_(){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_._cached_size_)*/{}} {} struct ExtensionRangeOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR ExtensionRangeOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -117,20 +128,20 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ExtensionRangeOptionsDefaultTypeInternal _ExtensionRangeOptions_default_instance_; PROTOBUF_CONSTEXPR FieldDescriptorProto::FieldDescriptorProto( - ::_pbi::ConstantInitialized) - : name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , extendee_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , type_name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , default_value_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , json_name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , options_(nullptr) - , number_(0) - , oneof_index_(0) - , proto3_optional_(false) - , label_(1) - - , type_(1) -{} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.extendee_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.type_name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.default_value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.json_name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.options_)*/nullptr + , /*decltype(_impl_.number_)*/0 + , /*decltype(_impl_.oneof_index_)*/0 + , /*decltype(_impl_.proto3_optional_)*/false + , /*decltype(_impl_.label_)*/1 + , /*decltype(_impl_.type_)*/1} {} struct FieldDescriptorProtoDefaultTypeInternal { PROTOBUF_CONSTEXPR FieldDescriptorProtoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -141,9 +152,11 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FieldDescriptorProtoDefaultTypeInternal _FieldDescriptorProto_default_instance_; PROTOBUF_CONSTEXPR OneofDescriptorProto::OneofDescriptorProto( - ::_pbi::ConstantInitialized) - : name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , options_(nullptr){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.options_)*/nullptr} {} struct OneofDescriptorProtoDefaultTypeInternal { PROTOBUF_CONSTEXPR OneofDescriptorProtoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -154,9 +167,11 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 OneofDescriptorProtoDefaultTypeInternal _OneofDescriptorProto_default_instance_; PROTOBUF_CONSTEXPR EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange( - ::_pbi::ConstantInitialized) - : start_(0) - , end_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.start_)*/0 + , /*decltype(_impl_.end_)*/0} {} struct EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal { PROTOBUF_CONSTEXPR EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -167,12 +182,14 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal _EnumDescriptorProto_EnumReservedRange_default_instance_; PROTOBUF_CONSTEXPR EnumDescriptorProto::EnumDescriptorProto( - ::_pbi::ConstantInitialized) - : value_() - , reserved_range_() - , reserved_name_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , options_(nullptr){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.value_)*/{} + , /*decltype(_impl_.reserved_range_)*/{} + , /*decltype(_impl_.reserved_name_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.options_)*/nullptr} {} struct EnumDescriptorProtoDefaultTypeInternal { PROTOBUF_CONSTEXPR EnumDescriptorProtoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -183,10 +200,12 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumDescriptorProtoDefaultTypeInternal _EnumDescriptorProto_default_instance_; PROTOBUF_CONSTEXPR EnumValueDescriptorProto::EnumValueDescriptorProto( - ::_pbi::ConstantInitialized) - : name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , options_(nullptr) - , number_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.options_)*/nullptr + , /*decltype(_impl_.number_)*/0} {} struct EnumValueDescriptorProtoDefaultTypeInternal { PROTOBUF_CONSTEXPR EnumValueDescriptorProtoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -197,10 +216,12 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumValueDescriptorProtoDefaultTypeInternal _EnumValueDescriptorProto_default_instance_; PROTOBUF_CONSTEXPR ServiceDescriptorProto::ServiceDescriptorProto( - ::_pbi::ConstantInitialized) - : method_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , options_(nullptr){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.method_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.options_)*/nullptr} {} struct ServiceDescriptorProtoDefaultTypeInternal { PROTOBUF_CONSTEXPR ServiceDescriptorProtoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -211,13 +232,15 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ServiceDescriptorProtoDefaultTypeInternal _ServiceDescriptorProto_default_instance_; PROTOBUF_CONSTEXPR MethodDescriptorProto::MethodDescriptorProto( - ::_pbi::ConstantInitialized) - : name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , input_type_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , output_type_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , options_(nullptr) - , client_streaming_(false) - , server_streaming_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.input_type_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.output_type_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.options_)*/nullptr + , /*decltype(_impl_.client_streaming_)*/false + , /*decltype(_impl_.server_streaming_)*/false} {} struct MethodDescriptorProtoDefaultTypeInternal { PROTOBUF_CONSTEXPR MethodDescriptorProtoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -228,29 +251,31 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 MethodDescriptorProtoDefaultTypeInternal _MethodDescriptorProto_default_instance_; PROTOBUF_CONSTEXPR FileOptions::FileOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_() - , java_package_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , java_outer_classname_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , go_package_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , objc_class_prefix_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , csharp_namespace_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , swift_prefix_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , php_class_prefix_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , php_namespace_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , php_metadata_namespace_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , ruby_package_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , java_multiple_files_(false) - , java_generate_equals_and_hash_(false) - , java_string_check_utf8_(false) - , cc_generic_services_(false) - , java_generic_services_(false) - , py_generic_services_(false) - , php_generic_services_(false) - , deprecated_(false) - , optimize_for_(1) - - , cc_enable_arenas_(true){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_.java_package_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.java_outer_classname_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.go_package_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.objc_class_prefix_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.csharp_namespace_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.swift_prefix_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.php_class_prefix_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.php_namespace_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.php_metadata_namespace_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.ruby_package_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.java_multiple_files_)*/false + , /*decltype(_impl_.java_generate_equals_and_hash_)*/false + , /*decltype(_impl_.java_string_check_utf8_)*/false + , /*decltype(_impl_.cc_generic_services_)*/false + , /*decltype(_impl_.java_generic_services_)*/false + , /*decltype(_impl_.py_generic_services_)*/false + , /*decltype(_impl_.php_generic_services_)*/false + , /*decltype(_impl_.deprecated_)*/false + , /*decltype(_impl_.optimize_for_)*/1 + , /*decltype(_impl_.cc_enable_arenas_)*/true} {} struct FileOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR FileOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -261,12 +286,15 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FileOptionsDefaultTypeInternal _FileOptions_default_instance_; PROTOBUF_CONSTEXPR MessageOptions::MessageOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_() - , message_set_wire_format_(false) - , no_standard_descriptor_accessor_(false) - , deprecated_(false) - , map_entry_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_.message_set_wire_format_)*/false + , /*decltype(_impl_.no_standard_descriptor_accessor_)*/false + , /*decltype(_impl_.deprecated_)*/false + , /*decltype(_impl_.map_entry_)*/false} {} struct MessageOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR MessageOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -277,17 +305,18 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 MessageOptionsDefaultTypeInternal _MessageOptions_default_instance_; PROTOBUF_CONSTEXPR FieldOptions::FieldOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_() - , ctype_(0) - - , jstype_(0) - - , packed_(false) - , lazy_(false) - , unverified_lazy_(false) - , deprecated_(false) - , weak_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_.ctype_)*/0 + , /*decltype(_impl_.jstype_)*/0 + , /*decltype(_impl_.packed_)*/false + , /*decltype(_impl_.lazy_)*/false + , /*decltype(_impl_.unverified_lazy_)*/false + , /*decltype(_impl_.deprecated_)*/false + , /*decltype(_impl_.weak_)*/false} {} struct FieldOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR FieldOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -298,8 +327,10 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FieldOptionsDefaultTypeInternal _FieldOptions_default_instance_; PROTOBUF_CONSTEXPR OneofOptions::OneofOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_(){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_._cached_size_)*/{}} {} struct OneofOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR OneofOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -310,10 +341,13 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 OneofOptionsDefaultTypeInternal _OneofOptions_default_instance_; PROTOBUF_CONSTEXPR EnumOptions::EnumOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_() - , allow_alias_(false) - , deprecated_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_.allow_alias_)*/false + , /*decltype(_impl_.deprecated_)*/false} {} struct EnumOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR EnumOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -324,9 +358,12 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumOptionsDefaultTypeInternal _EnumOptions_default_instance_; PROTOBUF_CONSTEXPR EnumValueOptions::EnumValueOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_() - , deprecated_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_.deprecated_)*/false} {} struct EnumValueOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR EnumValueOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -337,9 +374,12 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumValueOptionsDefaultTypeInternal _EnumValueOptions_default_instance_; PROTOBUF_CONSTEXPR ServiceOptions::ServiceOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_() - , deprecated_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_.deprecated_)*/false} {} struct ServiceOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR ServiceOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -350,11 +390,13 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ServiceOptionsDefaultTypeInternal _ServiceOptions_default_instance_; PROTOBUF_CONSTEXPR MethodOptions::MethodOptions( - ::_pbi::ConstantInitialized) - : uninterpreted_option_() - , deprecated_(false) - , idempotency_level_(0) -{} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._extensions_)*/{} + , /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.uninterpreted_option_)*/{} + , /*decltype(_impl_.deprecated_)*/false + , /*decltype(_impl_.idempotency_level_)*/0} {} struct MethodOptionsDefaultTypeInternal { PROTOBUF_CONSTEXPR MethodOptionsDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -365,9 +407,11 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 MethodOptionsDefaultTypeInternal _MethodOptions_default_instance_; PROTOBUF_CONSTEXPR UninterpretedOption_NamePart::UninterpretedOption_NamePart( - ::_pbi::ConstantInitialized) - : name_part_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , is_extension_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.name_part_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.is_extension_)*/false} {} struct UninterpretedOption_NamePartDefaultTypeInternal { PROTOBUF_CONSTEXPR UninterpretedOption_NamePartDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -378,14 +422,16 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 UninterpretedOption_NamePartDefaultTypeInternal _UninterpretedOption_NamePart_default_instance_; PROTOBUF_CONSTEXPR UninterpretedOption::UninterpretedOption( - ::_pbi::ConstantInitialized) - : name_() - , identifier_value_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , string_value_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , aggregate_value_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , positive_int_value_(uint64_t{0u}) - , negative_int_value_(int64_t{0}) - , double_value_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.name_)*/{} + , /*decltype(_impl_.identifier_value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.string_value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.aggregate_value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.positive_int_value_)*/uint64_t{0u} + , /*decltype(_impl_.negative_int_value_)*/int64_t{0} + , /*decltype(_impl_.double_value_)*/0} {} struct UninterpretedOptionDefaultTypeInternal { PROTOBUF_CONSTEXPR UninterpretedOptionDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -396,14 +442,16 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 UninterpretedOptionDefaultTypeInternal _UninterpretedOption_default_instance_; PROTOBUF_CONSTEXPR SourceCodeInfo_Location::SourceCodeInfo_Location( - ::_pbi::ConstantInitialized) - : path_() - , _path_cached_byte_size_(0) - , span_() - , _span_cached_byte_size_(0) - , leading_detached_comments_() - , leading_comments_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , trailing_comments_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.path_)*/{} + , /*decltype(_impl_._path_cached_byte_size_)*/{0} + , /*decltype(_impl_.span_)*/{} + , /*decltype(_impl_._span_cached_byte_size_)*/{0} + , /*decltype(_impl_.leading_detached_comments_)*/{} + , /*decltype(_impl_.leading_comments_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.trailing_comments_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}}} {} struct SourceCodeInfo_LocationDefaultTypeInternal { PROTOBUF_CONSTEXPR SourceCodeInfo_LocationDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -414,8 +462,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SourceCodeInfo_LocationDefaultTypeInternal _SourceCodeInfo_Location_default_instance_; PROTOBUF_CONSTEXPR SourceCodeInfo::SourceCodeInfo( - ::_pbi::ConstantInitialized) - : location_(){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.location_)*/{} + , /*decltype(_impl_._cached_size_)*/{}} {} struct SourceCodeInfoDefaultTypeInternal { PROTOBUF_CONSTEXPR SourceCodeInfoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -426,12 +475,14 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 SourceCodeInfoDefaultTypeInternal _SourceCodeInfo_default_instance_; PROTOBUF_CONSTEXPR GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation( - ::_pbi::ConstantInitialized) - : path_() - , _path_cached_byte_size_(0) - , source_file_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , begin_(0) - , end_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_._has_bits_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_.path_)*/{} + , /*decltype(_impl_._path_cached_byte_size_)*/{0} + , /*decltype(_impl_.source_file_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.begin_)*/0 + , /*decltype(_impl_.end_)*/0} {} struct GeneratedCodeInfo_AnnotationDefaultTypeInternal { PROTOBUF_CONSTEXPR GeneratedCodeInfo_AnnotationDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -442,8 +493,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 GeneratedCodeInfo_AnnotationDefaultTypeInternal _GeneratedCodeInfo_Annotation_default_instance_; PROTOBUF_CONSTEXPR GeneratedCodeInfo::GeneratedCodeInfo( - ::_pbi::ConstantInitialized) - : annotation_(){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.annotation_)*/{} + , /*decltype(_impl_._cached_size_)*/{}} {} struct GeneratedCodeInfoDefaultTypeInternal { PROTOBUF_CONSTEXPR GeneratedCodeInfoDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -465,25 +517,25 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorSet, file_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorSet, _impl_.file_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, package_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, dependency_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, public_dependency_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, weak_dependency_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, message_type_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, enum_type_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, service_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, extension_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, source_code_info_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, syntax_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.package_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.dependency_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.public_dependency_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.weak_dependency_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.message_type_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.enum_type_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.service_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.extension_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.source_code_info_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileDescriptorProto, _impl_.syntax_), 0, 1, ~0u, @@ -496,44 +548,44 @@ 3, 4, 2, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, start_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, end_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, _impl_.start_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, _impl_.end_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange, _impl_.options_), 1, 2, 0, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, start_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, end_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, _impl_.start_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange, _impl_.end_), 0, 1, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, field_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, extension_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, nested_type_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, enum_type_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, extension_range_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, oneof_decl_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, reserved_range_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, reserved_name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.field_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.extension_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.nested_type_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.enum_type_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.extension_range_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.oneof_decl_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.reserved_range_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DescriptorProto, _impl_.reserved_name_), 0, ~0u, ~0u, @@ -546,28 +598,28 @@ ~0u, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, uninterpreted_option_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions, _impl_.uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, number_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, label_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, type_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, type_name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, extendee_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, default_value_), - 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_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.number_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.label_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.type_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.type_name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.extendee_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.default_value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.oneof_index_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.json_name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto, _impl_.proto3_optional_), 0, 6, 9, @@ -579,111 +631,111 @@ 4, 5, 8, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto, _impl_.options_), 0, 1, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, start_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, end_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, _impl_.start_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange, _impl_.end_), 0, 1, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, value_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, reserved_range_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, reserved_name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _impl_.value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _impl_.reserved_range_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto, _impl_.reserved_name_), 0, ~0u, 1, ~0u, ~0u, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, number_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, _impl_.number_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto, _impl_.options_), 0, 2, 1, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, method_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, _impl_.method_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto, _impl_.options_), 0, ~0u, 1, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, input_type_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, output_type_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, client_streaming_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, server_streaming_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _impl_.input_type_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _impl_.output_type_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _impl_.client_streaming_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto, _impl_.server_streaming_), 0, 1, 2, 3, 4, 5, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, java_package_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, java_outer_classname_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, java_multiple_files_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, java_generate_equals_and_hash_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, java_string_check_utf8_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, optimize_for_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, go_package_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, cc_generic_services_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, java_generic_services_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, py_generic_services_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, php_generic_services_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, deprecated_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, cc_enable_arenas_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, objc_class_prefix_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, csharp_namespace_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, swift_prefix_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, php_class_prefix_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, php_namespace_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, php_metadata_namespace_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, ruby_package_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.java_package_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.java_outer_classname_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.java_multiple_files_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.java_generate_equals_and_hash_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.java_string_check_utf8_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.optimize_for_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.go_package_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.cc_generic_services_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.java_generic_services_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.py_generic_services_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.php_generic_services_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.deprecated_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.cc_enable_arenas_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.objc_class_prefix_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.csharp_namespace_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.swift_prefix_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.php_class_prefix_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.php_namespace_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.php_metadata_namespace_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.ruby_package_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FileOptions, _impl_.uninterpreted_option_), 0, 1, 10, @@ -705,36 +757,36 @@ 8, 9, ~0u, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, message_set_wire_format_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, no_standard_descriptor_accessor_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, deprecated_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, map_entry_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _impl_.message_set_wire_format_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _impl_.no_standard_descriptor_accessor_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _impl_.deprecated_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _impl_.map_entry_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MessageOptions, _impl_.uninterpreted_option_), 0, 1, 2, 3, ~0u, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, ctype_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, packed_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, jstype_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, lazy_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, unverified_lazy_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, deprecated_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, weak_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_.ctype_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_.packed_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_.jstype_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_.lazy_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_.unverified_lazy_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_.deprecated_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_.weak_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldOptions, _impl_.uninterpreted_option_), 0, 2, 1, @@ -745,78 +797,78 @@ ~0u, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofOptions, uninterpreted_option_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::OneofOptions, _impl_.uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, allow_alias_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, deprecated_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, _impl_.allow_alias_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, _impl_.deprecated_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumOptions, _impl_.uninterpreted_option_), 0, 1, ~0u, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, deprecated_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, _impl_.deprecated_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValueOptions, _impl_.uninterpreted_option_), 0, ~0u, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, deprecated_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, _impl_.deprecated_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ServiceOptions, _impl_.uninterpreted_option_), 0, ~0u, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, _internal_metadata_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, _extensions_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, _impl_._extensions_), ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, deprecated_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, idempotency_level_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, uninterpreted_option_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, _impl_.deprecated_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, _impl_.idempotency_level_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::MethodOptions, _impl_.uninterpreted_option_), 0, 1, ~0u, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, name_part_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, is_extension_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, _impl_.name_part_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart, _impl_.is_extension_), 0, 1, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, identifier_value_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, positive_int_value_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, negative_int_value_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, double_value_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, string_value_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, aggregate_value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _impl_.identifier_value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _impl_.positive_int_value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _impl_.negative_int_value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _impl_.double_value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _impl_.string_value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UninterpretedOption, _impl_.aggregate_value_), ~0u, 0, 3, @@ -824,17 +876,17 @@ 5, 1, 2, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, path_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, span_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, leading_comments_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, trailing_comments_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, leading_detached_comments_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _impl_.path_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _impl_.span_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _impl_.leading_comments_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _impl_.trailing_comments_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location, _impl_.leading_detached_comments_), ~0u, ~0u, 0, @@ -846,17 +898,17 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo, location_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _has_bits_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo, _impl_.location_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _impl_._has_bits_), PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, path_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, source_file_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, begin_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, end_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _impl_.path_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _impl_.source_file_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _impl_.begin_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation, _impl_.end_), ~0u, 0, 1, @@ -867,7 +919,7 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo, annotation_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo, _impl_.annotation_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::FileDescriptorSet)}, @@ -1276,19 +1328,28 @@ FileDescriptorSet::FileDescriptorSet(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - file_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorSet) } FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - file_(from.file_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.file_){from._impl_.file_} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorSet) } -inline void FileDescriptorSet::SharedCtor() { +inline void FileDescriptorSet::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.file_){arena} + , /*decltype(_impl_._cached_size_)*/{} + }; } FileDescriptorSet::~FileDescriptorSet() { @@ -1302,10 +1363,11 @@ inline void FileDescriptorSet::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_.file_.~RepeatedPtrField(); } void FileDescriptorSet::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void FileDescriptorSet::Clear() { @@ -1314,7 +1376,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - file_.Clear(); + _impl_.file_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1392,16 +1454,16 @@ // repeated .google.protobuf.FileDescriptorProto file = 1; total_size += 1UL * this->_internal_file_size(); - for (const auto& msg : this->file_) { + for (const auto& msg : this->_impl_.file_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData FileDescriptorSet::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, FileDescriptorSet::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*FileDescriptorSet::GetClassData() const { return &_class_data_; } @@ -1419,7 +1481,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - file_.MergeFrom(from.file_); + _impl_.file_.MergeFrom(from._impl_.file_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -1431,7 +1493,7 @@ } bool FileDescriptorSet::IsInitialized() const { - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(file_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.file_)) return false; return true; } @@ -1439,7 +1501,7 @@ void FileDescriptorSet::InternalSwap(FileDescriptorSet* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - file_.InternalSwap(&other->file_); + _impl_.file_.InternalSwap(&other->_impl_.file_); } ::PROTOBUF_NAMESPACE_ID::Metadata FileDescriptorSet::GetMetadata() const { @@ -1452,7 +1514,7 @@ class FileDescriptorProto::_Internal { public: - using HasBits = decltype(std::declval<FileDescriptorProto>()._has_bits_); + using HasBits = decltype(std::declval<FileDescriptorProto>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -1474,90 +1536,102 @@ const ::PROTOBUF_NAMESPACE_ID::FileOptions& FileDescriptorProto::_Internal::options(const FileDescriptorProto* msg) { - return *msg->options_; + return *msg->_impl_.options_; } const ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo& FileDescriptorProto::_Internal::source_code_info(const FileDescriptorProto* msg) { - return *msg->source_code_info_; + return *msg->_impl_.source_code_info_; } FileDescriptorProto::FileDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - dependency_(arena), - message_type_(arena), - enum_type_(arena), - service_(arena), - extension_(arena), - public_dependency_(arena), - weak_dependency_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileDescriptorProto) } FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - dependency_(from.dependency_), - message_type_(from.message_type_), - enum_type_(from.enum_type_), - service_(from.service_), - extension_(from.extension_), - public_dependency_(from.public_dependency_), - weak_dependency_(from.weak_dependency_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.dependency_){from._impl_.dependency_} + , decltype(_impl_.message_type_){from._impl_.message_type_} + , decltype(_impl_.enum_type_){from._impl_.enum_type_} + , decltype(_impl_.service_){from._impl_.service_} + , decltype(_impl_.extension_){from._impl_.extension_} + , decltype(_impl_.public_dependency_){from._impl_.public_dependency_} + , decltype(_impl_.weak_dependency_){from._impl_.weak_dependency_} + , decltype(_impl_.name_){} + , decltype(_impl_.package_){} + , decltype(_impl_.syntax_){} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.source_code_info_){nullptr}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - package_.InitDefault(); + _impl_.package_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - package_.Set("", GetArenaForAllocation()); + _impl_.package_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_package()) { - package_.Set(from._internal_package(), + _impl_.package_.Set(from._internal_package(), GetArenaForAllocation()); } - syntax_.InitDefault(); + _impl_.syntax_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - syntax_.Set("", GetArenaForAllocation()); + _impl_.syntax_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_syntax()) { - syntax_.Set(from._internal_syntax(), + _impl_.syntax_.Set(from._internal_syntax(), GetArenaForAllocation()); } if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::FileOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::FileOptions(*from._impl_.options_); } if (from._internal_has_source_code_info()) { - source_code_info_ = new ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo(*from.source_code_info_); - } else { - source_code_info_ = nullptr; + _impl_.source_code_info_ = new ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo(*from._impl_.source_code_info_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.FileDescriptorProto) } -inline void FileDescriptorProto::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -package_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - package_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -syntax_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - syntax_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&options_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&source_code_info_) - - reinterpret_cast<char*>(&options_)) + sizeof(source_code_info_)); +inline void FileDescriptorProto::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.dependency_){arena} + , decltype(_impl_.message_type_){arena} + , decltype(_impl_.enum_type_){arena} + , decltype(_impl_.service_){arena} + , decltype(_impl_.extension_){arena} + , decltype(_impl_.public_dependency_){arena} + , decltype(_impl_.weak_dependency_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.package_){} + , decltype(_impl_.syntax_){} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.source_code_info_){nullptr} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.package_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.package_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.syntax_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.syntax_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } FileDescriptorProto::~FileDescriptorProto() { @@ -1571,15 +1645,22 @@ inline void FileDescriptorProto::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - package_.Destroy(); - syntax_.Destroy(); - if (this != internal_default_instance()) delete options_; - if (this != internal_default_instance()) delete source_code_info_; + _impl_.dependency_.~RepeatedPtrField(); + _impl_.message_type_.~RepeatedPtrField(); + _impl_.enum_type_.~RepeatedPtrField(); + _impl_.service_.~RepeatedPtrField(); + _impl_.extension_.~RepeatedPtrField(); + _impl_.public_dependency_.~RepeatedField(); + _impl_.weak_dependency_.~RepeatedField(); + _impl_.name_.Destroy(); + _impl_.package_.Destroy(); + _impl_.syntax_.Destroy(); + if (this != internal_default_instance()) delete _impl_.options_; + if (this != internal_default_instance()) delete _impl_.source_code_info_; } void FileDescriptorProto::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void FileDescriptorProto::Clear() { @@ -1588,34 +1669,34 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - dependency_.Clear(); - message_type_.Clear(); - enum_type_.Clear(); - service_.Clear(); - extension_.Clear(); - public_dependency_.Clear(); - weak_dependency_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.dependency_.Clear(); + _impl_.message_type_.Clear(); + _impl_.enum_type_.Clear(); + _impl_.service_.Clear(); + _impl_.extension_.Clear(); + _impl_.public_dependency_.Clear(); + _impl_.weak_dependency_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - package_.ClearNonDefaultToEmpty(); + _impl_.package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - syntax_.ClearNonDefaultToEmpty(); + _impl_.syntax_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } if (cached_has_bits & 0x00000010u) { - GOOGLE_DCHECK(source_code_info_ != nullptr); - source_code_info_->Clear(); + GOOGLE_DCHECK(_impl_.source_code_info_ != nullptr); + _impl_.source_code_info_->Clear(); } } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1795,7 +1876,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -1809,7 +1890,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -1926,36 +2007,36 @@ // repeated string dependency = 3; total_size += 1 * - ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(dependency_.size()); - for (int i = 0, n = dependency_.size(); i < n; i++) { + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(_impl_.dependency_.size()); + for (int i = 0, n = _impl_.dependency_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( - dependency_.Get(i)); + _impl_.dependency_.Get(i)); } // repeated .google.protobuf.DescriptorProto message_type = 4; total_size += 1UL * this->_internal_message_type_size(); - for (const auto& msg : this->message_type_) { + for (const auto& msg : this->_impl_.message_type_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; total_size += 1UL * this->_internal_enum_type_size(); - for (const auto& msg : this->enum_type_) { + for (const auto& msg : this->_impl_.enum_type_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.ServiceDescriptorProto service = 6; total_size += 1UL * this->_internal_service_size(); - for (const auto& msg : this->service_) { + for (const auto& msg : this->_impl_.service_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.FieldDescriptorProto extension = 7; total_size += 1UL * this->_internal_extension_size(); - for (const auto& msg : this->extension_) { + for (const auto& msg : this->_impl_.extension_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } @@ -1963,7 +2044,7 @@ // repeated int32 public_dependency = 10; { size_t data_size = ::_pbi::WireFormatLite:: - Int32Size(this->public_dependency_); + Int32Size(this->_impl_.public_dependency_); total_size += 1 * ::_pbi::FromIntSize(this->_internal_public_dependency_size()); total_size += data_size; @@ -1972,13 +2053,13 @@ // repeated int32 weak_dependency = 11; { size_t data_size = ::_pbi::WireFormatLite:: - Int32Size(this->weak_dependency_); + Int32Size(this->_impl_.weak_dependency_); total_size += 1 * ::_pbi::FromIntSize(this->_internal_weak_dependency_size()); total_size += data_size; } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000001fu) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -2005,22 +2086,22 @@ if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *source_code_info_); + *_impl_.source_code_info_); } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData FileDescriptorProto::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, FileDescriptorProto::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*FileDescriptorProto::GetClassData() const { return &_class_data_; } @@ -2038,14 +2119,14 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - dependency_.MergeFrom(from.dependency_); - message_type_.MergeFrom(from.message_type_); - enum_type_.MergeFrom(from.enum_type_); - service_.MergeFrom(from.service_); - extension_.MergeFrom(from.extension_); - public_dependency_.MergeFrom(from.public_dependency_); - weak_dependency_.MergeFrom(from.weak_dependency_); - cached_has_bits = from._has_bits_[0]; + _impl_.dependency_.MergeFrom(from._impl_.dependency_); + _impl_.message_type_.MergeFrom(from._impl_.message_type_); + _impl_.enum_type_.MergeFrom(from._impl_.enum_type_); + _impl_.service_.MergeFrom(from._impl_.service_); + _impl_.extension_.MergeFrom(from._impl_.extension_); + _impl_.public_dependency_.MergeFrom(from._impl_.public_dependency_); + _impl_.weak_dependency_.MergeFrom(from._impl_.weak_dependency_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -2074,16 +2155,16 @@ } bool FileDescriptorProto::IsInitialized() const { - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(message_type_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.message_type_)) return false; - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(enum_type_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.enum_type_)) return false; - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(service_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.service_)) return false; - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(extension_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.extension_)) return false; if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -2093,32 +2174,32 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - dependency_.InternalSwap(&other->dependency_); - message_type_.InternalSwap(&other->message_type_); - enum_type_.InternalSwap(&other->enum_type_); - service_.InternalSwap(&other->service_); - extension_.InternalSwap(&other->extension_); - public_dependency_.InternalSwap(&other->public_dependency_); - weak_dependency_.InternalSwap(&other->weak_dependency_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.dependency_.InternalSwap(&other->_impl_.dependency_); + _impl_.message_type_.InternalSwap(&other->_impl_.message_type_); + _impl_.enum_type_.InternalSwap(&other->_impl_.enum_type_); + _impl_.service_.InternalSwap(&other->_impl_.service_); + _impl_.extension_.InternalSwap(&other->_impl_.extension_); + _impl_.public_dependency_.InternalSwap(&other->_impl_.public_dependency_); + _impl_.weak_dependency_.InternalSwap(&other->_impl_.weak_dependency_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &package_, lhs_arena, - &other->package_, rhs_arena + &_impl_.package_, lhs_arena, + &other->_impl_.package_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &syntax_, lhs_arena, - &other->syntax_, rhs_arena + &_impl_.syntax_, lhs_arena, + &other->_impl_.syntax_, rhs_arena ); ::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_FIELD_OFFSET(FileDescriptorProto, _impl_.source_code_info_) + + sizeof(FileDescriptorProto::_impl_.source_code_info_) + - PROTOBUF_FIELD_OFFSET(FileDescriptorProto, _impl_.options_)>( + reinterpret_cast<char*>(&_impl_.options_), + reinterpret_cast<char*>(&other->_impl_.options_)); } ::PROTOBUF_NAMESPACE_ID::Metadata FileDescriptorProto::GetMetadata() const { @@ -2131,7 +2212,7 @@ class DescriptorProto_ExtensionRange::_Internal { public: - using HasBits = decltype(std::declval<DescriptorProto_ExtensionRange>()._has_bits_); + using HasBits = decltype(std::declval<DescriptorProto_ExtensionRange>()._impl_._has_bits_); static void set_has_start(HasBits* has_bits) { (*has_bits)[0] |= 2u; } @@ -2146,34 +2227,44 @@ const ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions& DescriptorProto_ExtensionRange::_Internal::options(const DescriptorProto_ExtensionRange* msg) { - return *msg->options_; + return *msg->_impl_.options_; } DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ExtensionRange) } DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.start_){} + , decltype(_impl_.end_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions(*from._impl_.options_); } - ::memcpy(&start_, &from.start_, - static_cast<size_t>(reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&start_)) + sizeof(end_)); + ::memcpy(&_impl_.start_, &from._impl_.start_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.end_) - + reinterpret_cast<char*>(&_impl_.start_)) + sizeof(_impl_.end_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto.ExtensionRange) } -inline void DescriptorProto_ExtensionRange::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&options_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&options_)) + sizeof(end_)); +inline void DescriptorProto_ExtensionRange::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.start_){0} + , decltype(_impl_.end_){0} + }; } DescriptorProto_ExtensionRange::~DescriptorProto_ExtensionRange() { @@ -2187,11 +2278,11 @@ inline void DescriptorProto_ExtensionRange::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - if (this != internal_default_instance()) delete options_; + if (this != internal_default_instance()) delete _impl_.options_; } void DescriptorProto_ExtensionRange::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void DescriptorProto_ExtensionRange::Clear() { @@ -2200,17 +2291,17 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000001u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } if (cached_has_bits & 0x00000006u) { - ::memset(&start_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&start_)) + sizeof(end_)); + ::memset(&_impl_.start_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.end_) - + reinterpret_cast<char*>(&_impl_.start_)) + sizeof(_impl_.end_)); } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -2225,7 +2316,7 @@ case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { _Internal::set_has_start(&has_bits); - start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -2234,7 +2325,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_end(&has_bits); - end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -2263,7 +2354,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -2277,7 +2368,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000002u) { target = stream->EnsureSpace(target); @@ -2313,13 +2404,13 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000007u) { // optional .google.protobuf.ExtensionRangeOptions options = 3; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } // optional int32 start = 1; @@ -2333,11 +2424,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData DescriptorProto_ExtensionRange::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, DescriptorProto_ExtensionRange::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*DescriptorProto_ExtensionRange::GetClassData() const { return &_class_data_; } @@ -2355,18 +2446,18 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { _internal_mutable_options()->::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions::MergeFrom(from._internal_options()); } if (cached_has_bits & 0x00000002u) { - start_ = from.start_; + _impl_.start_ = from._impl_.start_; } if (cached_has_bits & 0x00000004u) { - end_ = from.end_; + _impl_.end_ = from._impl_.end_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -2380,7 +2471,7 @@ bool DescriptorProto_ExtensionRange::IsInitialized() const { if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -2388,13 +2479,13 @@ void DescriptorProto_ExtensionRange::InternalSwap(DescriptorProto_ExtensionRange* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::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_FIELD_OFFSET(DescriptorProto_ExtensionRange, _impl_.end_) + + sizeof(DescriptorProto_ExtensionRange::_impl_.end_) + - PROTOBUF_FIELD_OFFSET(DescriptorProto_ExtensionRange, _impl_.options_)>( + reinterpret_cast<char*>(&_impl_.options_), + reinterpret_cast<char*>(&other->_impl_.options_)); } ::PROTOBUF_NAMESPACE_ID::Metadata DescriptorProto_ExtensionRange::GetMetadata() const { @@ -2407,7 +2498,7 @@ class DescriptorProto_ReservedRange::_Internal { public: - using HasBits = decltype(std::declval<DescriptorProto_ReservedRange>()._has_bits_); + using HasBits = decltype(std::declval<DescriptorProto_ReservedRange>()._impl_._has_bits_); static void set_has_start(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -2419,24 +2510,34 @@ DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto.ReservedRange) } DescriptorProto_ReservedRange::DescriptorProto_ReservedRange(const DescriptorProto_ReservedRange& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.start_){} + , decltype(_impl_.end_){}}; + _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_)); + ::memcpy(&_impl_.start_, &from._impl_.start_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.end_) - + reinterpret_cast<char*>(&_impl_.start_)) + sizeof(_impl_.end_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto.ReservedRange) } -inline void DescriptorProto_ReservedRange::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&start_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&start_)) + sizeof(end_)); +inline void DescriptorProto_ReservedRange::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.start_){0} + , decltype(_impl_.end_){0} + }; } DescriptorProto_ReservedRange::~DescriptorProto_ReservedRange() { @@ -2453,7 +2554,7 @@ } void DescriptorProto_ReservedRange::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void DescriptorProto_ReservedRange::Clear() { @@ -2462,13 +2563,13 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { - ::memset(&start_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&start_)) + sizeof(end_)); + ::memset(&_impl_.start_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.end_) - + reinterpret_cast<char*>(&_impl_.start_)) + sizeof(_impl_.end_)); } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -2483,7 +2584,7 @@ case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { _Internal::set_has_start(&has_bits); - start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -2492,7 +2593,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_end(&has_bits); - end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -2513,7 +2614,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -2527,7 +2628,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); @@ -2556,7 +2657,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional int32 start = 1; if (cached_has_bits & 0x00000001u) { @@ -2569,11 +2670,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData DescriptorProto_ReservedRange::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, DescriptorProto_ReservedRange::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*DescriptorProto_ReservedRange::GetClassData() const { return &_class_data_; } @@ -2591,15 +2692,15 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - start_ = from.start_; + _impl_.start_ = from._impl_.start_; } if (cached_has_bits & 0x00000002u) { - end_ = from.end_; + _impl_.end_ = from._impl_.end_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -2618,13 +2719,13 @@ void DescriptorProto_ReservedRange::InternalSwap(DescriptorProto_ReservedRange* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::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_FIELD_OFFSET(DescriptorProto_ReservedRange, _impl_.end_) + + sizeof(DescriptorProto_ReservedRange::_impl_.end_) + - PROTOBUF_FIELD_OFFSET(DescriptorProto_ReservedRange, _impl_.start_)>( + reinterpret_cast<char*>(&_impl_.start_), + reinterpret_cast<char*>(&other->_impl_.start_)); } ::PROTOBUF_NAMESPACE_ID::Metadata DescriptorProto_ReservedRange::GetMetadata() const { @@ -2637,7 +2738,7 @@ class DescriptorProto::_Internal { public: - using HasBits = decltype(std::declval<DescriptorProto>()._has_bits_); + using HasBits = decltype(std::declval<DescriptorProto>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -2649,56 +2750,67 @@ const ::PROTOBUF_NAMESPACE_ID::MessageOptions& DescriptorProto::_Internal::options(const DescriptorProto* msg) { - return *msg->options_; + return *msg->_impl_.options_; } DescriptorProto::DescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - field_(arena), - nested_type_(arena), - enum_type_(arena), - extension_range_(arena), - extension_(arena), - oneof_decl_(arena), - reserved_range_(arena), - reserved_name_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.DescriptorProto) } DescriptorProto::DescriptorProto(const DescriptorProto& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - field_(from.field_), - nested_type_(from.nested_type_), - enum_type_(from.enum_type_), - extension_range_(from.extension_range_), - extension_(from.extension_), - oneof_decl_(from.oneof_decl_), - reserved_range_(from.reserved_range_), - reserved_name_(from.reserved_name_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.field_){from._impl_.field_} + , decltype(_impl_.nested_type_){from._impl_.nested_type_} + , decltype(_impl_.enum_type_){from._impl_.enum_type_} + , decltype(_impl_.extension_range_){from._impl_.extension_range_} + , decltype(_impl_.extension_){from._impl_.extension_} + , decltype(_impl_.oneof_decl_){from._impl_.oneof_decl_} + , decltype(_impl_.reserved_range_){from._impl_.reserved_range_} + , decltype(_impl_.reserved_name_){from._impl_.reserved_name_} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::MessageOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::MessageOptions(*from._impl_.options_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.DescriptorProto) } -inline void DescriptorProto::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -options_ = nullptr; +inline void DescriptorProto::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.field_){arena} + , decltype(_impl_.nested_type_){arena} + , decltype(_impl_.enum_type_){arena} + , decltype(_impl_.extension_range_){arena} + , decltype(_impl_.extension_){arena} + , decltype(_impl_.oneof_decl_){arena} + , decltype(_impl_.reserved_range_){arena} + , decltype(_impl_.reserved_name_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } DescriptorProto::~DescriptorProto() { @@ -2712,12 +2824,20 @@ inline void DescriptorProto::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - if (this != internal_default_instance()) delete options_; + _impl_.field_.~RepeatedPtrField(); + _impl_.nested_type_.~RepeatedPtrField(); + _impl_.enum_type_.~RepeatedPtrField(); + _impl_.extension_range_.~RepeatedPtrField(); + _impl_.extension_.~RepeatedPtrField(); + _impl_.oneof_decl_.~RepeatedPtrField(); + _impl_.reserved_range_.~RepeatedPtrField(); + _impl_.reserved_name_.~RepeatedPtrField(); + _impl_.name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.options_; } void DescriptorProto::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void DescriptorProto::Clear() { @@ -2726,25 +2846,25 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - field_.Clear(); - nested_type_.Clear(); - enum_type_.Clear(); - extension_range_.Clear(); - extension_.Clear(); - oneof_decl_.Clear(); - reserved_range_.Clear(); - reserved_name_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.field_.Clear(); + _impl_.nested_type_.Clear(); + _impl_.enum_type_.Clear(); + _impl_.extension_range_.Clear(); + _impl_.extension_.Clear(); + _impl_.oneof_decl_.Clear(); + _impl_.reserved_range_.Clear(); + _impl_.reserved_name_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -2899,7 +3019,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -2913,7 +3033,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -3015,62 +3135,62 @@ // repeated .google.protobuf.FieldDescriptorProto field = 2; total_size += 1UL * this->_internal_field_size(); - for (const auto& msg : this->field_) { + for (const auto& msg : this->_impl_.field_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.DescriptorProto nested_type = 3; total_size += 1UL * this->_internal_nested_type_size(); - for (const auto& msg : this->nested_type_) { + for (const auto& msg : this->_impl_.nested_type_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; total_size += 1UL * this->_internal_enum_type_size(); - for (const auto& msg : this->enum_type_) { + for (const auto& msg : this->_impl_.enum_type_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; total_size += 1UL * this->_internal_extension_range_size(); - for (const auto& msg : this->extension_range_) { + for (const auto& msg : this->_impl_.extension_range_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.FieldDescriptorProto extension = 6; total_size += 1UL * this->_internal_extension_size(); - for (const auto& msg : this->extension_) { + for (const auto& msg : this->_impl_.extension_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; total_size += 1UL * this->_internal_oneof_decl_size(); - for (const auto& msg : this->oneof_decl_) { + for (const auto& msg : this->_impl_.oneof_decl_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; total_size += 1UL * this->_internal_reserved_range_size(); - for (const auto& msg : this->reserved_range_) { + for (const auto& msg : this->_impl_.reserved_range_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated string reserved_name = 10; total_size += 1 * - ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(reserved_name_.size()); - for (int i = 0, n = reserved_name_.size(); i < n; i++) { + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(_impl_.reserved_name_.size()); + for (int i = 0, n = _impl_.reserved_name_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( - reserved_name_.Get(i)); + _impl_.reserved_name_.Get(i)); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -3083,15 +3203,15 @@ if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData DescriptorProto::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, DescriptorProto::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*DescriptorProto::GetClassData() const { return &_class_data_; } @@ -3109,15 +3229,15 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - field_.MergeFrom(from.field_); - nested_type_.MergeFrom(from.nested_type_); - enum_type_.MergeFrom(from.enum_type_); - extension_range_.MergeFrom(from.extension_range_); - extension_.MergeFrom(from.extension_); - oneof_decl_.MergeFrom(from.oneof_decl_); - reserved_range_.MergeFrom(from.reserved_range_); - reserved_name_.MergeFrom(from.reserved_name_); - cached_has_bits = from._has_bits_[0]; + _impl_.field_.MergeFrom(from._impl_.field_); + _impl_.nested_type_.MergeFrom(from._impl_.nested_type_); + _impl_.enum_type_.MergeFrom(from._impl_.enum_type_); + _impl_.extension_range_.MergeFrom(from._impl_.extension_range_); + _impl_.extension_.MergeFrom(from._impl_.extension_); + _impl_.oneof_decl_.MergeFrom(from._impl_.oneof_decl_); + _impl_.reserved_range_.MergeFrom(from._impl_.reserved_range_); + _impl_.reserved_name_.MergeFrom(from._impl_.reserved_name_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -3137,20 +3257,20 @@ } bool DescriptorProto::IsInitialized() const { - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(field_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.field_)) return false; - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(nested_type_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.nested_type_)) return false; - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(enum_type_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.enum_type_)) return false; - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(extension_range_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.extension_range_)) return false; - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(extension_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.extension_)) return false; - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(oneof_decl_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.oneof_decl_)) return false; if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -3160,20 +3280,20 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - field_.InternalSwap(&other->field_); - nested_type_.InternalSwap(&other->nested_type_); - enum_type_.InternalSwap(&other->enum_type_); - extension_range_.InternalSwap(&other->extension_range_); - extension_.InternalSwap(&other->extension_); - oneof_decl_.InternalSwap(&other->oneof_decl_); - reserved_range_.InternalSwap(&other->reserved_range_); - reserved_name_.InternalSwap(&other->reserved_name_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.field_.InternalSwap(&other->_impl_.field_); + _impl_.nested_type_.InternalSwap(&other->_impl_.nested_type_); + _impl_.enum_type_.InternalSwap(&other->_impl_.enum_type_); + _impl_.extension_range_.InternalSwap(&other->_impl_.extension_range_); + _impl_.extension_.InternalSwap(&other->_impl_.extension_); + _impl_.oneof_decl_.InternalSwap(&other->_impl_.oneof_decl_); + _impl_.reserved_range_.InternalSwap(&other->_impl_.reserved_range_); + _impl_.reserved_name_.InternalSwap(&other->_impl_.reserved_name_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); - swap(options_, other->options_); + swap(_impl_.options_, other->_impl_.options_); } ::PROTOBUF_NAMESPACE_ID::Metadata DescriptorProto::GetMetadata() const { @@ -3190,21 +3310,31 @@ ExtensionRangeOptions::ExtensionRangeOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.ExtensionRangeOptions) } ExtensionRangeOptions::ExtensionRangeOptions(const ExtensionRangeOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); // @@protoc_insertion_point(copy_constructor:google.protobuf.ExtensionRangeOptions) } -inline void ExtensionRangeOptions::SharedCtor() { +inline void ExtensionRangeOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_.uninterpreted_option_){arena} + , /*decltype(_impl_._cached_size_)*/{} + }; } ExtensionRangeOptions::~ExtensionRangeOptions() { @@ -3218,10 +3348,12 @@ inline void ExtensionRangeOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); } void ExtensionRangeOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void ExtensionRangeOptions::Clear() { @@ -3230,8 +3362,8 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -3264,7 +3396,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -3297,7 +3429,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -3312,7 +3444,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.ExtensionRangeOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -3320,16 +3452,16 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData ExtensionRangeOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, ExtensionRangeOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*ExtensionRangeOptions::GetClassData() const { return &_class_data_; } @@ -3347,8 +3479,8 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -3360,20 +3492,20 @@ } bool ExtensionRangeOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void ExtensionRangeOptions::InternalSwap(ExtensionRangeOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); } ::PROTOBUF_NAMESPACE_ID::Metadata ExtensionRangeOptions::GetMetadata() const { @@ -3386,7 +3518,7 @@ class FieldDescriptorProto::_Internal { public: - using HasBits = decltype(std::declval<FieldDescriptorProto>()._has_bits_); + using HasBits = decltype(std::declval<FieldDescriptorProto>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -3425,96 +3557,120 @@ const ::PROTOBUF_NAMESPACE_ID::FieldOptions& FieldDescriptorProto::_Internal::options(const FieldDescriptorProto* msg) { - return *msg->options_; + return *msg->_impl_.options_; } FieldDescriptorProto::FieldDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldDescriptorProto) } FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.extendee_){} + , decltype(_impl_.type_name_){} + , decltype(_impl_.default_value_){} + , decltype(_impl_.json_name_){} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.number_){} + , decltype(_impl_.oneof_index_){} + , decltype(_impl_.proto3_optional_){} + , decltype(_impl_.label_){} + , decltype(_impl_.type_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - extendee_.InitDefault(); + _impl_.extendee_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - extendee_.Set("", GetArenaForAllocation()); + _impl_.extendee_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_extendee()) { - extendee_.Set(from._internal_extendee(), + _impl_.extendee_.Set(from._internal_extendee(), GetArenaForAllocation()); } - type_name_.InitDefault(); + _impl_.type_name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - type_name_.Set("", GetArenaForAllocation()); + _impl_.type_name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_type_name()) { - type_name_.Set(from._internal_type_name(), + _impl_.type_name_.Set(from._internal_type_name(), GetArenaForAllocation()); } - default_value_.InitDefault(); + _impl_.default_value_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - default_value_.Set("", GetArenaForAllocation()); + _impl_.default_value_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_default_value()) { - default_value_.Set(from._internal_default_value(), + _impl_.default_value_.Set(from._internal_default_value(), GetArenaForAllocation()); } - json_name_.InitDefault(); + _impl_.json_name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - json_name_.Set("", GetArenaForAllocation()); + _impl_.json_name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_json_name()) { - json_name_.Set(from._internal_json_name(), + _impl_.json_name_.Set(from._internal_json_name(), GetArenaForAllocation()); } if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::FieldOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::FieldOptions(*from._impl_.options_); } - ::memcpy(&number_, &from.number_, - static_cast<size_t>(reinterpret_cast<char*>(&type_) - - reinterpret_cast<char*>(&number_)) + sizeof(type_)); + ::memcpy(&_impl_.number_, &from._impl_.number_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.type_) - + reinterpret_cast<char*>(&_impl_.number_)) + sizeof(_impl_.type_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldDescriptorProto) } -inline void FieldDescriptorProto::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -extendee_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - extendee_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -type_name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - type_name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -default_value_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - default_value_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -json_name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - json_name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&options_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&proto3_optional_) - - reinterpret_cast<char*>(&options_)) + sizeof(proto3_optional_)); -label_ = 1; -type_ = 1; +inline void FieldDescriptorProto::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.extendee_){} + , decltype(_impl_.type_name_){} + , decltype(_impl_.default_value_){} + , decltype(_impl_.json_name_){} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.number_){0} + , decltype(_impl_.oneof_index_){0} + , decltype(_impl_.proto3_optional_){false} + , decltype(_impl_.label_){1} + , decltype(_impl_.type_){1} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.extendee_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.extendee_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.type_name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.type_name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.default_value_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.default_value_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.json_name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.json_name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } FieldDescriptorProto::~FieldDescriptorProto() { @@ -3528,16 +3684,16 @@ inline void FieldDescriptorProto::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - extendee_.Destroy(); - type_name_.Destroy(); - default_value_.Destroy(); - json_name_.Destroy(); - if (this != internal_default_instance()) delete options_; + _impl_.name_.Destroy(); + _impl_.extendee_.Destroy(); + _impl_.type_name_.Destroy(); + _impl_.default_value_.Destroy(); + _impl_.json_name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.options_; } void FieldDescriptorProto::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void FieldDescriptorProto::Clear() { @@ -3546,39 +3702,39 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - extendee_.ClearNonDefaultToEmpty(); + _impl_.extendee_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - type_name_.ClearNonDefaultToEmpty(); + _impl_.type_name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - default_value_.ClearNonDefaultToEmpty(); + _impl_.default_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { - json_name_.ClearNonDefaultToEmpty(); + _impl_.json_name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } } if (cached_has_bits & 0x000000c0u) { - ::memset(&number_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&oneof_index_) - - reinterpret_cast<char*>(&number_)) + sizeof(oneof_index_)); + ::memset(&_impl_.number_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.oneof_index_) - + reinterpret_cast<char*>(&_impl_.number_)) + sizeof(_impl_.oneof_index_)); } if (cached_has_bits & 0x00000700u) { - proto3_optional_ = false; - label_ = 1; - type_ = 1; + _impl_.proto3_optional_ = false; + _impl_.label_ = 1; + _impl_.type_ = 1; } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -3617,7 +3773,7 @@ case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) { _Internal::set_has_number(&has_bits); - number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -3684,7 +3840,7 @@ case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 72)) { _Internal::set_has_oneof_index(&has_bits); - oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -3705,7 +3861,7 @@ case 17: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 136)) { _Internal::set_has_proto3_optional(&has_bits); - proto3_optional_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.proto3_optional_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -3726,7 +3882,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -3740,7 +3896,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -3846,7 +4002,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -3887,7 +4043,7 @@ if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } // optional int32 number = 3; @@ -3920,11 +4076,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData FieldDescriptorProto::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, FieldDescriptorProto::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*FieldDescriptorProto::GetClassData() const { return &_class_data_; } @@ -3942,7 +4098,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -3963,24 +4119,24 @@ _internal_mutable_options()->::PROTOBUF_NAMESPACE_ID::FieldOptions::MergeFrom(from._internal_options()); } if (cached_has_bits & 0x00000040u) { - number_ = from.number_; + _impl_.number_ = from._impl_.number_; } if (cached_has_bits & 0x00000080u) { - oneof_index_ = from.oneof_index_; + _impl_.oneof_index_ = from._impl_.oneof_index_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 0x00000700u) { if (cached_has_bits & 0x00000100u) { - proto3_optional_ = from.proto3_optional_; + _impl_.proto3_optional_ = from._impl_.proto3_optional_; } if (cached_has_bits & 0x00000200u) { - label_ = from.label_; + _impl_.label_ = from._impl_.label_; } if (cached_has_bits & 0x00000400u) { - type_ = from.type_; + _impl_.type_ = from._impl_.type_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -3994,7 +4150,7 @@ bool FieldDescriptorProto::IsInitialized() const { if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -4004,35 +4160,35 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &extendee_, lhs_arena, - &other->extendee_, rhs_arena + &_impl_.extendee_, lhs_arena, + &other->_impl_.extendee_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &type_name_, lhs_arena, - &other->type_name_, rhs_arena + &_impl_.type_name_, lhs_arena, + &other->_impl_.type_name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &default_value_, lhs_arena, - &other->default_value_, rhs_arena + &_impl_.default_value_, lhs_arena, + &other->_impl_.default_value_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &json_name_, lhs_arena, - &other->json_name_, rhs_arena + &_impl_.json_name_, lhs_arena, + &other->_impl_.json_name_, rhs_arena ); ::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_); + PROTOBUF_FIELD_OFFSET(FieldDescriptorProto, _impl_.proto3_optional_) + + sizeof(FieldDescriptorProto::_impl_.proto3_optional_) + - PROTOBUF_FIELD_OFFSET(FieldDescriptorProto, _impl_.options_)>( + reinterpret_cast<char*>(&_impl_.options_), + reinterpret_cast<char*>(&other->_impl_.options_)); + swap(_impl_.label_, other->_impl_.label_); + swap(_impl_.type_, other->_impl_.type_); } ::PROTOBUF_NAMESPACE_ID::Metadata FieldDescriptorProto::GetMetadata() const { @@ -4045,7 +4201,7 @@ class OneofDescriptorProto::_Internal { public: - using HasBits = decltype(std::declval<OneofDescriptorProto>()._has_bits_); + using HasBits = decltype(std::declval<OneofDescriptorProto>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -4057,40 +4213,51 @@ const ::PROTOBUF_NAMESPACE_ID::OneofOptions& OneofDescriptorProto::_Internal::options(const OneofDescriptorProto* msg) { - return *msg->options_; + return *msg->_impl_.options_; } OneofDescriptorProto::OneofDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofDescriptorProto) } OneofDescriptorProto::OneofDescriptorProto(const OneofDescriptorProto& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::OneofOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::OneofOptions(*from._impl_.options_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.OneofDescriptorProto) } -inline void OneofDescriptorProto::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -options_ = nullptr; +inline void OneofDescriptorProto::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } OneofDescriptorProto::~OneofDescriptorProto() { @@ -4104,12 +4271,12 @@ inline void OneofDescriptorProto::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - if (this != internal_default_instance()) delete options_; + _impl_.name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.options_; } void OneofDescriptorProto::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void OneofDescriptorProto::Clear() { @@ -4118,17 +4285,17 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -4175,7 +4342,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -4189,7 +4356,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -4223,7 +4390,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -4236,15 +4403,15 @@ if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData OneofDescriptorProto::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, OneofDescriptorProto::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*OneofDescriptorProto::GetClassData() const { return &_class_data_; } @@ -4262,7 +4429,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -4283,7 +4450,7 @@ bool OneofDescriptorProto::IsInitialized() const { if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -4293,12 +4460,12 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); - swap(options_, other->options_); + swap(_impl_.options_, other->_impl_.options_); } ::PROTOBUF_NAMESPACE_ID::Metadata OneofDescriptorProto::GetMetadata() const { @@ -4311,7 +4478,7 @@ class EnumDescriptorProto_EnumReservedRange::_Internal { public: - using HasBits = decltype(std::declval<EnumDescriptorProto_EnumReservedRange>()._has_bits_); + using HasBits = decltype(std::declval<EnumDescriptorProto_EnumReservedRange>()._impl_._has_bits_); static void set_has_start(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -4323,24 +4490,34 @@ EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) } EnumDescriptorProto_EnumReservedRange::EnumDescriptorProto_EnumReservedRange(const EnumDescriptorProto_EnumReservedRange& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.start_){} + , decltype(_impl_.end_){}}; + _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_)); + ::memcpy(&_impl_.start_, &from._impl_.start_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.end_) - + reinterpret_cast<char*>(&_impl_.start_)) + sizeof(_impl_.end_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumDescriptorProto.EnumReservedRange) } -inline void EnumDescriptorProto_EnumReservedRange::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&start_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&start_)) + sizeof(end_)); +inline void EnumDescriptorProto_EnumReservedRange::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.start_){0} + , decltype(_impl_.end_){0} + }; } EnumDescriptorProto_EnumReservedRange::~EnumDescriptorProto_EnumReservedRange() { @@ -4357,7 +4534,7 @@ } void EnumDescriptorProto_EnumReservedRange::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void EnumDescriptorProto_EnumReservedRange::Clear() { @@ -4366,13 +4543,13 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { - ::memset(&start_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&start_)) + sizeof(end_)); + ::memset(&_impl_.start_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.end_) - + reinterpret_cast<char*>(&_impl_.start_)) + sizeof(_impl_.end_)); } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -4387,7 +4564,7 @@ case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { _Internal::set_has_start(&has_bits); - start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.start_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -4396,7 +4573,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_end(&has_bits); - end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -4417,7 +4594,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -4431,7 +4608,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional int32 start = 1; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); @@ -4460,7 +4637,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional int32 start = 1; if (cached_has_bits & 0x00000001u) { @@ -4473,11 +4650,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData EnumDescriptorProto_EnumReservedRange::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, EnumDescriptorProto_EnumReservedRange::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*EnumDescriptorProto_EnumReservedRange::GetClassData() const { return &_class_data_; } @@ -4495,15 +4672,15 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - start_ = from.start_; + _impl_.start_ = from._impl_.start_; } if (cached_has_bits & 0x00000002u) { - end_ = from.end_; + _impl_.end_ = from._impl_.end_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -4522,13 +4699,13 @@ void EnumDescriptorProto_EnumReservedRange::InternalSwap(EnumDescriptorProto_EnumReservedRange* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::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_FIELD_OFFSET(EnumDescriptorProto_EnumReservedRange, _impl_.end_) + + sizeof(EnumDescriptorProto_EnumReservedRange::_impl_.end_) + - PROTOBUF_FIELD_OFFSET(EnumDescriptorProto_EnumReservedRange, _impl_.start_)>( + reinterpret_cast<char*>(&_impl_.start_), + reinterpret_cast<char*>(&other->_impl_.start_)); } ::PROTOBUF_NAMESPACE_ID::Metadata EnumDescriptorProto_EnumReservedRange::GetMetadata() const { @@ -4541,7 +4718,7 @@ class EnumDescriptorProto::_Internal { public: - using HasBits = decltype(std::declval<EnumDescriptorProto>()._has_bits_); + using HasBits = decltype(std::declval<EnumDescriptorProto>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -4553,46 +4730,57 @@ const ::PROTOBUF_NAMESPACE_ID::EnumOptions& EnumDescriptorProto::_Internal::options(const EnumDescriptorProto* msg) { - return *msg->options_; + return *msg->_impl_.options_; } EnumDescriptorProto::EnumDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - value_(arena), - reserved_range_(arena), - reserved_name_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumDescriptorProto) } EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - value_(from.value_), - reserved_range_(from.reserved_range_), - reserved_name_(from.reserved_name_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.value_){from._impl_.value_} + , decltype(_impl_.reserved_range_){from._impl_.reserved_range_} + , decltype(_impl_.reserved_name_){from._impl_.reserved_name_} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::EnumOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::EnumOptions(*from._impl_.options_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumDescriptorProto) } -inline void EnumDescriptorProto::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -options_ = nullptr; +inline void EnumDescriptorProto::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.value_){arena} + , decltype(_impl_.reserved_range_){arena} + , decltype(_impl_.reserved_name_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } EnumDescriptorProto::~EnumDescriptorProto() { @@ -4606,12 +4794,15 @@ inline void EnumDescriptorProto::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - if (this != internal_default_instance()) delete options_; + _impl_.value_.~RepeatedPtrField(); + _impl_.reserved_range_.~RepeatedPtrField(); + _impl_.reserved_name_.~RepeatedPtrField(); + _impl_.name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.options_; } void EnumDescriptorProto::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void EnumDescriptorProto::Clear() { @@ -4620,20 +4811,20 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_.Clear(); - reserved_range_.Clear(); - reserved_name_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.value_.Clear(); + _impl_.reserved_range_.Clear(); + _impl_.reserved_name_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -4723,7 +4914,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -4737,7 +4928,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -4799,27 +4990,27 @@ // repeated .google.protobuf.EnumValueDescriptorProto value = 2; total_size += 1UL * this->_internal_value_size(); - for (const auto& msg : this->value_) { + for (const auto& msg : this->_impl_.value_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; total_size += 1UL * this->_internal_reserved_range_size(); - for (const auto& msg : this->reserved_range_) { + for (const auto& msg : this->_impl_.reserved_range_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated string reserved_name = 5; total_size += 1 * - ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(reserved_name_.size()); - for (int i = 0, n = reserved_name_.size(); i < n; i++) { + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(_impl_.reserved_name_.size()); + for (int i = 0, n = _impl_.reserved_name_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( - reserved_name_.Get(i)); + _impl_.reserved_name_.Get(i)); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -4832,15 +5023,15 @@ if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData EnumDescriptorProto::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, EnumDescriptorProto::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*EnumDescriptorProto::GetClassData() const { return &_class_data_; } @@ -4858,10 +5049,10 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - value_.MergeFrom(from.value_); - reserved_range_.MergeFrom(from.reserved_range_); - reserved_name_.MergeFrom(from.reserved_name_); - cached_has_bits = from._has_bits_[0]; + _impl_.value_.MergeFrom(from._impl_.value_); + _impl_.reserved_range_.MergeFrom(from._impl_.reserved_range_); + _impl_.reserved_name_.MergeFrom(from._impl_.reserved_name_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -4881,10 +5072,10 @@ } bool EnumDescriptorProto::IsInitialized() const { - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(value_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.value_)) return false; if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -4894,15 +5085,15 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&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_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.value_.InternalSwap(&other->_impl_.value_); + _impl_.reserved_range_.InternalSwap(&other->_impl_.reserved_range_); + _impl_.reserved_name_.InternalSwap(&other->_impl_.reserved_name_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); - swap(options_, other->options_); + swap(_impl_.options_, other->_impl_.options_); } ::PROTOBUF_NAMESPACE_ID::Metadata EnumDescriptorProto::GetMetadata() const { @@ -4915,7 +5106,7 @@ class EnumValueDescriptorProto::_Internal { public: - using HasBits = decltype(std::declval<EnumValueDescriptorProto>()._has_bits_); + using HasBits = decltype(std::declval<EnumValueDescriptorProto>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -4930,44 +5121,54 @@ const ::PROTOBUF_NAMESPACE_ID::EnumValueOptions& EnumValueDescriptorProto::_Internal::options(const EnumValueDescriptorProto* msg) { - return *msg->options_; + return *msg->_impl_.options_; } EnumValueDescriptorProto::EnumValueDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueDescriptorProto) } EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.number_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::EnumValueOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::EnumValueOptions(*from._impl_.options_); } - number_ = from.number_; + _impl_.number_ = from._impl_.number_; // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValueDescriptorProto) } -inline void EnumValueDescriptorProto::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&options_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&number_) - - reinterpret_cast<char*>(&options_)) + sizeof(number_)); +inline void EnumValueDescriptorProto::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.number_){0} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } EnumValueDescriptorProto::~EnumValueDescriptorProto() { @@ -4981,12 +5182,12 @@ inline void EnumValueDescriptorProto::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - if (this != internal_default_instance()) delete options_; + _impl_.name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.options_; } void EnumValueDescriptorProto::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void EnumValueDescriptorProto::Clear() { @@ -4995,18 +5196,18 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } } - number_ = 0; - _has_bits_.Clear(); + _impl_.number_ = 0; + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -5033,7 +5234,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_number(&has_bits); - number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -5062,7 +5263,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -5076,7 +5277,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -5116,7 +5317,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000007u) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -5129,7 +5330,7 @@ if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } // optional int32 number = 2; @@ -5138,11 +5339,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData EnumValueDescriptorProto::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, EnumValueDescriptorProto::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*EnumValueDescriptorProto::GetClassData() const { return &_class_data_; } @@ -5160,7 +5361,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -5169,9 +5370,9 @@ _internal_mutable_options()->::PROTOBUF_NAMESPACE_ID::EnumValueOptions::MergeFrom(from._internal_options()); } if (cached_has_bits & 0x00000004u) { - number_ = from.number_; + _impl_.number_ = from._impl_.number_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -5185,7 +5386,7 @@ bool EnumValueDescriptorProto::IsInitialized() const { if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -5195,17 +5396,17 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::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_FIELD_OFFSET(EnumValueDescriptorProto, _impl_.number_) + + sizeof(EnumValueDescriptorProto::_impl_.number_) + - PROTOBUF_FIELD_OFFSET(EnumValueDescriptorProto, _impl_.options_)>( + reinterpret_cast<char*>(&_impl_.options_), + reinterpret_cast<char*>(&other->_impl_.options_)); } ::PROTOBUF_NAMESPACE_ID::Metadata EnumValueDescriptorProto::GetMetadata() const { @@ -5218,7 +5419,7 @@ class ServiceDescriptorProto::_Internal { public: - using HasBits = decltype(std::declval<ServiceDescriptorProto>()._has_bits_); + using HasBits = decltype(std::declval<ServiceDescriptorProto>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -5230,42 +5431,53 @@ const ::PROTOBUF_NAMESPACE_ID::ServiceOptions& ServiceDescriptorProto::_Internal::options(const ServiceDescriptorProto* msg) { - return *msg->options_; + return *msg->_impl_.options_; } ServiceDescriptorProto::ServiceDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - method_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceDescriptorProto) } ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - method_(from.method_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.method_){from._impl_.method_} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::ServiceOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::ServiceOptions(*from._impl_.options_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.ServiceDescriptorProto) } -inline void ServiceDescriptorProto::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -options_ = nullptr; +inline void ServiceDescriptorProto::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.method_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.options_){nullptr} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } ServiceDescriptorProto::~ServiceDescriptorProto() { @@ -5279,12 +5491,13 @@ inline void ServiceDescriptorProto::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - if (this != internal_default_instance()) delete options_; + _impl_.method_.~RepeatedPtrField(); + _impl_.name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.options_; } void ServiceDescriptorProto::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void ServiceDescriptorProto::Clear() { @@ -5293,18 +5506,18 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - method_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.method_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -5364,7 +5577,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -5378,7 +5591,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -5422,12 +5635,12 @@ // repeated .google.protobuf.MethodDescriptorProto method = 2; total_size += 1UL * this->_internal_method_size(); - for (const auto& msg : this->method_) { + for (const auto& msg : this->_impl_.method_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -5440,15 +5653,15 @@ if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData ServiceDescriptorProto::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, ServiceDescriptorProto::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*ServiceDescriptorProto::GetClassData() const { return &_class_data_; } @@ -5466,8 +5679,8 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - method_.MergeFrom(from.method_); - cached_has_bits = from._has_bits_[0]; + _impl_.method_.MergeFrom(from._impl_.method_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -5487,10 +5700,10 @@ } bool ServiceDescriptorProto::IsInitialized() const { - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(method_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.method_)) return false; if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -5500,13 +5713,13 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - method_.InternalSwap(&other->method_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.method_.InternalSwap(&other->_impl_.method_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); - swap(options_, other->options_); + swap(_impl_.options_, other->_impl_.options_); } ::PROTOBUF_NAMESPACE_ID::Metadata ServiceDescriptorProto::GetMetadata() const { @@ -5519,7 +5732,7 @@ class MethodDescriptorProto::_Internal { public: - using HasBits = decltype(std::declval<MethodDescriptorProto>()._has_bits_); + using HasBits = decltype(std::declval<MethodDescriptorProto>()._impl_._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -5543,70 +5756,86 @@ const ::PROTOBUF_NAMESPACE_ID::MethodOptions& MethodDescriptorProto::_Internal::options(const MethodDescriptorProto* msg) { - return *msg->options_; + return *msg->_impl_.options_; } MethodDescriptorProto::MethodDescriptorProto(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodDescriptorProto) } MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.input_type_){} + , decltype(_impl_.output_type_){} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.client_streaming_){} + , decltype(_impl_.server_streaming_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - input_type_.InitDefault(); + _impl_.input_type_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - input_type_.Set("", GetArenaForAllocation()); + _impl_.input_type_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_input_type()) { - input_type_.Set(from._internal_input_type(), + _impl_.input_type_.Set(from._internal_input_type(), GetArenaForAllocation()); } - output_type_.InitDefault(); + _impl_.output_type_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - output_type_.Set("", GetArenaForAllocation()); + _impl_.output_type_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_output_type()) { - output_type_.Set(from._internal_output_type(), + _impl_.output_type_.Set(from._internal_output_type(), GetArenaForAllocation()); } if (from._internal_has_options()) { - options_ = new ::PROTOBUF_NAMESPACE_ID::MethodOptions(*from.options_); - } else { - options_ = nullptr; + _impl_.options_ = new ::PROTOBUF_NAMESPACE_ID::MethodOptions(*from._impl_.options_); } - ::memcpy(&client_streaming_, &from.client_streaming_, - static_cast<size_t>(reinterpret_cast<char*>(&server_streaming_) - - reinterpret_cast<char*>(&client_streaming_)) + sizeof(server_streaming_)); + ::memcpy(&_impl_.client_streaming_, &from._impl_.client_streaming_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.server_streaming_) - + reinterpret_cast<char*>(&_impl_.client_streaming_)) + sizeof(_impl_.server_streaming_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.MethodDescriptorProto) } -inline void MethodDescriptorProto::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -input_type_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - input_type_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -output_type_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - output_type_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&options_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&server_streaming_) - - reinterpret_cast<char*>(&options_)) + sizeof(server_streaming_)); +inline void MethodDescriptorProto::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){} + , decltype(_impl_.input_type_){} + , decltype(_impl_.output_type_){} + , decltype(_impl_.options_){nullptr} + , decltype(_impl_.client_streaming_){false} + , decltype(_impl_.server_streaming_){false} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.input_type_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.input_type_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.output_type_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.output_type_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } MethodDescriptorProto::~MethodDescriptorProto() { @@ -5620,14 +5849,14 @@ inline void MethodDescriptorProto::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - input_type_.Destroy(); - output_type_.Destroy(); - if (this != internal_default_instance()) delete options_; + _impl_.name_.Destroy(); + _impl_.input_type_.Destroy(); + _impl_.output_type_.Destroy(); + if (this != internal_default_instance()) delete _impl_.options_; } void MethodDescriptorProto::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void MethodDescriptorProto::Clear() { @@ -5636,26 +5865,26 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { - name_.ClearNonDefaultToEmpty(); + _impl_.name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - input_type_.ClearNonDefaultToEmpty(); + _impl_.input_type_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - output_type_.ClearNonDefaultToEmpty(); + _impl_.output_type_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - GOOGLE_DCHECK(options_ != nullptr); - options_->Clear(); + GOOGLE_DCHECK(_impl_.options_ != nullptr); + _impl_.options_->Clear(); } } - ::memset(&client_streaming_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&server_streaming_) - - reinterpret_cast<char*>(&client_streaming_)) + sizeof(server_streaming_)); - _has_bits_.Clear(); + ::memset(&_impl_.client_streaming_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.server_streaming_) - + reinterpret_cast<char*>(&_impl_.client_streaming_)) + sizeof(_impl_.server_streaming_)); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -5714,7 +5943,7 @@ case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 40)) { _Internal::set_has_client_streaming(&has_bits); - client_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.client_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -5723,7 +5952,7 @@ case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 48)) { _Internal::set_has_server_streaming(&has_bits); - server_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.server_streaming_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -5744,7 +5973,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -5758,7 +5987,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string name = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -5824,7 +6053,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { // optional string name = 1; if (cached_has_bits & 0x00000001u) { @@ -5851,7 +6080,7 @@ if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *options_); + *_impl_.options_); } // optional bool client_streaming = 5 [default = false]; @@ -5865,11 +6094,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData MethodDescriptorProto::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, MethodDescriptorProto::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*MethodDescriptorProto::GetClassData() const { return &_class_data_; } @@ -5887,7 +6116,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); @@ -5902,12 +6131,12 @@ _internal_mutable_options()->::PROTOBUF_NAMESPACE_ID::MethodOptions::MergeFrom(from._internal_options()); } if (cached_has_bits & 0x00000010u) { - client_streaming_ = from.client_streaming_; + _impl_.client_streaming_ = from._impl_.client_streaming_; } if (cached_has_bits & 0x00000020u) { - server_streaming_ = from.server_streaming_; + _impl_.server_streaming_ = from._impl_.server_streaming_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -5921,7 +6150,7 @@ bool MethodDescriptorProto::IsInitialized() const { if (_internal_has_options()) { - if (!options_->IsInitialized()) return false; + if (!_impl_.options_->IsInitialized()) return false; } return true; } @@ -5931,25 +6160,25 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &input_type_, lhs_arena, - &other->input_type_, rhs_arena + &_impl_.input_type_, lhs_arena, + &other->_impl_.input_type_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &output_type_, lhs_arena, - &other->output_type_, rhs_arena + &_impl_.output_type_, lhs_arena, + &other->_impl_.output_type_, rhs_arena ); ::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_FIELD_OFFSET(MethodDescriptorProto, _impl_.server_streaming_) + + sizeof(MethodDescriptorProto::_impl_.server_streaming_) + - PROTOBUF_FIELD_OFFSET(MethodDescriptorProto, _impl_.options_)>( + reinterpret_cast<char*>(&_impl_.options_), + reinterpret_cast<char*>(&other->_impl_.options_)); } ::PROTOBUF_NAMESPACE_ID::Metadata MethodDescriptorProto::GetMetadata() const { @@ -5962,7 +6191,7 @@ class FileOptions::_Internal { public: - using HasBits = decltype(std::declval<FileOptions>()._has_bits_); + using HasBits = decltype(std::declval<FileOptions>()._impl_._has_bits_); static void set_has_java_package(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -6027,151 +6256,196 @@ FileOptions::FileOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.FileOptions) } FileOptions::FileOptions(const FileOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , decltype(_impl_.java_package_){} + , decltype(_impl_.java_outer_classname_){} + , decltype(_impl_.go_package_){} + , decltype(_impl_.objc_class_prefix_){} + , decltype(_impl_.csharp_namespace_){} + , decltype(_impl_.swift_prefix_){} + , decltype(_impl_.php_class_prefix_){} + , decltype(_impl_.php_namespace_){} + , decltype(_impl_.php_metadata_namespace_){} + , decltype(_impl_.ruby_package_){} + , decltype(_impl_.java_multiple_files_){} + , decltype(_impl_.java_generate_equals_and_hash_){} + , decltype(_impl_.java_string_check_utf8_){} + , decltype(_impl_.cc_generic_services_){} + , decltype(_impl_.java_generic_services_){} + , decltype(_impl_.py_generic_services_){} + , decltype(_impl_.php_generic_services_){} + , decltype(_impl_.deprecated_){} + , decltype(_impl_.optimize_for_){} + , decltype(_impl_.cc_enable_arenas_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); - java_package_.InitDefault(); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); + _impl_.java_package_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - java_package_.Set("", GetArenaForAllocation()); + _impl_.java_package_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_java_package()) { - java_package_.Set(from._internal_java_package(), + _impl_.java_package_.Set(from._internal_java_package(), GetArenaForAllocation()); } - java_outer_classname_.InitDefault(); + _impl_.java_outer_classname_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - java_outer_classname_.Set("", GetArenaForAllocation()); + _impl_.java_outer_classname_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_java_outer_classname()) { - java_outer_classname_.Set(from._internal_java_outer_classname(), + _impl_.java_outer_classname_.Set(from._internal_java_outer_classname(), GetArenaForAllocation()); } - go_package_.InitDefault(); + _impl_.go_package_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - go_package_.Set("", GetArenaForAllocation()); + _impl_.go_package_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_go_package()) { - go_package_.Set(from._internal_go_package(), + _impl_.go_package_.Set(from._internal_go_package(), GetArenaForAllocation()); } - objc_class_prefix_.InitDefault(); + _impl_.objc_class_prefix_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - objc_class_prefix_.Set("", GetArenaForAllocation()); + _impl_.objc_class_prefix_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_objc_class_prefix()) { - objc_class_prefix_.Set(from._internal_objc_class_prefix(), + _impl_.objc_class_prefix_.Set(from._internal_objc_class_prefix(), GetArenaForAllocation()); } - csharp_namespace_.InitDefault(); + _impl_.csharp_namespace_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - csharp_namespace_.Set("", GetArenaForAllocation()); + _impl_.csharp_namespace_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_csharp_namespace()) { - csharp_namespace_.Set(from._internal_csharp_namespace(), + _impl_.csharp_namespace_.Set(from._internal_csharp_namespace(), GetArenaForAllocation()); } - swift_prefix_.InitDefault(); + _impl_.swift_prefix_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - swift_prefix_.Set("", GetArenaForAllocation()); + _impl_.swift_prefix_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_swift_prefix()) { - swift_prefix_.Set(from._internal_swift_prefix(), + _impl_.swift_prefix_.Set(from._internal_swift_prefix(), GetArenaForAllocation()); } - php_class_prefix_.InitDefault(); + _impl_.php_class_prefix_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - php_class_prefix_.Set("", GetArenaForAllocation()); + _impl_.php_class_prefix_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_php_class_prefix()) { - php_class_prefix_.Set(from._internal_php_class_prefix(), + _impl_.php_class_prefix_.Set(from._internal_php_class_prefix(), GetArenaForAllocation()); } - php_namespace_.InitDefault(); + _impl_.php_namespace_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - php_namespace_.Set("", GetArenaForAllocation()); + _impl_.php_namespace_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_php_namespace()) { - php_namespace_.Set(from._internal_php_namespace(), + _impl_.php_namespace_.Set(from._internal_php_namespace(), GetArenaForAllocation()); } - php_metadata_namespace_.InitDefault(); + _impl_.php_metadata_namespace_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - php_metadata_namespace_.Set("", GetArenaForAllocation()); + _impl_.php_metadata_namespace_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_php_metadata_namespace()) { - php_metadata_namespace_.Set(from._internal_php_metadata_namespace(), + _impl_.php_metadata_namespace_.Set(from._internal_php_metadata_namespace(), GetArenaForAllocation()); } - ruby_package_.InitDefault(); + _impl_.ruby_package_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - ruby_package_.Set("", GetArenaForAllocation()); + _impl_.ruby_package_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_ruby_package()) { - ruby_package_.Set(from._internal_ruby_package(), + _impl_.ruby_package_.Set(from._internal_ruby_package(), GetArenaForAllocation()); } - ::memcpy(&java_multiple_files_, &from.java_multiple_files_, - static_cast<size_t>(reinterpret_cast<char*>(&cc_enable_arenas_) - - reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(cc_enable_arenas_)); + ::memcpy(&_impl_.java_multiple_files_, &from._impl_.java_multiple_files_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.cc_enable_arenas_) - + reinterpret_cast<char*>(&_impl_.java_multiple_files_)) + sizeof(_impl_.cc_enable_arenas_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.FileOptions) } -inline void FileOptions::SharedCtor() { -java_package_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - java_package_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -java_outer_classname_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - java_outer_classname_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -go_package_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - go_package_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -objc_class_prefix_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - objc_class_prefix_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -csharp_namespace_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - csharp_namespace_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -swift_prefix_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - swift_prefix_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -php_class_prefix_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - php_class_prefix_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -php_namespace_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - php_namespace_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -php_metadata_namespace_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - php_metadata_namespace_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -ruby_package_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - ruby_package_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&java_multiple_files_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&deprecated_) - - reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(deprecated_)); -optimize_for_ = 1; -cc_enable_arenas_ = true; +inline void FileOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){arena} + , decltype(_impl_.java_package_){} + , decltype(_impl_.java_outer_classname_){} + , decltype(_impl_.go_package_){} + , decltype(_impl_.objc_class_prefix_){} + , decltype(_impl_.csharp_namespace_){} + , decltype(_impl_.swift_prefix_){} + , decltype(_impl_.php_class_prefix_){} + , decltype(_impl_.php_namespace_){} + , decltype(_impl_.php_metadata_namespace_){} + , decltype(_impl_.ruby_package_){} + , decltype(_impl_.java_multiple_files_){false} + , decltype(_impl_.java_generate_equals_and_hash_){false} + , decltype(_impl_.java_string_check_utf8_){false} + , decltype(_impl_.cc_generic_services_){false} + , decltype(_impl_.java_generic_services_){false} + , decltype(_impl_.py_generic_services_){false} + , decltype(_impl_.php_generic_services_){false} + , decltype(_impl_.deprecated_){false} + , decltype(_impl_.optimize_for_){1} + , decltype(_impl_.cc_enable_arenas_){true} + }; + _impl_.java_package_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.java_package_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.java_outer_classname_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.java_outer_classname_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.go_package_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.go_package_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.objc_class_prefix_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.objc_class_prefix_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.csharp_namespace_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.csharp_namespace_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.swift_prefix_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.swift_prefix_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.php_class_prefix_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.php_class_prefix_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.php_namespace_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.php_namespace_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.php_metadata_namespace_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.php_metadata_namespace_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.ruby_package_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.ruby_package_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } FileOptions::~FileOptions() { @@ -6185,20 +6459,22 @@ inline void FileOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - java_package_.Destroy(); - java_outer_classname_.Destroy(); - go_package_.Destroy(); - objc_class_prefix_.Destroy(); - csharp_namespace_.Destroy(); - swift_prefix_.Destroy(); - php_class_prefix_.Destroy(); - php_namespace_.Destroy(); - php_metadata_namespace_.Destroy(); - ruby_package_.Destroy(); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); + _impl_.java_package_.Destroy(); + _impl_.java_outer_classname_.Destroy(); + _impl_.go_package_.Destroy(); + _impl_.objc_class_prefix_.Destroy(); + _impl_.csharp_namespace_.Destroy(); + _impl_.swift_prefix_.Destroy(); + _impl_.php_class_prefix_.Destroy(); + _impl_.php_namespace_.Destroy(); + _impl_.php_metadata_namespace_.Destroy(); + _impl_.ruby_package_.Destroy(); } void FileOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void FileOptions::Clear() { @@ -6207,56 +6483,56 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { - java_package_.ClearNonDefaultToEmpty(); + _impl_.java_package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - java_outer_classname_.ClearNonDefaultToEmpty(); + _impl_.java_outer_classname_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - go_package_.ClearNonDefaultToEmpty(); + _impl_.go_package_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { - objc_class_prefix_.ClearNonDefaultToEmpty(); + _impl_.objc_class_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { - csharp_namespace_.ClearNonDefaultToEmpty(); + _impl_.csharp_namespace_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000020u) { - swift_prefix_.ClearNonDefaultToEmpty(); + _impl_.swift_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000040u) { - php_class_prefix_.ClearNonDefaultToEmpty(); + _impl_.php_class_prefix_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000080u) { - php_namespace_.ClearNonDefaultToEmpty(); + _impl_.php_namespace_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 0x00000300u) { if (cached_has_bits & 0x00000100u) { - php_metadata_namespace_.ClearNonDefaultToEmpty(); + _impl_.php_metadata_namespace_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000200u) { - ruby_package_.ClearNonDefaultToEmpty(); + _impl_.ruby_package_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 0x0000fc00u) { - ::memset(&java_multiple_files_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&py_generic_services_) - - reinterpret_cast<char*>(&java_multiple_files_)) + sizeof(py_generic_services_)); + ::memset(&_impl_.java_multiple_files_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.py_generic_services_) - + reinterpret_cast<char*>(&_impl_.java_multiple_files_)) + sizeof(_impl_.py_generic_services_)); } if (cached_has_bits & 0x000f0000u) { - ::memset(&php_generic_services_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&deprecated_) - - reinterpret_cast<char*>(&php_generic_services_)) + sizeof(deprecated_)); - optimize_for_ = 1; - cc_enable_arenas_ = true; + ::memset(&_impl_.php_generic_services_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.deprecated_) - + reinterpret_cast<char*>(&_impl_.php_generic_services_)) + sizeof(_impl_.deprecated_)); + _impl_.optimize_for_ = 1; + _impl_.cc_enable_arenas_ = true; } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -6308,7 +6584,7 @@ case 10: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 80)) { _Internal::set_has_java_multiple_files(&has_bits); - java_multiple_files_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.java_multiple_files_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6329,7 +6605,7 @@ case 16: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 128)) { _Internal::set_has_cc_generic_services(&has_bits); - cc_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.cc_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6338,7 +6614,7 @@ case 17: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 136)) { _Internal::set_has_java_generic_services(&has_bits); - java_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.java_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6347,7 +6623,7 @@ case 18: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 144)) { _Internal::set_has_py_generic_services(&has_bits); - py_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.py_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6356,7 +6632,7 @@ case 20: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 160)) { _Internal::set_has_java_generate_equals_and_hash(&has_bits); - java_generate_equals_and_hash_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.java_generate_equals_and_hash_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6365,7 +6641,7 @@ case 23: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 184)) { _Internal::set_has_deprecated(&has_bits); - deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6374,7 +6650,7 @@ case 27: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 216)) { _Internal::set_has_java_string_check_utf8(&has_bits); - java_string_check_utf8_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.java_string_check_utf8_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6383,7 +6659,7 @@ case 31: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 248)) { _Internal::set_has_cc_enable_arenas(&has_bits); - cc_enable_arenas_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.cc_enable_arenas_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6452,7 +6728,7 @@ case 42: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 80)) { _Internal::set_has_php_generic_services(&has_bits); - php_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.php_generic_services_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -6504,7 +6780,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -6515,7 +6791,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -6529,7 +6805,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string java_package = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -6700,7 +6976,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -6715,7 +6991,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.FileOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -6723,12 +6999,12 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { // optional string java_package = 1; if (cached_has_bits & 0x00000001u) { @@ -6856,11 +7132,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData FileOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, FileOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*FileOptions::GetClassData() const { return &_class_data_; } @@ -6878,8 +7154,8 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - cached_has_bits = from._has_bits_[0]; + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_java_package(from._internal_java_package()); @@ -6914,41 +7190,41 @@ _internal_set_ruby_package(from._internal_ruby_package()); } if (cached_has_bits & 0x00000400u) { - java_multiple_files_ = from.java_multiple_files_; + _impl_.java_multiple_files_ = from._impl_.java_multiple_files_; } if (cached_has_bits & 0x00000800u) { - java_generate_equals_and_hash_ = from.java_generate_equals_and_hash_; + _impl_.java_generate_equals_and_hash_ = from._impl_.java_generate_equals_and_hash_; } if (cached_has_bits & 0x00001000u) { - java_string_check_utf8_ = from.java_string_check_utf8_; + _impl_.java_string_check_utf8_ = from._impl_.java_string_check_utf8_; } if (cached_has_bits & 0x00002000u) { - cc_generic_services_ = from.cc_generic_services_; + _impl_.cc_generic_services_ = from._impl_.cc_generic_services_; } if (cached_has_bits & 0x00004000u) { - java_generic_services_ = from.java_generic_services_; + _impl_.java_generic_services_ = from._impl_.java_generic_services_; } if (cached_has_bits & 0x00008000u) { - py_generic_services_ = from.py_generic_services_; + _impl_.py_generic_services_ = from._impl_.py_generic_services_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 0x000f0000u) { if (cached_has_bits & 0x00010000u) { - php_generic_services_ = from.php_generic_services_; + _impl_.php_generic_services_ = from._impl_.php_generic_services_; } if (cached_has_bits & 0x00020000u) { - deprecated_ = from.deprecated_; + _impl_.deprecated_ = from._impl_.deprecated_; } if (cached_has_bits & 0x00040000u) { - optimize_for_ = from.optimize_for_; + _impl_.optimize_for_ = from._impl_.optimize_for_; } if (cached_has_bits & 0x00080000u) { - cc_enable_arenas_ = from.cc_enable_arenas_; + _impl_.cc_enable_arenas_ = from._impl_.cc_enable_arenas_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -6960,71 +7236,71 @@ } bool FileOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void FileOptions::InternalSwap(FileOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &java_package_, lhs_arena, - &other->java_package_, rhs_arena + &_impl_.java_package_, lhs_arena, + &other->_impl_.java_package_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &java_outer_classname_, lhs_arena, - &other->java_outer_classname_, rhs_arena + &_impl_.java_outer_classname_, lhs_arena, + &other->_impl_.java_outer_classname_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &go_package_, lhs_arena, - &other->go_package_, rhs_arena + &_impl_.go_package_, lhs_arena, + &other->_impl_.go_package_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &objc_class_prefix_, lhs_arena, - &other->objc_class_prefix_, rhs_arena + &_impl_.objc_class_prefix_, lhs_arena, + &other->_impl_.objc_class_prefix_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &csharp_namespace_, lhs_arena, - &other->csharp_namespace_, rhs_arena + &_impl_.csharp_namespace_, lhs_arena, + &other->_impl_.csharp_namespace_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &swift_prefix_, lhs_arena, - &other->swift_prefix_, rhs_arena + &_impl_.swift_prefix_, lhs_arena, + &other->_impl_.swift_prefix_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &php_class_prefix_, lhs_arena, - &other->php_class_prefix_, rhs_arena + &_impl_.php_class_prefix_, lhs_arena, + &other->_impl_.php_class_prefix_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &php_namespace_, lhs_arena, - &other->php_namespace_, rhs_arena + &_impl_.php_namespace_, lhs_arena, + &other->_impl_.php_namespace_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &php_metadata_namespace_, lhs_arena, - &other->php_metadata_namespace_, rhs_arena + &_impl_.php_metadata_namespace_, lhs_arena, + &other->_impl_.php_metadata_namespace_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &ruby_package_, lhs_arena, - &other->ruby_package_, rhs_arena + &_impl_.ruby_package_, lhs_arena, + &other->_impl_.ruby_package_, rhs_arena ); ::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_FIELD_OFFSET(FileOptions, _impl_.deprecated_) + + sizeof(FileOptions::_impl_.deprecated_) + - PROTOBUF_FIELD_OFFSET(FileOptions, _impl_.java_multiple_files_)>( + reinterpret_cast<char*>(&_impl_.java_multiple_files_), + reinterpret_cast<char*>(&other->_impl_.java_multiple_files_)); + swap(_impl_.optimize_for_, other->_impl_.optimize_for_); + swap(_impl_.cc_enable_arenas_, other->_impl_.cc_enable_arenas_); } ::PROTOBUF_NAMESPACE_ID::Metadata FileOptions::GetMetadata() const { @@ -7037,7 +7313,7 @@ class MessageOptions::_Internal { public: - using HasBits = decltype(std::declval<MessageOptions>()._has_bits_); + using HasBits = decltype(std::declval<MessageOptions>()._impl_._has_bits_); static void set_has_message_set_wire_format(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -7054,29 +7330,44 @@ MessageOptions::MessageOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.MessageOptions) } MessageOptions::MessageOptions(const MessageOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , decltype(_impl_.message_set_wire_format_){} + , decltype(_impl_.no_standard_descriptor_accessor_){} + , decltype(_impl_.deprecated_){} + , decltype(_impl_.map_entry_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); - ::memcpy(&message_set_wire_format_, &from.message_set_wire_format_, - static_cast<size_t>(reinterpret_cast<char*>(&map_entry_) - - reinterpret_cast<char*>(&message_set_wire_format_)) + sizeof(map_entry_)); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); + ::memcpy(&_impl_.message_set_wire_format_, &from._impl_.message_set_wire_format_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.map_entry_) - + reinterpret_cast<char*>(&_impl_.message_set_wire_format_)) + sizeof(_impl_.map_entry_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.MessageOptions) } -inline void MessageOptions::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&message_set_wire_format_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&map_entry_) - - reinterpret_cast<char*>(&message_set_wire_format_)) + sizeof(map_entry_)); +inline void MessageOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){arena} + , decltype(_impl_.message_set_wire_format_){false} + , decltype(_impl_.no_standard_descriptor_accessor_){false} + , decltype(_impl_.deprecated_){false} + , decltype(_impl_.map_entry_){false} + }; } MessageOptions::~MessageOptions() { @@ -7090,10 +7381,12 @@ inline void MessageOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); } void MessageOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void MessageOptions::Clear() { @@ -7102,12 +7395,12 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); - ::memset(&message_set_wire_format_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&map_entry_) - - reinterpret_cast<char*>(&message_set_wire_format_)) + sizeof(map_entry_)); - _has_bits_.Clear(); + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); + ::memset(&_impl_.message_set_wire_format_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.map_entry_) - + reinterpret_cast<char*>(&_impl_.message_set_wire_format_)) + sizeof(_impl_.map_entry_)); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -7122,7 +7415,7 @@ case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { _Internal::set_has_message_set_wire_format(&has_bits); - message_set_wire_format_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.message_set_wire_format_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7131,7 +7424,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_no_standard_descriptor_accessor(&has_bits); - no_standard_descriptor_accessor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.no_standard_descriptor_accessor_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7140,7 +7433,7 @@ case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) { _Internal::set_has_deprecated(&has_bits); - deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7149,7 +7442,7 @@ case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 56)) { _Internal::set_has_map_entry(&has_bits); - map_entry_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.map_entry_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7177,7 +7470,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -7188,7 +7481,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -7202,7 +7495,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional bool message_set_wire_format = 1 [default = false]; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); @@ -7236,7 +7529,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -7251,7 +7544,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.MessageOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -7259,12 +7552,12 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { // optional bool message_set_wire_format = 1 [default = false]; if (cached_has_bits & 0x00000001u) { @@ -7287,11 +7580,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData MessageOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, MessageOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*MessageOptions::GetClassData() const { return &_class_data_; } @@ -7309,24 +7602,24 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - cached_has_bits = from._has_bits_[0]; + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { - message_set_wire_format_ = from.message_set_wire_format_; + _impl_.message_set_wire_format_ = from._impl_.message_set_wire_format_; } if (cached_has_bits & 0x00000002u) { - no_standard_descriptor_accessor_ = from.no_standard_descriptor_accessor_; + _impl_.no_standard_descriptor_accessor_ = from._impl_.no_standard_descriptor_accessor_; } if (cached_has_bits & 0x00000004u) { - deprecated_ = from.deprecated_; + _impl_.deprecated_ = from._impl_.deprecated_; } if (cached_has_bits & 0x00000008u) { - map_entry_ = from.map_entry_; + _impl_.map_entry_ = from._impl_.map_entry_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -7338,27 +7631,27 @@ } bool MessageOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void MessageOptions::InternalSwap(MessageOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); ::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_FIELD_OFFSET(MessageOptions, _impl_.map_entry_) + + sizeof(MessageOptions::_impl_.map_entry_) + - PROTOBUF_FIELD_OFFSET(MessageOptions, _impl_.message_set_wire_format_)>( + reinterpret_cast<char*>(&_impl_.message_set_wire_format_), + reinterpret_cast<char*>(&other->_impl_.message_set_wire_format_)); } ::PROTOBUF_NAMESPACE_ID::Metadata MessageOptions::GetMetadata() const { @@ -7371,7 +7664,7 @@ class FieldOptions::_Internal { public: - using HasBits = decltype(std::declval<FieldOptions>()._has_bits_); + using HasBits = decltype(std::declval<FieldOptions>()._impl_._has_bits_); static void set_has_ctype(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -7397,29 +7690,50 @@ FieldOptions::FieldOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldOptions) } FieldOptions::FieldOptions(const FieldOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , decltype(_impl_.ctype_){} + , decltype(_impl_.jstype_){} + , decltype(_impl_.packed_){} + , decltype(_impl_.lazy_){} + , decltype(_impl_.unverified_lazy_){} + , decltype(_impl_.deprecated_){} + , decltype(_impl_.weak_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); - ::memcpy(&ctype_, &from.ctype_, - static_cast<size_t>(reinterpret_cast<char*>(&weak_) - - reinterpret_cast<char*>(&ctype_)) + sizeof(weak_)); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); + ::memcpy(&_impl_.ctype_, &from._impl_.ctype_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.weak_) - + reinterpret_cast<char*>(&_impl_.ctype_)) + sizeof(_impl_.weak_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldOptions) } -inline void FieldOptions::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&ctype_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&weak_) - - reinterpret_cast<char*>(&ctype_)) + sizeof(weak_)); +inline void FieldOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){arena} + , decltype(_impl_.ctype_){0} + , decltype(_impl_.jstype_){0} + , decltype(_impl_.packed_){false} + , decltype(_impl_.lazy_){false} + , decltype(_impl_.unverified_lazy_){false} + , decltype(_impl_.deprecated_){false} + , decltype(_impl_.weak_){false} + }; } FieldOptions::~FieldOptions() { @@ -7433,10 +7747,12 @@ inline void FieldOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); } void FieldOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void FieldOptions::Clear() { @@ -7445,15 +7761,15 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { - ::memset(&ctype_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&weak_) - - reinterpret_cast<char*>(&ctype_)) + sizeof(weak_)); + ::memset(&_impl_.ctype_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.weak_) - + reinterpret_cast<char*>(&_impl_.ctype_)) + sizeof(_impl_.weak_)); } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -7481,7 +7797,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_packed(&has_bits); - packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7490,7 +7806,7 @@ case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) { _Internal::set_has_deprecated(&has_bits); - deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7499,7 +7815,7 @@ case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 40)) { _Internal::set_has_lazy(&has_bits); - lazy_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.lazy_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7521,7 +7837,7 @@ case 10: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 80)) { _Internal::set_has_weak(&has_bits); - weak_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.weak_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7530,7 +7846,7 @@ case 15: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 120)) { _Internal::set_has_unverified_lazy(&has_bits); - unverified_lazy_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.unverified_lazy_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -7558,7 +7874,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -7569,7 +7885,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -7583,7 +7899,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); @@ -7637,7 +7953,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -7652,7 +7968,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.FieldOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -7660,12 +7976,12 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; if (cached_has_bits & 0x00000001u) { @@ -7705,11 +8021,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData FieldOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, FieldOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*FieldOptions::GetClassData() const { return &_class_data_; } @@ -7727,33 +8043,33 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - cached_has_bits = from._has_bits_[0]; + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x0000007fu) { if (cached_has_bits & 0x00000001u) { - ctype_ = from.ctype_; + _impl_.ctype_ = from._impl_.ctype_; } if (cached_has_bits & 0x00000002u) { - jstype_ = from.jstype_; + _impl_.jstype_ = from._impl_.jstype_; } if (cached_has_bits & 0x00000004u) { - packed_ = from.packed_; + _impl_.packed_ = from._impl_.packed_; } if (cached_has_bits & 0x00000008u) { - lazy_ = from.lazy_; + _impl_.lazy_ = from._impl_.lazy_; } if (cached_has_bits & 0x00000010u) { - unverified_lazy_ = from.unverified_lazy_; + _impl_.unverified_lazy_ = from._impl_.unverified_lazy_; } if (cached_has_bits & 0x00000020u) { - deprecated_ = from.deprecated_; + _impl_.deprecated_ = from._impl_.deprecated_; } if (cached_has_bits & 0x00000040u) { - weak_ = from.weak_; + _impl_.weak_ = from._impl_.weak_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -7765,27 +8081,27 @@ } bool FieldOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void FieldOptions::InternalSwap(FieldOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); ::PROTOBUF_NAMESPACE_ID::internal::memswap< - PROTOBUF_FIELD_OFFSET(FieldOptions, weak_) - + sizeof(FieldOptions::weak_) - - PROTOBUF_FIELD_OFFSET(FieldOptions, ctype_)>( - reinterpret_cast<char*>(&ctype_), - reinterpret_cast<char*>(&other->ctype_)); + PROTOBUF_FIELD_OFFSET(FieldOptions, _impl_.weak_) + + sizeof(FieldOptions::_impl_.weak_) + - PROTOBUF_FIELD_OFFSET(FieldOptions, _impl_.ctype_)>( + reinterpret_cast<char*>(&_impl_.ctype_), + reinterpret_cast<char*>(&other->_impl_.ctype_)); } ::PROTOBUF_NAMESPACE_ID::Metadata FieldOptions::GetMetadata() const { @@ -7802,21 +8118,31 @@ OneofOptions::OneofOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.OneofOptions) } OneofOptions::OneofOptions(const OneofOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); // @@protoc_insertion_point(copy_constructor:google.protobuf.OneofOptions) } -inline void OneofOptions::SharedCtor() { +inline void OneofOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_.uninterpreted_option_){arena} + , /*decltype(_impl_._cached_size_)*/{} + }; } OneofOptions::~OneofOptions() { @@ -7830,10 +8156,12 @@ inline void OneofOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); } void OneofOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void OneofOptions::Clear() { @@ -7842,8 +8170,8 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -7876,7 +8204,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -7909,7 +8237,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -7924,7 +8252,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.OneofOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -7932,16 +8260,16 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData OneofOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, OneofOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*OneofOptions::GetClassData() const { return &_class_data_; } @@ -7959,8 +8287,8 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -7972,20 +8300,20 @@ } bool OneofOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void OneofOptions::InternalSwap(OneofOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); } ::PROTOBUF_NAMESPACE_ID::Metadata OneofOptions::GetMetadata() const { @@ -7998,7 +8326,7 @@ class EnumOptions::_Internal { public: - using HasBits = decltype(std::declval<EnumOptions>()._has_bits_); + using HasBits = decltype(std::declval<EnumOptions>()._impl_._has_bits_); static void set_has_allow_alias(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -8009,29 +8337,40 @@ EnumOptions::EnumOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumOptions) } EnumOptions::EnumOptions(const EnumOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , decltype(_impl_.allow_alias_){} + , decltype(_impl_.deprecated_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); - ::memcpy(&allow_alias_, &from.allow_alias_, - static_cast<size_t>(reinterpret_cast<char*>(&deprecated_) - - reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_)); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); + ::memcpy(&_impl_.allow_alias_, &from._impl_.allow_alias_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.deprecated_) - + reinterpret_cast<char*>(&_impl_.allow_alias_)) + sizeof(_impl_.deprecated_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumOptions) } -inline void EnumOptions::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&allow_alias_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&deprecated_) - - reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_)); +inline void EnumOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){arena} + , decltype(_impl_.allow_alias_){false} + , decltype(_impl_.deprecated_){false} + }; } EnumOptions::~EnumOptions() { @@ -8045,10 +8384,12 @@ inline void EnumOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); } void EnumOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void EnumOptions::Clear() { @@ -8057,12 +8398,12 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); - ::memset(&allow_alias_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&deprecated_) - - reinterpret_cast<char*>(&allow_alias_)) + sizeof(deprecated_)); - _has_bits_.Clear(); + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); + ::memset(&_impl_.allow_alias_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.deprecated_) - + reinterpret_cast<char*>(&_impl_.allow_alias_)) + sizeof(_impl_.deprecated_)); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -8077,7 +8418,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_allow_alias(&has_bits); - allow_alias_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.allow_alias_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -8086,7 +8427,7 @@ case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) { _Internal::set_has_deprecated(&has_bits); - deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -8114,7 +8455,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -8125,7 +8466,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -8139,7 +8480,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional bool allow_alias = 2; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); @@ -8161,7 +8502,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -8176,7 +8517,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -8184,12 +8525,12 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional bool allow_alias = 2; if (cached_has_bits & 0x00000001u) { @@ -8202,11 +8543,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData EnumOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, EnumOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*EnumOptions::GetClassData() const { return &_class_data_; } @@ -8224,18 +8565,18 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - cached_has_bits = from._has_bits_[0]; + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - allow_alias_ = from.allow_alias_; + _impl_.allow_alias_ = from._impl_.allow_alias_; } if (cached_has_bits & 0x00000002u) { - deprecated_ = from.deprecated_; + _impl_.deprecated_ = from._impl_.deprecated_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -8247,27 +8588,27 @@ } bool EnumOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void EnumOptions::InternalSwap(EnumOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); ::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_FIELD_OFFSET(EnumOptions, _impl_.deprecated_) + + sizeof(EnumOptions::_impl_.deprecated_) + - PROTOBUF_FIELD_OFFSET(EnumOptions, _impl_.allow_alias_)>( + reinterpret_cast<char*>(&_impl_.allow_alias_), + reinterpret_cast<char*>(&other->_impl_.allow_alias_)); } ::PROTOBUF_NAMESPACE_ID::Metadata EnumOptions::GetMetadata() const { @@ -8280,7 +8621,7 @@ class EnumValueOptions::_Internal { public: - using HasBits = decltype(std::declval<EnumValueOptions>()._has_bits_); + using HasBits = decltype(std::declval<EnumValueOptions>()._impl_._has_bits_); static void set_has_deprecated(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -8288,24 +8629,36 @@ EnumValueOptions::EnumValueOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValueOptions) } EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , decltype(_impl_.deprecated_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); - deprecated_ = from.deprecated_; + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); + _impl_.deprecated_ = from._impl_.deprecated_; // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValueOptions) } -inline void EnumValueOptions::SharedCtor() { -deprecated_ = false; +inline void EnumValueOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){arena} + , decltype(_impl_.deprecated_){false} + }; } EnumValueOptions::~EnumValueOptions() { @@ -8319,10 +8672,12 @@ inline void EnumValueOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); } void EnumValueOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void EnumValueOptions::Clear() { @@ -8331,10 +8686,10 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); - deprecated_ = false; - _has_bits_.Clear(); + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); + _impl_.deprecated_ = false; + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -8349,7 +8704,7 @@ case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { _Internal::set_has_deprecated(&has_bits); - deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -8377,7 +8732,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -8388,7 +8743,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -8402,7 +8757,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional bool deprecated = 1 [default = false]; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); @@ -8418,7 +8773,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -8433,7 +8788,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.EnumValueOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -8441,22 +8796,22 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // optional bool deprecated = 1 [default = false]; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 1 + 1; } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData EnumValueOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, EnumValueOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*EnumValueOptions::GetClassData() const { return &_class_data_; } @@ -8474,11 +8829,11 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); if (from._internal_has_deprecated()) { _internal_set_deprecated(from._internal_deprecated()); } - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -8490,22 +8845,22 @@ } bool EnumValueOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void EnumValueOptions::InternalSwap(EnumValueOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); - swap(deprecated_, other->deprecated_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); + swap(_impl_.deprecated_, other->_impl_.deprecated_); } ::PROTOBUF_NAMESPACE_ID::Metadata EnumValueOptions::GetMetadata() const { @@ -8518,7 +8873,7 @@ class ServiceOptions::_Internal { public: - using HasBits = decltype(std::declval<ServiceOptions>()._has_bits_); + using HasBits = decltype(std::declval<ServiceOptions>()._impl_._has_bits_); static void set_has_deprecated(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -8526,24 +8881,36 @@ ServiceOptions::ServiceOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.ServiceOptions) } ServiceOptions::ServiceOptions(const ServiceOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , decltype(_impl_.deprecated_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); - deprecated_ = from.deprecated_; + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); + _impl_.deprecated_ = from._impl_.deprecated_; // @@protoc_insertion_point(copy_constructor:google.protobuf.ServiceOptions) } -inline void ServiceOptions::SharedCtor() { -deprecated_ = false; +inline void ServiceOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){arena} + , decltype(_impl_.deprecated_){false} + }; } ServiceOptions::~ServiceOptions() { @@ -8557,10 +8924,12 @@ inline void ServiceOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); } void ServiceOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void ServiceOptions::Clear() { @@ -8569,10 +8938,10 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); - deprecated_ = false; - _has_bits_.Clear(); + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); + _impl_.deprecated_ = false; + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -8587,7 +8956,7 @@ case 33: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { _Internal::set_has_deprecated(&has_bits); - deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -8615,7 +8984,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -8626,7 +8995,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -8640,7 +9009,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional bool deprecated = 33 [default = false]; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); @@ -8656,7 +9025,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -8671,7 +9040,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.ServiceOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -8679,22 +9048,22 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // optional bool deprecated = 33 [default = false]; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 2 + 1; } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData ServiceOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, ServiceOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*ServiceOptions::GetClassData() const { return &_class_data_; } @@ -8712,11 +9081,11 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); if (from._internal_has_deprecated()) { _internal_set_deprecated(from._internal_deprecated()); } - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -8728,22 +9097,22 @@ } bool ServiceOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void ServiceOptions::InternalSwap(ServiceOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); - swap(deprecated_, other->deprecated_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); + swap(_impl_.deprecated_, other->_impl_.deprecated_); } ::PROTOBUF_NAMESPACE_ID::Metadata ServiceOptions::GetMetadata() const { @@ -8756,7 +9125,7 @@ class MethodOptions::_Internal { public: - using HasBits = decltype(std::declval<MethodOptions>()._has_bits_); + using HasBits = decltype(std::declval<MethodOptions>()._impl_._has_bits_); static void set_has_deprecated(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -8767,29 +9136,40 @@ MethodOptions::MethodOptions(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - _extensions_(arena), - uninterpreted_option_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.MethodOptions) } MethodOptions::MethodOptions(const MethodOptions& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - uninterpreted_option_(from.uninterpreted_option_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{} + , decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){from._impl_.uninterpreted_option_} + , decltype(_impl_.deprecated_){} + , decltype(_impl_.idempotency_level_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); - ::memcpy(&deprecated_, &from.deprecated_, - static_cast<size_t>(reinterpret_cast<char*>(&idempotency_level_) - - reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_)); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); + ::memcpy(&_impl_.deprecated_, &from._impl_.deprecated_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.idempotency_level_) - + reinterpret_cast<char*>(&_impl_.deprecated_)) + sizeof(_impl_.idempotency_level_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.MethodOptions) } -inline void MethodOptions::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&deprecated_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&idempotency_level_) - - reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_)); +inline void MethodOptions::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_._extensions_)*/{::_pbi::ArenaInitialized(), arena} + , decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.uninterpreted_option_){arena} + , decltype(_impl_.deprecated_){false} + , decltype(_impl_.idempotency_level_){0} + }; } MethodOptions::~MethodOptions() { @@ -8803,10 +9183,12 @@ inline void MethodOptions::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_._extensions_.~ExtensionSet(); + _impl_.uninterpreted_option_.~RepeatedPtrField(); } void MethodOptions::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void MethodOptions::Clear() { @@ -8815,15 +9197,15 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - _extensions_.Clear(); - uninterpreted_option_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_._extensions_.Clear(); + _impl_.uninterpreted_option_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { - ::memset(&deprecated_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&idempotency_level_) - - reinterpret_cast<char*>(&deprecated_)) + sizeof(idempotency_level_)); + ::memset(&_impl_.deprecated_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.idempotency_level_) - + reinterpret_cast<char*>(&_impl_.deprecated_)) + sizeof(_impl_.idempotency_level_)); } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -8838,7 +9220,7 @@ case 33: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { _Internal::set_has_deprecated(&has_bits); - deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.deprecated_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -8879,7 +9261,7 @@ goto message_done; } if ((8000u <= tag)) { - ptr = _extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); + ptr = _impl_._extensions_.ParseField(tag, ptr, internal_default_instance(), &_internal_metadata_, ctx); CHK_(ptr != nullptr); continue; } @@ -8890,7 +9272,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -8904,7 +9286,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional bool deprecated = 33 [default = false]; if (cached_has_bits & 0x00000001u) { target = stream->EnsureSpace(target); @@ -8927,7 +9309,7 @@ } // Extension range [1000, 536870912) - target = _extensions_._InternalSerialize( + target = _impl_._extensions_._InternalSerialize( internal_default_instance(), 1000, 536870912, target, stream); if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { @@ -8942,7 +9324,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.MethodOptions) size_t total_size = 0; - total_size += _extensions_.ByteSize(); + total_size += _impl_._extensions_.ByteSize(); uint32_t cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused @@ -8950,12 +9332,12 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; total_size += 2UL * this->_internal_uninterpreted_option_size(); - for (const auto& msg : this->uninterpreted_option_) { + for (const auto& msg : this->_impl_.uninterpreted_option_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional bool deprecated = 33 [default = false]; if (cached_has_bits & 0x00000001u) { @@ -8969,11 +9351,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData MethodOptions::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, MethodOptions::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*MethodOptions::GetClassData() const { return &_class_data_; } @@ -8991,18 +9373,18 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - cached_has_bits = from._has_bits_[0]; + _impl_.uninterpreted_option_.MergeFrom(from._impl_.uninterpreted_option_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - deprecated_ = from.deprecated_; + _impl_.deprecated_ = from._impl_.deprecated_; } if (cached_has_bits & 0x00000002u) { - idempotency_level_ = from.idempotency_level_; + _impl_.idempotency_level_ = from._impl_.idempotency_level_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } - _extensions_.MergeFrom(internal_default_instance(), from._extensions_); + _impl_._extensions_.MergeFrom(internal_default_instance(), from._impl_._extensions_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -9014,27 +9396,27 @@ } bool MethodOptions::IsInitialized() const { - if (!_extensions_.IsInitialized()) { + if (!_impl_._extensions_.IsInitialized()) { return false; } - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(uninterpreted_option_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.uninterpreted_option_)) return false; return true; } void MethodOptions::InternalSwap(MethodOptions* other) { using std::swap; - _extensions_.InternalSwap(&other->_extensions_); + _impl_._extensions_.InternalSwap(&other->_impl_._extensions_); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - uninterpreted_option_.InternalSwap(&other->uninterpreted_option_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.uninterpreted_option_.InternalSwap(&other->_impl_.uninterpreted_option_); ::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_FIELD_OFFSET(MethodOptions, _impl_.idempotency_level_) + + sizeof(MethodOptions::_impl_.idempotency_level_) + - PROTOBUF_FIELD_OFFSET(MethodOptions, _impl_.deprecated_)>( + reinterpret_cast<char*>(&_impl_.deprecated_), + reinterpret_cast<char*>(&other->_impl_.deprecated_)); } ::PROTOBUF_NAMESPACE_ID::Metadata MethodOptions::GetMetadata() const { @@ -9047,7 +9429,7 @@ class UninterpretedOption_NamePart::_Internal { public: - using HasBits = decltype(std::declval<UninterpretedOption_NamePart>()._has_bits_); + using HasBits = decltype(std::declval<UninterpretedOption_NamePart>()._impl_._has_bits_); static void set_has_name_part(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -9062,31 +9444,44 @@ UninterpretedOption_NamePart::UninterpretedOption_NamePart(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption.NamePart) } UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_part_){} + , decltype(_impl_.is_extension_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_part_.InitDefault(); + _impl_.name_part_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_part_.Set("", GetArenaForAllocation()); + _impl_.name_part_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_name_part()) { - name_part_.Set(from._internal_name_part(), + _impl_.name_part_.Set(from._internal_name_part(), GetArenaForAllocation()); } - is_extension_ = from.is_extension_; + _impl_.is_extension_ = from._impl_.is_extension_; // @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption.NamePart) } -inline void UninterpretedOption_NamePart::SharedCtor() { -name_part_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_part_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -is_extension_ = false; +inline void UninterpretedOption_NamePart::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_part_){} + , decltype(_impl_.is_extension_){false} + }; + _impl_.name_part_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_part_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } UninterpretedOption_NamePart::~UninterpretedOption_NamePart() { @@ -9100,11 +9495,11 @@ inline void UninterpretedOption_NamePart::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_part_.Destroy(); + _impl_.name_part_.Destroy(); } void UninterpretedOption_NamePart::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void UninterpretedOption_NamePart::Clear() { @@ -9113,12 +9508,12 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000001u) { - name_part_.ClearNonDefaultToEmpty(); + _impl_.name_part_.ClearNonDefaultToEmpty(); } - is_extension_ = false; - _has_bits_.Clear(); + _impl_.is_extension_ = false; + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -9145,7 +9540,7 @@ case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { _Internal::set_has_is_extension(&has_bits); - is_extension_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.is_extension_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -9166,7 +9561,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -9180,7 +9575,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // required string name_part = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -9227,7 +9622,7 @@ // @@protoc_insertion_point(message_byte_size_start:google.protobuf.UninterpretedOption.NamePart) size_t total_size = 0; - if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. + if (((_impl_._has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present. // required string name_part = 1; total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( @@ -9243,11 +9638,11 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData UninterpretedOption_NamePart::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, UninterpretedOption_NamePart::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*UninterpretedOption_NamePart::GetClassData() const { return &_class_data_; } @@ -9265,15 +9660,15 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - cached_has_bits = from._has_bits_[0]; + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_name_part(from._internal_name_part()); } if (cached_has_bits & 0x00000002u) { - is_extension_ = from.is_extension_; + _impl_.is_extension_ = from._impl_.is_extension_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -9286,7 +9681,7 @@ } bool UninterpretedOption_NamePart::IsInitialized() const { - if (_Internal::MissingRequiredFields(_has_bits_)) return false; + if (_Internal::MissingRequiredFields(_impl_._has_bits_)) return false; return true; } @@ -9295,12 +9690,12 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_part_, lhs_arena, - &other->name_part_, rhs_arena + &_impl_.name_part_, lhs_arena, + &other->_impl_.name_part_, rhs_arena ); - swap(is_extension_, other->is_extension_); + swap(_impl_.is_extension_, other->_impl_.is_extension_); } ::PROTOBUF_NAMESPACE_ID::Metadata UninterpretedOption_NamePart::GetMetadata() const { @@ -9313,7 +9708,7 @@ class UninterpretedOption::_Internal { public: - using HasBits = decltype(std::declval<UninterpretedOption>()._has_bits_); + using HasBits = decltype(std::declval<UninterpretedOption>()._impl_._has_bits_); static void set_has_identifier_value(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -9336,63 +9731,81 @@ UninterpretedOption::UninterpretedOption(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - name_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.UninterpretedOption) } UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - name_(from.name_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){from._impl_.name_} + , decltype(_impl_.identifier_value_){} + , decltype(_impl_.string_value_){} + , decltype(_impl_.aggregate_value_){} + , decltype(_impl_.positive_int_value_){} + , decltype(_impl_.negative_int_value_){} + , decltype(_impl_.double_value_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - identifier_value_.InitDefault(); + _impl_.identifier_value_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - identifier_value_.Set("", GetArenaForAllocation()); + _impl_.identifier_value_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_identifier_value()) { - identifier_value_.Set(from._internal_identifier_value(), + _impl_.identifier_value_.Set(from._internal_identifier_value(), GetArenaForAllocation()); } - string_value_.InitDefault(); + _impl_.string_value_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - string_value_.Set("", GetArenaForAllocation()); + _impl_.string_value_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_string_value()) { - string_value_.Set(from._internal_string_value(), + _impl_.string_value_.Set(from._internal_string_value(), GetArenaForAllocation()); } - aggregate_value_.InitDefault(); + _impl_.aggregate_value_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - aggregate_value_.Set("", GetArenaForAllocation()); + _impl_.aggregate_value_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_aggregate_value()) { - aggregate_value_.Set(from._internal_aggregate_value(), + _impl_.aggregate_value_.Set(from._internal_aggregate_value(), GetArenaForAllocation()); } - ::memcpy(&positive_int_value_, &from.positive_int_value_, - static_cast<size_t>(reinterpret_cast<char*>(&double_value_) - - reinterpret_cast<char*>(&positive_int_value_)) + sizeof(double_value_)); + ::memcpy(&_impl_.positive_int_value_, &from._impl_.positive_int_value_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.double_value_) - + reinterpret_cast<char*>(&_impl_.positive_int_value_)) + sizeof(_impl_.double_value_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.UninterpretedOption) } -inline void UninterpretedOption::SharedCtor() { -identifier_value_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - identifier_value_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -string_value_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - string_value_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -aggregate_value_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - aggregate_value_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&positive_int_value_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&double_value_) - - reinterpret_cast<char*>(&positive_int_value_)) + sizeof(double_value_)); +inline void UninterpretedOption::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.name_){arena} + , decltype(_impl_.identifier_value_){} + , decltype(_impl_.string_value_){} + , decltype(_impl_.aggregate_value_){} + , decltype(_impl_.positive_int_value_){uint64_t{0u}} + , decltype(_impl_.negative_int_value_){int64_t{0}} + , decltype(_impl_.double_value_){0} + }; + _impl_.identifier_value_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.identifier_value_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.string_value_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.string_value_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.aggregate_value_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.aggregate_value_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } UninterpretedOption::~UninterpretedOption() { @@ -9406,13 +9819,14 @@ inline void UninterpretedOption::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - identifier_value_.Destroy(); - string_value_.Destroy(); - aggregate_value_.Destroy(); + _impl_.name_.~RepeatedPtrField(); + _impl_.identifier_value_.Destroy(); + _impl_.string_value_.Destroy(); + _impl_.aggregate_value_.Destroy(); } void UninterpretedOption::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void UninterpretedOption::Clear() { @@ -9421,25 +9835,25 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - name_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.name_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { - identifier_value_.ClearNonDefaultToEmpty(); + _impl_.identifier_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - string_value_.ClearNonDefaultToEmpty(); + _impl_.string_value_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { - aggregate_value_.ClearNonDefaultToEmpty(); + _impl_.aggregate_value_.ClearNonDefaultToEmpty(); } } if (cached_has_bits & 0x00000038u) { - ::memset(&positive_int_value_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&double_value_) - - reinterpret_cast<char*>(&positive_int_value_)) + sizeof(double_value_)); + ::memset(&_impl_.positive_int_value_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.double_value_) - + reinterpret_cast<char*>(&_impl_.positive_int_value_)) + sizeof(_impl_.double_value_)); } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -9479,7 +9893,7 @@ case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 32)) { _Internal::set_has_positive_int_value(&has_bits); - positive_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.positive_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -9488,7 +9902,7 @@ case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 40)) { _Internal::set_has_negative_int_value(&has_bits); - negative_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.negative_int_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -9497,7 +9911,7 @@ case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 49)) { _Internal::set_has_double_value(&has_bits); - double_value_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); + _impl_.double_value_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; @@ -9539,7 +9953,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -9561,7 +9975,7 @@ InternalWriteMessage(2, repfield, repfield.GetCachedSize(), target, stream); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string identifier_value = 3; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -9624,12 +10038,12 @@ // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; total_size += 1UL * this->_internal_name_size(); - for (const auto& msg : this->name_) { + for (const auto& msg : this->_impl_.name_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { // optional string identifier_value = 3; if (cached_has_bits & 0x00000001u) { @@ -9668,11 +10082,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData UninterpretedOption::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, UninterpretedOption::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*UninterpretedOption::GetClassData() const { return &_class_data_; } @@ -9690,8 +10104,8 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - name_.MergeFrom(from.name_); - cached_has_bits = from._has_bits_[0]; + _impl_.name_.MergeFrom(from._impl_.name_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { _internal_set_identifier_value(from._internal_identifier_value()); @@ -9703,15 +10117,15 @@ _internal_set_aggregate_value(from._internal_aggregate_value()); } if (cached_has_bits & 0x00000008u) { - positive_int_value_ = from.positive_int_value_; + _impl_.positive_int_value_ = from._impl_.positive_int_value_; } if (cached_has_bits & 0x00000010u) { - negative_int_value_ = from.negative_int_value_; + _impl_.negative_int_value_ = from._impl_.negative_int_value_; } if (cached_has_bits & 0x00000020u) { - double_value_ = from.double_value_; + _impl_.double_value_ = from._impl_.double_value_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -9724,7 +10138,7 @@ } bool UninterpretedOption::IsInitialized() const { - if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(name_)) + if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(_impl_.name_)) return false; return true; } @@ -9734,26 +10148,26 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - name_.InternalSwap(&other->name_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.name_.InternalSwap(&other->_impl_.name_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &identifier_value_, lhs_arena, - &other->identifier_value_, rhs_arena + &_impl_.identifier_value_, lhs_arena, + &other->_impl_.identifier_value_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &string_value_, lhs_arena, - &other->string_value_, rhs_arena + &_impl_.string_value_, lhs_arena, + &other->_impl_.string_value_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &aggregate_value_, lhs_arena, - &other->aggregate_value_, rhs_arena + &_impl_.aggregate_value_, lhs_arena, + &other->_impl_.aggregate_value_, rhs_arena ); ::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_FIELD_OFFSET(UninterpretedOption, _impl_.double_value_) + + sizeof(UninterpretedOption::_impl_.double_value_) + - PROTOBUF_FIELD_OFFSET(UninterpretedOption, _impl_.positive_int_value_)>( + reinterpret_cast<char*>(&_impl_.positive_int_value_), + reinterpret_cast<char*>(&other->_impl_.positive_int_value_)); } ::PROTOBUF_NAMESPACE_ID::Metadata UninterpretedOption::GetMetadata() const { @@ -9766,7 +10180,7 @@ class SourceCodeInfo_Location::_Internal { public: - using HasBits = decltype(std::declval<SourceCodeInfo_Location>()._has_bits_); + using HasBits = decltype(std::declval<SourceCodeInfo_Location>()._impl_._has_bits_); static void set_has_leading_comments(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -9777,48 +10191,66 @@ SourceCodeInfo_Location::SourceCodeInfo_Location(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - path_(arena), - span_(arena), - leading_detached_comments_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo.Location) } SourceCodeInfo_Location::SourceCodeInfo_Location(const SourceCodeInfo_Location& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - path_(from.path_), - span_(from.span_), - leading_detached_comments_(from.leading_detached_comments_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.path_){from._impl_.path_} + , /*decltype(_impl_._path_cached_byte_size_)*/{0} + , decltype(_impl_.span_){from._impl_.span_} + , /*decltype(_impl_._span_cached_byte_size_)*/{0} + , decltype(_impl_.leading_detached_comments_){from._impl_.leading_detached_comments_} + , decltype(_impl_.leading_comments_){} + , decltype(_impl_.trailing_comments_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - leading_comments_.InitDefault(); + _impl_.leading_comments_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - leading_comments_.Set("", GetArenaForAllocation()); + _impl_.leading_comments_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_leading_comments()) { - leading_comments_.Set(from._internal_leading_comments(), + _impl_.leading_comments_.Set(from._internal_leading_comments(), GetArenaForAllocation()); } - trailing_comments_.InitDefault(); + _impl_.trailing_comments_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - trailing_comments_.Set("", GetArenaForAllocation()); + _impl_.trailing_comments_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_trailing_comments()) { - trailing_comments_.Set(from._internal_trailing_comments(), + _impl_.trailing_comments_.Set(from._internal_trailing_comments(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo.Location) } -inline void SourceCodeInfo_Location::SharedCtor() { -leading_comments_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - leading_comments_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -trailing_comments_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - trailing_comments_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING +inline void SourceCodeInfo_Location::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.path_){arena} + , /*decltype(_impl_._path_cached_byte_size_)*/{0} + , decltype(_impl_.span_){arena} + , /*decltype(_impl_._span_cached_byte_size_)*/{0} + , decltype(_impl_.leading_detached_comments_){arena} + , decltype(_impl_.leading_comments_){} + , decltype(_impl_.trailing_comments_){} + }; + _impl_.leading_comments_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.leading_comments_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.trailing_comments_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.trailing_comments_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } SourceCodeInfo_Location::~SourceCodeInfo_Location() { @@ -9832,12 +10264,15 @@ inline void SourceCodeInfo_Location::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - leading_comments_.Destroy(); - trailing_comments_.Destroy(); + _impl_.path_.~RepeatedField(); + _impl_.span_.~RepeatedField(); + _impl_.leading_detached_comments_.~RepeatedPtrField(); + _impl_.leading_comments_.Destroy(); + _impl_.trailing_comments_.Destroy(); } void SourceCodeInfo_Location::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void SourceCodeInfo_Location::Clear() { @@ -9846,19 +10281,19 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - path_.Clear(); - span_.Clear(); - leading_detached_comments_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.path_.Clear(); + _impl_.span_.Clear(); + _impl_.leading_detached_comments_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { - leading_comments_.ClearNonDefaultToEmpty(); + _impl_.leading_comments_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { - trailing_comments_.ClearNonDefaultToEmpty(); + _impl_.trailing_comments_.ClearNonDefaultToEmpty(); } } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -9948,7 +10383,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -9964,7 +10399,7 @@ // repeated int32 path = 1 [packed = true]; { - int byte_size = _path_cached_byte_size_.load(std::memory_order_relaxed); + int byte_size = _impl_._path_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteInt32Packed( 1, _internal_path(), byte_size, target); @@ -9973,14 +10408,14 @@ // repeated int32 span = 2 [packed = true]; { - int byte_size = _span_cached_byte_size_.load(std::memory_order_relaxed); + int byte_size = _impl_._span_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteInt32Packed( 2, _internal_span(), byte_size, target); } } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string leading_comments = 3; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -10030,13 +10465,13 @@ // repeated int32 path = 1 [packed = true]; { size_t data_size = ::_pbi::WireFormatLite:: - Int32Size(this->path_); + Int32Size(this->_impl_.path_); if (data_size > 0) { total_size += 1 + ::_pbi::WireFormatLite::Int32Size(static_cast<int32_t>(data_size)); } int cached_size = ::_pbi::ToCachedSize(data_size); - _path_cached_byte_size_.store(cached_size, + _impl_._path_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } @@ -10044,26 +10479,26 @@ // repeated int32 span = 2 [packed = true]; { size_t data_size = ::_pbi::WireFormatLite:: - Int32Size(this->span_); + Int32Size(this->_impl_.span_); if (data_size > 0) { total_size += 1 + ::_pbi::WireFormatLite::Int32Size(static_cast<int32_t>(data_size)); } int cached_size = ::_pbi::ToCachedSize(data_size); - _span_cached_byte_size_.store(cached_size, + _impl_._span_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // repeated string leading_detached_comments = 6; total_size += 1 * - ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(leading_detached_comments_.size()); - for (int i = 0, n = leading_detached_comments_.size(); i < n; i++) { + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(_impl_.leading_detached_comments_.size()); + for (int i = 0, n = _impl_.leading_detached_comments_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( - leading_detached_comments_.Get(i)); + _impl_.leading_detached_comments_.Get(i)); } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string leading_comments = 3; if (cached_has_bits & 0x00000001u) { @@ -10080,11 +10515,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData SourceCodeInfo_Location::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, SourceCodeInfo_Location::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*SourceCodeInfo_Location::GetClassData() const { return &_class_data_; } @@ -10102,10 +10537,10 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - path_.MergeFrom(from.path_); - span_.MergeFrom(from.span_); - leading_detached_comments_.MergeFrom(from.leading_detached_comments_); - cached_has_bits = from._has_bits_[0]; + _impl_.path_.MergeFrom(from._impl_.path_); + _impl_.span_.MergeFrom(from._impl_.span_); + _impl_.leading_detached_comments_.MergeFrom(from._impl_.leading_detached_comments_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_leading_comments(from._internal_leading_comments()); @@ -10133,17 +10568,17 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&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_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.path_.InternalSwap(&other->_impl_.path_); + _impl_.span_.InternalSwap(&other->_impl_.span_); + _impl_.leading_detached_comments_.InternalSwap(&other->_impl_.leading_detached_comments_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &leading_comments_, lhs_arena, - &other->leading_comments_, rhs_arena + &_impl_.leading_comments_, lhs_arena, + &other->_impl_.leading_comments_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &trailing_comments_, lhs_arena, - &other->trailing_comments_, rhs_arena + &_impl_.trailing_comments_, lhs_arena, + &other->_impl_.trailing_comments_, rhs_arena ); } @@ -10161,19 +10596,28 @@ SourceCodeInfo::SourceCodeInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - location_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceCodeInfo) } SourceCodeInfo::SourceCodeInfo(const SourceCodeInfo& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - location_(from.location_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.location_){from._impl_.location_} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceCodeInfo) } -inline void SourceCodeInfo::SharedCtor() { +inline void SourceCodeInfo::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.location_){arena} + , /*decltype(_impl_._cached_size_)*/{} + }; } SourceCodeInfo::~SourceCodeInfo() { @@ -10187,10 +10631,11 @@ inline void SourceCodeInfo::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_.location_.~RepeatedPtrField(); } void SourceCodeInfo::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void SourceCodeInfo::Clear() { @@ -10199,7 +10644,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - location_.Clear(); + _impl_.location_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -10277,16 +10722,16 @@ // repeated .google.protobuf.SourceCodeInfo.Location location = 1; total_size += 1UL * this->_internal_location_size(); - for (const auto& msg : this->location_) { + for (const auto& msg : this->_impl_.location_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData SourceCodeInfo::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, SourceCodeInfo::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*SourceCodeInfo::GetClassData() const { return &_class_data_; } @@ -10304,7 +10749,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - location_.MergeFrom(from.location_); + _impl_.location_.MergeFrom(from._impl_.location_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -10322,7 +10767,7 @@ void SourceCodeInfo::InternalSwap(SourceCodeInfo* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - location_.InternalSwap(&other->location_); + _impl_.location_.InternalSwap(&other->_impl_.location_); } ::PROTOBUF_NAMESPACE_ID::Metadata SourceCodeInfo::GetMetadata() const { @@ -10335,7 +10780,7 @@ class GeneratedCodeInfo_Annotation::_Internal { public: - using HasBits = decltype(std::declval<GeneratedCodeInfo_Annotation>()._has_bits_); + using HasBits = decltype(std::declval<GeneratedCodeInfo_Annotation>()._impl_._has_bits_); static void set_has_source_file(HasBits* has_bits) { (*has_bits)[0] |= 1u; } @@ -10349,39 +10794,53 @@ GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - path_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo.Annotation) } GeneratedCodeInfo_Annotation::GeneratedCodeInfo_Annotation(const GeneratedCodeInfo_Annotation& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - _has_bits_(from._has_bits_), - path_(from.path_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){from._impl_._has_bits_} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.path_){from._impl_.path_} + , /*decltype(_impl_._path_cached_byte_size_)*/{0} + , decltype(_impl_.source_file_){} + , decltype(_impl_.begin_){} + , decltype(_impl_.end_){}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - source_file_.InitDefault(); + _impl_.source_file_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - source_file_.Set("", GetArenaForAllocation()); + _impl_.source_file_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (from._internal_has_source_file()) { - source_file_.Set(from._internal_source_file(), + _impl_.source_file_.Set(from._internal_source_file(), GetArenaForAllocation()); } - ::memcpy(&begin_, &from.begin_, - static_cast<size_t>(reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&begin_)) + sizeof(end_)); + ::memcpy(&_impl_.begin_, &from._impl_.begin_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.end_) - + reinterpret_cast<char*>(&_impl_.begin_)) + sizeof(_impl_.end_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo.Annotation) } -inline void GeneratedCodeInfo_Annotation::SharedCtor() { -source_file_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - source_file_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&begin_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&begin_)) + sizeof(end_)); +inline void GeneratedCodeInfo_Annotation::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_._has_bits_){} + , /*decltype(_impl_._cached_size_)*/{} + , decltype(_impl_.path_){arena} + , /*decltype(_impl_._path_cached_byte_size_)*/{0} + , decltype(_impl_.source_file_){} + , decltype(_impl_.begin_){0} + , decltype(_impl_.end_){0} + }; + _impl_.source_file_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.source_file_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } GeneratedCodeInfo_Annotation::~GeneratedCodeInfo_Annotation() { @@ -10395,11 +10854,12 @@ inline void GeneratedCodeInfo_Annotation::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - source_file_.Destroy(); + _impl_.path_.~RepeatedField(); + _impl_.source_file_.Destroy(); } void GeneratedCodeInfo_Annotation::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void GeneratedCodeInfo_Annotation::Clear() { @@ -10408,17 +10868,17 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - path_.Clear(); - cached_has_bits = _has_bits_[0]; + _impl_.path_.Clear(); + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000001u) { - source_file_.ClearNonDefaultToEmpty(); + _impl_.source_file_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000006u) { - ::memset(&begin_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&end_) - - reinterpret_cast<char*>(&begin_)) + sizeof(end_)); + ::memset(&_impl_.begin_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.end_) - + reinterpret_cast<char*>(&_impl_.begin_)) + sizeof(_impl_.end_)); } - _has_bits_.Clear(); + _impl_._has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -10456,7 +10916,7 @@ case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) { _Internal::set_has_begin(&has_bits); - begin_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.begin_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -10465,7 +10925,7 @@ case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 32)) { _Internal::set_has_end(&has_bits); - end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.end_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -10486,7 +10946,7 @@ CHK_(ptr != nullptr); } // while message_done: - _has_bits_.Or(has_bits); + _impl_._has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; @@ -10502,14 +10962,14 @@ // repeated int32 path = 1 [packed = true]; { - int byte_size = _path_cached_byte_size_.load(std::memory_order_relaxed); + int byte_size = _impl_._path_cached_byte_size_.load(std::memory_order_relaxed); if (byte_size > 0) { target = stream->WriteInt32Packed( 1, _internal_path(), byte_size, target); } } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; // optional string source_file = 2; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( @@ -10551,18 +11011,18 @@ // repeated int32 path = 1 [packed = true]; { size_t data_size = ::_pbi::WireFormatLite:: - Int32Size(this->path_); + Int32Size(this->_impl_.path_); if (data_size > 0) { total_size += 1 + ::_pbi::WireFormatLite::Int32Size(static_cast<int32_t>(data_size)); } int cached_size = ::_pbi::ToCachedSize(data_size); - _path_cached_byte_size_.store(cached_size, + _impl_._path_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } - cached_has_bits = _has_bits_[0]; + cached_has_bits = _impl_._has_bits_[0]; if (cached_has_bits & 0x00000007u) { // optional string source_file = 2; if (cached_has_bits & 0x00000001u) { @@ -10582,11 +11042,11 @@ } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData GeneratedCodeInfo_Annotation::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, GeneratedCodeInfo_Annotation::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GeneratedCodeInfo_Annotation::GetClassData() const { return &_class_data_; } @@ -10604,19 +11064,19 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - path_.MergeFrom(from.path_); - cached_has_bits = from._has_bits_[0]; + _impl_.path_.MergeFrom(from._impl_.path_); + cached_has_bits = from._impl_._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { _internal_set_source_file(from._internal_source_file()); } if (cached_has_bits & 0x00000002u) { - begin_ = from.begin_; + _impl_.begin_ = from._impl_.begin_; } if (cached_has_bits & 0x00000004u) { - end_ = from.end_; + _impl_.end_ = from._impl_.end_; } - _has_bits_[0] |= cached_has_bits; + _impl_._has_bits_[0] |= cached_has_bits; } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -10637,18 +11097,18 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(_has_bits_[0], other->_has_bits_[0]); - path_.InternalSwap(&other->path_); + swap(_impl_._has_bits_[0], other->_impl_._has_bits_[0]); + _impl_.path_.InternalSwap(&other->_impl_.path_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &source_file_, lhs_arena, - &other->source_file_, rhs_arena + &_impl_.source_file_, lhs_arena, + &other->_impl_.source_file_, rhs_arena ); ::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_FIELD_OFFSET(GeneratedCodeInfo_Annotation, _impl_.end_) + + sizeof(GeneratedCodeInfo_Annotation::_impl_.end_) + - PROTOBUF_FIELD_OFFSET(GeneratedCodeInfo_Annotation, _impl_.begin_)>( + reinterpret_cast<char*>(&_impl_.begin_), + reinterpret_cast<char*>(&other->_impl_.begin_)); } ::PROTOBUF_NAMESPACE_ID::Metadata GeneratedCodeInfo_Annotation::GetMetadata() const { @@ -10665,19 +11125,28 @@ GeneratedCodeInfo::GeneratedCodeInfo(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - annotation_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.GeneratedCodeInfo) } GeneratedCodeInfo::GeneratedCodeInfo(const GeneratedCodeInfo& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - annotation_(from.annotation_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.annotation_){from._impl_.annotation_} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.GeneratedCodeInfo) } -inline void GeneratedCodeInfo::SharedCtor() { +inline void GeneratedCodeInfo::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.annotation_){arena} + , /*decltype(_impl_._cached_size_)*/{} + }; } GeneratedCodeInfo::~GeneratedCodeInfo() { @@ -10691,10 +11160,11 @@ inline void GeneratedCodeInfo::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_.annotation_.~RepeatedPtrField(); } void GeneratedCodeInfo::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void GeneratedCodeInfo::Clear() { @@ -10703,7 +11173,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - annotation_.Clear(); + _impl_.annotation_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -10781,16 +11251,16 @@ // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; total_size += 1UL * this->_internal_annotation_size(); - for (const auto& msg : this->annotation_) { + for (const auto& msg : this->_impl_.annotation_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData GeneratedCodeInfo::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, GeneratedCodeInfo::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GeneratedCodeInfo::GetClassData() const { return &_class_data_; } @@ -10808,7 +11278,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - annotation_.MergeFrom(from.annotation_); + _impl_.annotation_.MergeFrom(from._impl_.annotation_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -10826,7 +11296,7 @@ void GeneratedCodeInfo::InternalSwap(GeneratedCodeInfo* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - annotation_.InternalSwap(&other->annotation_); + _impl_.annotation_.InternalSwap(&other->_impl_.annotation_); } ::PROTOBUF_NAMESPACE_ID::Metadata GeneratedCodeInfo::GetMetadata() const {
diff --git a/src/google/protobuf/descriptor.pb.h b/src/google/protobuf/descriptor.pb.h index 90547f5..4cd97bc 100644 --- a/src/google/protobuf/descriptor.pb.h +++ b/src/google/protobuf/descriptor.pb.h
@@ -418,10 +418,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FileDescriptorSet* other); @@ -473,8 +473,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto > file_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto > file_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -577,10 +580,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FileDescriptorProto* other); @@ -855,20 +858,23 @@ 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> dependency_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto > message_type_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto > enum_type_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto > service_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto > extension_; - ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > public_dependency_; - ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > weak_dependency_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr package_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr syntax_; - ::PROTOBUF_NAMESPACE_ID::FileOptions* options_; - ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> dependency_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto > message_type_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto > enum_type_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto > service_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto > extension_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > public_dependency_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > weak_dependency_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr package_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr syntax_; + ::PROTOBUF_NAMESPACE_ID::FileOptions* options_; + ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -971,10 +977,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto_ExtensionRange* other); @@ -1054,11 +1060,14 @@ 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::ExtensionRangeOptions* options_; - int32_t start_; - int32_t end_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options_; + int32_t start_; + int32_t end_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -1161,10 +1170,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto_ReservedRange* other); @@ -1225,10 +1234,13 @@ 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_; - int32_t start_; - int32_t end_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + int32_t start_; + int32_t end_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -1331,10 +1343,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DescriptorProto* other); @@ -1566,18 +1578,21 @@ 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::FieldDescriptorProto > field_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto > nested_type_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto > enum_type_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange > extension_range_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto > extension_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto > oneof_decl_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange > reserved_range_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> reserved_name_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; - ::PROTOBUF_NAMESPACE_ID::MessageOptions* options_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto > field_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto > nested_type_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto > enum_type_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange > extension_range_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto > extension_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto > oneof_decl_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange > reserved_range_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> reserved_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::MessageOptions* options_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -1680,10 +1695,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ExtensionRangeOptions* other); @@ -1736,7 +1751,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -1745,7 +1760,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -1756,7 +1771,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -1766,7 +1781,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -1778,7 +1793,7 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -1788,7 +1803,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -1800,7 +1815,7 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -1811,7 +1826,7 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -1824,7 +1839,7 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -1835,7 +1850,7 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -1846,7 +1861,7 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -1857,7 +1872,7 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -1867,7 +1882,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -1878,7 +1893,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -1891,7 +1906,7 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -1903,7 +1918,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -1915,20 +1930,23 @@ ExtensionRangeOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.ExtensionRangeOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -2031,10 +2049,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FieldDescriptorProto* other); @@ -2345,19 +2363,22 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr extendee_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_name_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr default_value_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr json_name_; - ::PROTOBUF_NAMESPACE_ID::FieldOptions* options_; - int32_t number_; - int32_t oneof_index_; - bool proto3_optional_; - int label_; - int type_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr extendee_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr default_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr json_name_; + ::PROTOBUF_NAMESPACE_ID::FieldOptions* options_; + int32_t number_; + int32_t oneof_index_; + bool proto3_optional_; + int label_; + int type_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -2460,10 +2481,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(OneofDescriptorProto* other); @@ -2534,10 +2555,13 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::OneofOptions* options_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::OneofOptions* options_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -2640,10 +2664,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumDescriptorProto_EnumReservedRange* other); @@ -2704,10 +2728,13 @@ 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_; - int32_t start_; - int32_t end_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + int32_t start_; + int32_t end_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -2810,10 +2837,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumDescriptorProto* other); @@ -2949,13 +2976,16 @@ 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::EnumValueDescriptorProto > value_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange > reserved_range_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> reserved_name_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; - ::PROTOBUF_NAMESPACE_ID::EnumOptions* options_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto > value_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange > reserved_range_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> reserved_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::EnumOptions* options_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -3058,10 +3088,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumValueDescriptorProto* other); @@ -3146,11 +3176,14 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* options_; - int32_t number_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* options_; + int32_t number_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -3253,10 +3286,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ServiceDescriptorProto* other); @@ -3346,11 +3379,14 @@ 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::MethodDescriptorProto > method_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; - ::PROTOBUF_NAMESPACE_ID::ServiceOptions* options_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto > method_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::ServiceOptions* options_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -3453,10 +3489,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MethodDescriptorProto* other); @@ -3593,14 +3629,17 @@ 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_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr input_type_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr output_type_; - ::PROTOBUF_NAMESPACE_ID::MethodOptions* options_; - bool client_streaming_; - bool server_streaming_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr input_type_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr output_type_; + ::PROTOBUF_NAMESPACE_ID::MethodOptions* options_; + bool client_streaming_; + bool server_streaming_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -3703,10 +3742,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FileOptions* other); @@ -4121,7 +4160,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -4130,7 +4169,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -4141,7 +4180,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -4151,7 +4190,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -4163,7 +4202,7 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4173,7 +4212,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -4185,7 +4224,7 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4196,7 +4235,7 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4209,7 +4248,7 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -4220,7 +4259,7 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4231,7 +4270,7 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -4242,7 +4281,7 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4252,7 +4291,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -4263,7 +4302,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -4276,7 +4315,7 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -4288,7 +4327,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4300,41 +4339,44 @@ FileOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.FileOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - 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_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr java_package_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr java_outer_classname_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr go_package_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr objc_class_prefix_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr csharp_namespace_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr swift_prefix_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_class_prefix_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_namespace_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_metadata_namespace_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr ruby_package_; - bool java_multiple_files_; - bool java_generate_equals_and_hash_; - bool java_string_check_utf8_; - bool cc_generic_services_; - bool java_generic_services_; - bool py_generic_services_; - bool php_generic_services_; - bool deprecated_; - int optimize_for_; - bool cc_enable_arenas_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::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_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr java_package_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr java_outer_classname_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr go_package_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr objc_class_prefix_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr csharp_namespace_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr swift_prefix_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_class_prefix_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_namespace_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr php_metadata_namespace_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr ruby_package_; + bool java_multiple_files_; + bool java_generate_equals_and_hash_; + bool java_string_check_utf8_; + bool cc_generic_services_; + bool java_generic_services_; + bool py_generic_services_; + bool php_generic_services_; + bool deprecated_; + int optimize_for_; + bool cc_enable_arenas_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -4437,10 +4479,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MessageOptions* other); @@ -4549,7 +4591,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -4558,7 +4600,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -4569,7 +4611,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -4579,7 +4621,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -4591,7 +4633,7 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4601,7 +4643,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -4613,7 +4655,7 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4624,7 +4666,7 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4637,7 +4679,7 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -4648,7 +4690,7 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4659,7 +4701,7 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -4670,7 +4712,7 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4680,7 +4722,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -4691,7 +4733,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -4704,7 +4746,7 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -4716,7 +4758,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -4728,25 +4770,28 @@ MessageOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.MessageOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - 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_; - bool message_set_wire_format_; - bool no_standard_descriptor_accessor_; - bool deprecated_; - bool map_entry_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::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_; + bool message_set_wire_format_; + bool no_standard_descriptor_accessor_; + bool deprecated_; + bool map_entry_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -4849,10 +4894,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FieldOptions* other); @@ -5067,7 +5112,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -5076,7 +5121,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -5087,7 +5132,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -5097,7 +5142,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -5109,7 +5154,7 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5119,7 +5164,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -5131,7 +5176,7 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5142,7 +5187,7 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5155,7 +5200,7 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -5166,7 +5211,7 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5177,7 +5222,7 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -5188,7 +5233,7 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5198,7 +5243,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -5209,7 +5254,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -5222,7 +5267,7 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -5234,7 +5279,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5246,28 +5291,31 @@ FieldOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.FieldOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - 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_; - int ctype_; - int jstype_; - bool packed_; - bool lazy_; - bool unverified_lazy_; - bool deprecated_; - bool weak_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::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_; + int ctype_; + int jstype_; + bool packed_; + bool lazy_; + bool unverified_lazy_; + bool deprecated_; + bool weak_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -5370,10 +5418,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(OneofOptions* other); @@ -5426,7 +5474,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -5435,7 +5483,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -5446,7 +5494,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -5456,7 +5504,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -5468,7 +5516,7 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5478,7 +5526,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -5490,7 +5538,7 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5501,7 +5549,7 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5514,7 +5562,7 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -5525,7 +5573,7 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5536,7 +5584,7 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -5547,7 +5595,7 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5557,7 +5605,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -5568,7 +5616,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -5581,7 +5629,7 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -5593,7 +5641,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5605,20 +5653,23 @@ OneofOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.OneofOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption > uninterpreted_option_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -5721,10 +5772,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumOptions* other); @@ -5805,7 +5856,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -5814,7 +5865,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -5825,7 +5876,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -5835,7 +5886,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -5847,7 +5898,7 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5857,7 +5908,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -5869,7 +5920,7 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5880,7 +5931,7 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5893,7 +5944,7 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -5904,7 +5955,7 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5915,7 +5966,7 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -5926,7 +5977,7 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5936,7 +5987,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -5947,7 +5998,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -5960,7 +6011,7 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -5972,7 +6023,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -5984,23 +6035,26 @@ EnumOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.EnumOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - 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_; - bool allow_alias_; - bool deprecated_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::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_; + bool allow_alias_; + bool deprecated_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -6103,10 +6157,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumValueOptions* other); @@ -6173,7 +6227,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -6182,7 +6236,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -6193,7 +6247,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -6203,7 +6257,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -6215,7 +6269,7 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6225,7 +6279,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -6237,7 +6291,7 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6248,7 +6302,7 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6261,7 +6315,7 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -6272,7 +6326,7 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6283,7 +6337,7 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -6294,7 +6348,7 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6304,7 +6358,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -6315,7 +6369,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -6328,7 +6382,7 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -6340,7 +6394,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6352,22 +6406,25 @@ EnumValueOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.EnumValueOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - 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_; - bool deprecated_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::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_; + bool deprecated_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -6470,10 +6527,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ServiceOptions* other); @@ -6540,7 +6597,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -6549,7 +6606,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -6560,7 +6617,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -6570,7 +6627,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -6582,7 +6639,7 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6592,7 +6649,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -6604,7 +6661,7 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6615,7 +6672,7 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6628,7 +6685,7 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -6639,7 +6696,7 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6650,7 +6707,7 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -6661,7 +6718,7 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6671,7 +6728,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -6682,7 +6739,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -6695,7 +6752,7 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -6707,7 +6764,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -6719,22 +6776,25 @@ ServiceOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.ServiceOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - 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_; - bool deprecated_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::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_; + bool deprecated_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -6837,10 +6897,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(MethodOptions* other); @@ -6953,7 +7013,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.Has(id.number()); + return _impl_._extensions_.Has(id.number()); } template <typename _proto_TypeTraits, @@ -6962,7 +7022,7 @@ inline void ClearExtension( const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { - _extensions_.ClearExtension(id.number()); + _impl_._extensions_.ClearExtension(id.number()); } @@ -6973,7 +7033,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _extensions_.ExtensionSize(id.number()); + return _impl_._extensions_.ExtensionSize(id.number()); } template <typename _proto_TypeTraits, @@ -6983,7 +7043,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, id.default_value()); } @@ -6995,7 +7055,7 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Mutable(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -7005,7 +7065,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::ConstType value) { - _proto_TypeTraits::Set(id.number(), _field_type, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), _field_type, value, &_impl_._extensions_); } @@ -7017,7 +7077,7 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::SetAllocated(id.number(), _field_type, value, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -7028,7 +7088,7 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Singular::MutableType value) { _proto_TypeTraits::UnsafeArenaSetAllocated(id.number(), _field_type, - value, &_extensions_); + value, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -7041,7 +7101,7 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::Release(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, ::PROTOBUF_NAMESPACE_ID::internal::FieldType _field_type, @@ -7052,7 +7112,7 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::UnsafeArenaRelease(id.number(), _field_type, - &_extensions_); + &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -7063,7 +7123,7 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) const { - return _proto_TypeTraits::Get(id.number(), _extensions_, index); + return _proto_TypeTraits::Get(id.number(), _impl_._extensions_, index); } template <typename _proto_TypeTraits, @@ -7074,7 +7134,7 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index) { - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); + return _proto_TypeTraits::Mutable(id.number(), index, &_impl_._extensions_); } template <typename _proto_TypeTraits, @@ -7084,7 +7144,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id, int index, typename _proto_TypeTraits::Repeated::ConstType value) { - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); + _proto_TypeTraits::Set(id.number(), index, value, &_impl_._extensions_); } @@ -7095,7 +7155,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { typename _proto_TypeTraits::Repeated::MutableType to_add = - _proto_TypeTraits::Add(id.number(), _field_type, &_extensions_); + _proto_TypeTraits::Add(id.number(), _field_type, &_impl_._extensions_); return to_add; } @@ -7108,7 +7168,7 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id, typename _proto_TypeTraits::Repeated::ConstType value) { _proto_TypeTraits::Add(id.number(), _field_type, _is_packed, value, - &_extensions_); + &_impl_._extensions_); } @@ -7120,7 +7180,7 @@ const ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) const { - return _proto_TypeTraits::GetRepeated(id.number(), _extensions_); + return _proto_TypeTraits::GetRepeated(id.number(), _impl_._extensions_); } template <typename _proto_TypeTraits, @@ -7132,23 +7192,26 @@ MethodOptions, _proto_TypeTraits, _field_type, _is_packed>& id) { return _proto_TypeTraits::MutableRepeated(id.number(), _field_type, - _is_packed, &_extensions_); + _is_packed, &_impl_._extensions_); } // @@protoc_insertion_point(class_scope:google.protobuf.MethodOptions) private: class _Internal; - ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; - 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_; - bool deprecated_; - int idempotency_level_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ExtensionSet _extensions_; + + ::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_; + bool deprecated_; + int idempotency_level_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -7251,10 +7314,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(UninterpretedOption_NamePart* other); @@ -7323,10 +7386,13 @@ 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_part_; - bool is_extension_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_part_; + bool is_extension_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -7429,10 +7495,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(UninterpretedOption* other); @@ -7585,15 +7651,18 @@ 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_NamePart > name_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr identifier_value_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr aggregate_value_; - uint64_t positive_int_value_; - int64_t negative_int_value_; - double double_value_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart > name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr identifier_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr aggregate_value_; + uint64_t positive_int_value_; + int64_t negative_int_value_; + double double_value_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -7696,10 +7765,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SourceCodeInfo_Location* other); @@ -7841,15 +7910,18 @@ 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::RepeatedField< int32_t > path_; - mutable std::atomic<int> _path_cached_byte_size_; - ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > span_; - mutable std::atomic<int> _span_cached_byte_size_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> leading_detached_comments_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr leading_comments_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr trailing_comments_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > path_; + mutable std::atomic<int> _path_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > span_; + mutable std::atomic<int> _span_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> leading_detached_comments_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr leading_comments_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr trailing_comments_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -7952,10 +8024,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SourceCodeInfo* other); @@ -8009,8 +8081,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location > location_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location > location_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -8113,10 +8188,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GeneratedCodeInfo_Annotation* other); @@ -8219,13 +8294,16 @@ 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::RepeatedField< int32_t > path_; - mutable std::atomic<int> _path_cached_byte_size_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr source_file_; - int32_t begin_; - int32_t end_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::HasBits<1> _has_bits_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > path_; + mutable std::atomic<int> _path_cached_byte_size_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr source_file_; + int32_t begin_; + int32_t end_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // ------------------------------------------------------------------- @@ -8328,10 +8406,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GeneratedCodeInfo* other); @@ -8385,8 +8463,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation > annotation_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation > annotation_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fdescriptor_2eproto; }; // =================================================================== @@ -8402,32 +8483,32 @@ // repeated .google.protobuf.FileDescriptorProto file = 1; inline int FileDescriptorSet::_internal_file_size() const { - return file_.size(); + return _impl_.file_.size(); } inline int FileDescriptorSet::file_size() const { return _internal_file_size(); } inline void FileDescriptorSet::clear_file() { - file_.Clear(); + _impl_.file_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* FileDescriptorSet::mutable_file(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorSet.file) - return file_.Mutable(index); + return _impl_.file_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto >* FileDescriptorSet::mutable_file() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorSet.file) - return &file_; + return &_impl_.file_; } inline const ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto& FileDescriptorSet::_internal_file(int index) const { - return file_.Get(index); + return _impl_.file_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto& FileDescriptorSet::file(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorSet.file) return _internal_file(index); } inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* FileDescriptorSet::_internal_add_file() { - return file_.Add(); + return _impl_.file_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* FileDescriptorSet::add_file() { ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto* _add = _internal_add_file(); @@ -8437,7 +8518,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FileDescriptorProto >& FileDescriptorSet::file() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorSet.file) - return file_; + return _impl_.file_; } // ------------------------------------------------------------------- @@ -8446,15 +8527,15 @@ // optional string name = 1; inline bool FileDescriptorProto::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool FileDescriptorProto::has_name() const { return _internal_has_name(); } inline void FileDescriptorProto::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& FileDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.name) @@ -8463,8 +8544,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileDescriptorProto::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.name) } inline std::string* FileDescriptorProto::mutable_name() { @@ -8473,40 +8554,40 @@ return _s; } inline const std::string& FileDescriptorProto::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void FileDescriptorProto::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* FileDescriptorProto::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* FileDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileDescriptorProto::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.name) @@ -8514,15 +8595,15 @@ // optional string package = 2; inline bool FileDescriptorProto::_internal_has_package() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool FileDescriptorProto::has_package() const { return _internal_has_package(); } inline void FileDescriptorProto::clear_package() { - package_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000002u; + _impl_.package_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& FileDescriptorProto::package() const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.package) @@ -8531,8 +8612,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileDescriptorProto::set_package(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000002u; - package_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.package_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.package) } inline std::string* FileDescriptorProto::mutable_package() { @@ -8541,40 +8622,40 @@ return _s; } inline const std::string& FileDescriptorProto::_internal_package() const { - return package_.Get(); + return _impl_.package_.Get(); } inline void FileDescriptorProto::_internal_set_package(const std::string& value) { - _has_bits_[0] |= 0x00000002u; - package_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.package_.Set(value, GetArenaForAllocation()); } inline std::string* FileDescriptorProto::_internal_mutable_package() { - _has_bits_[0] |= 0x00000002u; - return package_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + return _impl_.package_.Mutable(GetArenaForAllocation()); } inline std::string* FileDescriptorProto::release_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.package) if (!_internal_has_package()) { return nullptr; } - _has_bits_[0] &= ~0x00000002u; - auto* p = package_.Release(); + _impl_._has_bits_[0] &= ~0x00000002u; + auto* p = _impl_.package_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (package_.IsDefault()) { - package_.Set("", GetArenaForAllocation()); + if (_impl_.package_.IsDefault()) { + _impl_.package_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileDescriptorProto::set_allocated_package(std::string* package) { if (package != nullptr) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - package_.SetAllocated(package, GetArenaForAllocation()); + _impl_.package_.SetAllocated(package, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (package_.IsDefault()) { - package_.Set("", GetArenaForAllocation()); + if (_impl_.package_.IsDefault()) { + _impl_.package_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.package) @@ -8582,13 +8663,13 @@ // repeated string dependency = 3; inline int FileDescriptorProto::_internal_dependency_size() const { - return dependency_.size(); + return _impl_.dependency_.size(); } inline int FileDescriptorProto::dependency_size() const { return _internal_dependency_size(); } inline void FileDescriptorProto::clear_dependency() { - dependency_.Clear(); + _impl_.dependency_.Clear(); } inline std::string* FileDescriptorProto::add_dependency() { std::string* _s = _internal_add_dependency(); @@ -8596,7 +8677,7 @@ return _s; } inline const std::string& FileDescriptorProto::_internal_dependency(int index) const { - return dependency_.Get(index); + return _impl_.dependency_.Get(index); } inline const std::string& FileDescriptorProto::dependency(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.dependency) @@ -8604,80 +8685,80 @@ } inline std::string* FileDescriptorProto::mutable_dependency(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.dependency) - return dependency_.Mutable(index); + return _impl_.dependency_.Mutable(index); } inline void FileDescriptorProto::set_dependency(int index, const std::string& value) { - dependency_.Mutable(index)->assign(value); + _impl_.dependency_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.dependency) } inline void FileDescriptorProto::set_dependency(int index, std::string&& value) { - dependency_.Mutable(index)->assign(std::move(value)); + _impl_.dependency_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.dependency) } inline void FileDescriptorProto::set_dependency(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); - dependency_.Mutable(index)->assign(value); + _impl_.dependency_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.FileDescriptorProto.dependency) } inline void FileDescriptorProto::set_dependency(int index, const char* value, size_t size) { - dependency_.Mutable(index)->assign( + _impl_.dependency_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FileDescriptorProto.dependency) } inline std::string* FileDescriptorProto::_internal_add_dependency() { - return dependency_.Add(); + return _impl_.dependency_.Add(); } inline void FileDescriptorProto::add_dependency(const std::string& value) { - dependency_.Add()->assign(value); + _impl_.dependency_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.dependency) } inline void FileDescriptorProto::add_dependency(std::string&& value) { - dependency_.Add(std::move(value)); + _impl_.dependency_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.FileDescriptorProto.dependency) } inline void FileDescriptorProto::add_dependency(const char* value) { GOOGLE_DCHECK(value != nullptr); - dependency_.Add()->assign(value); + _impl_.dependency_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.FileDescriptorProto.dependency) } inline void FileDescriptorProto::add_dependency(const char* value, size_t size) { - dependency_.Add()->assign(reinterpret_cast<const char*>(value), size); + _impl_.dependency_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.FileDescriptorProto.dependency) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& FileDescriptorProto::dependency() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.dependency) - return dependency_; + return _impl_.dependency_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* FileDescriptorProto::mutable_dependency() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.dependency) - return &dependency_; + return &_impl_.dependency_; } // repeated int32 public_dependency = 10; inline int FileDescriptorProto::_internal_public_dependency_size() const { - return public_dependency_.size(); + return _impl_.public_dependency_.size(); } inline int FileDescriptorProto::public_dependency_size() const { return _internal_public_dependency_size(); } inline void FileDescriptorProto::clear_public_dependency() { - public_dependency_.Clear(); + _impl_.public_dependency_.Clear(); } inline int32_t FileDescriptorProto::_internal_public_dependency(int index) const { - return public_dependency_.Get(index); + return _impl_.public_dependency_.Get(index); } inline int32_t FileDescriptorProto::public_dependency(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.public_dependency) return _internal_public_dependency(index); } inline void FileDescriptorProto::set_public_dependency(int index, int32_t value) { - public_dependency_.Set(index, value); + _impl_.public_dependency_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.public_dependency) } inline void FileDescriptorProto::_internal_add_public_dependency(int32_t value) { - public_dependency_.Add(value); + _impl_.public_dependency_.Add(value); } inline void FileDescriptorProto::add_public_dependency(int32_t value) { _internal_add_public_dependency(value); @@ -8685,7 +8766,7 @@ } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& FileDescriptorProto::_internal_public_dependency() const { - return public_dependency_; + return _impl_.public_dependency_; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& FileDescriptorProto::public_dependency() const { @@ -8694,7 +8775,7 @@ } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* FileDescriptorProto::_internal_mutable_public_dependency() { - return &public_dependency_; + return &_impl_.public_dependency_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* FileDescriptorProto::mutable_public_dependency() { @@ -8704,27 +8785,27 @@ // repeated int32 weak_dependency = 11; inline int FileDescriptorProto::_internal_weak_dependency_size() const { - return weak_dependency_.size(); + return _impl_.weak_dependency_.size(); } inline int FileDescriptorProto::weak_dependency_size() const { return _internal_weak_dependency_size(); } inline void FileDescriptorProto::clear_weak_dependency() { - weak_dependency_.Clear(); + _impl_.weak_dependency_.Clear(); } inline int32_t FileDescriptorProto::_internal_weak_dependency(int index) const { - return weak_dependency_.Get(index); + return _impl_.weak_dependency_.Get(index); } inline int32_t FileDescriptorProto::weak_dependency(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.weak_dependency) return _internal_weak_dependency(index); } inline void FileDescriptorProto::set_weak_dependency(int index, int32_t value) { - weak_dependency_.Set(index, value); + _impl_.weak_dependency_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.weak_dependency) } inline void FileDescriptorProto::_internal_add_weak_dependency(int32_t value) { - weak_dependency_.Add(value); + _impl_.weak_dependency_.Add(value); } inline void FileDescriptorProto::add_weak_dependency(int32_t value) { _internal_add_weak_dependency(value); @@ -8732,7 +8813,7 @@ } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& FileDescriptorProto::_internal_weak_dependency() const { - return weak_dependency_; + return _impl_.weak_dependency_; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& FileDescriptorProto::weak_dependency() const { @@ -8741,7 +8822,7 @@ } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* FileDescriptorProto::_internal_mutable_weak_dependency() { - return &weak_dependency_; + return &_impl_.weak_dependency_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* FileDescriptorProto::mutable_weak_dependency() { @@ -8751,32 +8832,32 @@ // repeated .google.protobuf.DescriptorProto message_type = 4; inline int FileDescriptorProto::_internal_message_type_size() const { - return message_type_.size(); + return _impl_.message_type_.size(); } inline int FileDescriptorProto::message_type_size() const { return _internal_message_type_size(); } inline void FileDescriptorProto::clear_message_type() { - message_type_.Clear(); + _impl_.message_type_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto* FileDescriptorProto::mutable_message_type(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.message_type) - return message_type_.Mutable(index); + return _impl_.message_type_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto >* FileDescriptorProto::mutable_message_type() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.message_type) - return &message_type_; + return &_impl_.message_type_; } inline const ::PROTOBUF_NAMESPACE_ID::DescriptorProto& FileDescriptorProto::_internal_message_type(int index) const { - return message_type_.Get(index); + return _impl_.message_type_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::DescriptorProto& FileDescriptorProto::message_type(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.message_type) return _internal_message_type(index); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto* FileDescriptorProto::_internal_add_message_type() { - return message_type_.Add(); + return _impl_.message_type_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto* FileDescriptorProto::add_message_type() { ::PROTOBUF_NAMESPACE_ID::DescriptorProto* _add = _internal_add_message_type(); @@ -8786,37 +8867,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto >& FileDescriptorProto::message_type() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.message_type) - return message_type_; + return _impl_.message_type_; } // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; inline int FileDescriptorProto::_internal_enum_type_size() const { - return enum_type_.size(); + return _impl_.enum_type_.size(); } inline int FileDescriptorProto::enum_type_size() const { return _internal_enum_type_size(); } inline void FileDescriptorProto::clear_enum_type() { - enum_type_.Clear(); + _impl_.enum_type_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* FileDescriptorProto::mutable_enum_type(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.enum_type) - return enum_type_.Mutable(index); + return _impl_.enum_type_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >* FileDescriptorProto::mutable_enum_type() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.enum_type) - return &enum_type_; + return &_impl_.enum_type_; } inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto& FileDescriptorProto::_internal_enum_type(int index) const { - return enum_type_.Get(index); + return _impl_.enum_type_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto& FileDescriptorProto::enum_type(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.enum_type) return _internal_enum_type(index); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* FileDescriptorProto::_internal_add_enum_type() { - return enum_type_.Add(); + return _impl_.enum_type_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* FileDescriptorProto::add_enum_type() { ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* _add = _internal_add_enum_type(); @@ -8826,37 +8907,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >& FileDescriptorProto::enum_type() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.enum_type) - return enum_type_; + return _impl_.enum_type_; } // repeated .google.protobuf.ServiceDescriptorProto service = 6; inline int FileDescriptorProto::_internal_service_size() const { - return service_.size(); + return _impl_.service_.size(); } inline int FileDescriptorProto::service_size() const { return _internal_service_size(); } inline void FileDescriptorProto::clear_service() { - service_.Clear(); + _impl_.service_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* FileDescriptorProto::mutable_service(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.service) - return service_.Mutable(index); + return _impl_.service_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto >* FileDescriptorProto::mutable_service() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.service) - return &service_; + return &_impl_.service_; } inline const ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto& FileDescriptorProto::_internal_service(int index) const { - return service_.Get(index); + return _impl_.service_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto& FileDescriptorProto::service(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.service) return _internal_service(index); } inline ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* FileDescriptorProto::_internal_add_service() { - return service_.Add(); + return _impl_.service_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* FileDescriptorProto::add_service() { ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto* _add = _internal_add_service(); @@ -8866,37 +8947,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::ServiceDescriptorProto >& FileDescriptorProto::service() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.service) - return service_; + return _impl_.service_; } // repeated .google.protobuf.FieldDescriptorProto extension = 7; inline int FileDescriptorProto::_internal_extension_size() const { - return extension_.size(); + return _impl_.extension_.size(); } inline int FileDescriptorProto::extension_size() const { return _internal_extension_size(); } inline void FileDescriptorProto::clear_extension() { - extension_.Clear(); + _impl_.extension_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* FileDescriptorProto::mutable_extension(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileDescriptorProto.extension) - return extension_.Mutable(index); + return _impl_.extension_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* FileDescriptorProto::mutable_extension() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileDescriptorProto.extension) - return &extension_; + return &_impl_.extension_; } inline const ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& FileDescriptorProto::_internal_extension(int index) const { - return extension_.Get(index); + return _impl_.extension_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& FileDescriptorProto::extension(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.extension) return _internal_extension(index); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* FileDescriptorProto::_internal_add_extension() { - return extension_.Add(); + return _impl_.extension_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* FileDescriptorProto::add_extension() { ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* _add = _internal_add_extension(); @@ -8906,24 +8987,24 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& FileDescriptorProto::extension() const { // @@protoc_insertion_point(field_list:google.protobuf.FileDescriptorProto.extension) - return extension_; + return _impl_.extension_; } // optional .google.protobuf.FileOptions options = 8; inline bool FileDescriptorProto::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool FileDescriptorProto::has_options() const { return _internal_has_options(); } inline void FileDescriptorProto::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000008u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000008u; } inline const ::PROTOBUF_NAMESPACE_ID::FileOptions& FileDescriptorProto::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::FileOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::FileOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::FileOptions&>( ::PROTOBUF_NAMESPACE_ID::_FileOptions_default_instance_); } @@ -8934,20 +9015,20 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::FileOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000008u; + _impl_._has_bits_[0] |= 0x00000008u; } else { - _has_bits_[0] &= ~0x00000008u; + _impl_._has_bits_[0] &= ~0x00000008u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FileDescriptorProto.options) } inline ::PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::release_options() { - _has_bits_[0] &= ~0x00000008u; - ::PROTOBUF_NAMESPACE_ID::FileOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000008u; + ::PROTOBUF_NAMESPACE_ID::FileOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -8961,18 +9042,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.options) - _has_bits_[0] &= ~0x00000008u; - ::PROTOBUF_NAMESPACE_ID::FileOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000008u; + ::PROTOBUF_NAMESPACE_ID::FileOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::_internal_mutable_options() { - _has_bits_[0] |= 0x00000008u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000008u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::FileOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::FileOptions* FileDescriptorProto::mutable_options() { ::PROTOBUF_NAMESPACE_ID::FileOptions* _msg = _internal_mutable_options(); @@ -8982,7 +9063,7 @@ inline void FileDescriptorProto::set_allocated_options(::PROTOBUF_NAMESPACE_ID::FileOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -8991,29 +9072,29 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000008u; + _impl_._has_bits_[0] |= 0x00000008u; } else { - _has_bits_[0] &= ~0x00000008u; + _impl_._has_bits_[0] &= ~0x00000008u; } - options_ = options; + _impl_.options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.options) } // optional .google.protobuf.SourceCodeInfo source_code_info = 9; inline bool FileDescriptorProto::_internal_has_source_code_info() const { - bool value = (_has_bits_[0] & 0x00000010u) != 0; - PROTOBUF_ASSUME(!value || source_code_info_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; + PROTOBUF_ASSUME(!value || _impl_.source_code_info_ != nullptr); return value; } inline bool FileDescriptorProto::has_source_code_info() const { return _internal_has_source_code_info(); } inline void FileDescriptorProto::clear_source_code_info() { - if (source_code_info_ != nullptr) source_code_info_->Clear(); - _has_bits_[0] &= ~0x00000010u; + if (_impl_.source_code_info_ != nullptr) _impl_.source_code_info_->Clear(); + _impl_._has_bits_[0] &= ~0x00000010u; } inline const ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo& FileDescriptorProto::_internal_source_code_info() const { - const ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* p = source_code_info_; + const ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* p = _impl_.source_code_info_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo&>( ::PROTOBUF_NAMESPACE_ID::_SourceCodeInfo_default_instance_); } @@ -9024,20 +9105,20 @@ inline void FileDescriptorProto::unsafe_arena_set_allocated_source_code_info( ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_code_info_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_code_info_); } - source_code_info_ = source_code_info; + _impl_.source_code_info_ = source_code_info; if (source_code_info) { - _has_bits_[0] |= 0x00000010u; + _impl_._has_bits_[0] |= 0x00000010u; } else { - _has_bits_[0] &= ~0x00000010u; + _impl_._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() { - _has_bits_[0] &= ~0x00000010u; - ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* temp = source_code_info_; - source_code_info_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000010u; + ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* temp = _impl_.source_code_info_; + _impl_.source_code_info_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -9051,18 +9132,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* FileDescriptorProto::unsafe_arena_release_source_code_info() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.source_code_info) - _has_bits_[0] &= ~0x00000010u; - ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* temp = source_code_info_; - source_code_info_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000010u; + ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* temp = _impl_.source_code_info_; + _impl_.source_code_info_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* FileDescriptorProto::_internal_mutable_source_code_info() { - _has_bits_[0] |= 0x00000010u; - if (source_code_info_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000010u; + if (_impl_.source_code_info_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::SourceCodeInfo>(GetArenaForAllocation()); - source_code_info_ = p; + _impl_.source_code_info_ = p; } - return source_code_info_; + return _impl_.source_code_info_; } inline ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* FileDescriptorProto::mutable_source_code_info() { ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* _msg = _internal_mutable_source_code_info(); @@ -9072,7 +9153,7 @@ inline void FileDescriptorProto::set_allocated_source_code_info(::PROTOBUF_NAMESPACE_ID::SourceCodeInfo* source_code_info) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete source_code_info_; + delete _impl_.source_code_info_; } if (source_code_info) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -9081,25 +9162,25 @@ source_code_info = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, source_code_info, submessage_arena); } - _has_bits_[0] |= 0x00000010u; + _impl_._has_bits_[0] |= 0x00000010u; } else { - _has_bits_[0] &= ~0x00000010u; + _impl_._has_bits_[0] &= ~0x00000010u; } - source_code_info_ = source_code_info; + _impl_.source_code_info_ = source_code_info; // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.source_code_info) } // optional string syntax = 12; inline bool FileDescriptorProto::_internal_has_syntax() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool FileDescriptorProto::has_syntax() const { return _internal_has_syntax(); } inline void FileDescriptorProto::clear_syntax() { - syntax_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000004u; + _impl_.syntax_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000004u; } inline const std::string& FileDescriptorProto::syntax() const { // @@protoc_insertion_point(field_get:google.protobuf.FileDescriptorProto.syntax) @@ -9108,8 +9189,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileDescriptorProto::set_syntax(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000004u; - syntax_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.syntax_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileDescriptorProto.syntax) } inline std::string* FileDescriptorProto::mutable_syntax() { @@ -9118,40 +9199,40 @@ return _s; } inline const std::string& FileDescriptorProto::_internal_syntax() const { - return syntax_.Get(); + return _impl_.syntax_.Get(); } inline void FileDescriptorProto::_internal_set_syntax(const std::string& value) { - _has_bits_[0] |= 0x00000004u; - syntax_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.syntax_.Set(value, GetArenaForAllocation()); } inline std::string* FileDescriptorProto::_internal_mutable_syntax() { - _has_bits_[0] |= 0x00000004u; - return syntax_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + return _impl_.syntax_.Mutable(GetArenaForAllocation()); } inline std::string* FileDescriptorProto::release_syntax() { // @@protoc_insertion_point(field_release:google.protobuf.FileDescriptorProto.syntax) if (!_internal_has_syntax()) { return nullptr; } - _has_bits_[0] &= ~0x00000004u; - auto* p = syntax_.Release(); + _impl_._has_bits_[0] &= ~0x00000004u; + auto* p = _impl_.syntax_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (syntax_.IsDefault()) { - syntax_.Set("", GetArenaForAllocation()); + if (_impl_.syntax_.IsDefault()) { + _impl_.syntax_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileDescriptorProto::set_allocated_syntax(std::string* syntax) { if (syntax != nullptr) { - _has_bits_[0] |= 0x00000004u; + _impl_._has_bits_[0] |= 0x00000004u; } else { - _has_bits_[0] &= ~0x00000004u; + _impl_._has_bits_[0] &= ~0x00000004u; } - syntax_.SetAllocated(syntax, GetArenaForAllocation()); + _impl_.syntax_.SetAllocated(syntax, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (syntax_.IsDefault()) { - syntax_.Set("", GetArenaForAllocation()); + if (_impl_.syntax_.IsDefault()) { + _impl_.syntax_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileDescriptorProto.syntax) @@ -9163,26 +9244,26 @@ // optional int32 start = 1; inline bool DescriptorProto_ExtensionRange::_internal_has_start() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool DescriptorProto_ExtensionRange::has_start() const { return _internal_has_start(); } inline void DescriptorProto_ExtensionRange::clear_start() { - start_ = 0; - _has_bits_[0] &= ~0x00000002u; + _impl_.start_ = 0; + _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t DescriptorProto_ExtensionRange::_internal_start() const { - return start_; + return _impl_.start_; } inline int32_t DescriptorProto_ExtensionRange::start() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.start) return _internal_start(); } inline void DescriptorProto_ExtensionRange::_internal_set_start(int32_t value) { - _has_bits_[0] |= 0x00000002u; - start_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.start_ = value; } inline void DescriptorProto_ExtensionRange::set_start(int32_t value) { _internal_set_start(value); @@ -9191,26 +9272,26 @@ // optional int32 end = 2; inline bool DescriptorProto_ExtensionRange::_internal_has_end() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool DescriptorProto_ExtensionRange::has_end() const { return _internal_has_end(); } inline void DescriptorProto_ExtensionRange::clear_end() { - end_ = 0; - _has_bits_[0] &= ~0x00000004u; + _impl_.end_ = 0; + _impl_._has_bits_[0] &= ~0x00000004u; } inline int32_t DescriptorProto_ExtensionRange::_internal_end() const { - return end_; + return _impl_.end_; } inline int32_t DescriptorProto_ExtensionRange::end() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ExtensionRange.end) return _internal_end(); } inline void DescriptorProto_ExtensionRange::_internal_set_end(int32_t value) { - _has_bits_[0] |= 0x00000004u; - end_ = value; + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.end_ = value; } inline void DescriptorProto_ExtensionRange::set_end(int32_t value) { _internal_set_end(value); @@ -9219,19 +9300,19 @@ // optional .google.protobuf.ExtensionRangeOptions options = 3; inline bool DescriptorProto_ExtensionRange::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool DescriptorProto_ExtensionRange::has_options() const { return _internal_has_options(); } inline void DescriptorProto_ExtensionRange::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000001u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions& DescriptorProto_ExtensionRange::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions&>( ::PROTOBUF_NAMESPACE_ID::_ExtensionRangeOptions_default_instance_); } @@ -9242,20 +9323,20 @@ inline void DescriptorProto_ExtensionRange::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._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() { - _has_bits_[0] &= ~0x00000001u; - ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000001u; + ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -9269,18 +9350,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* DescriptorProto_ExtensionRange::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.ExtensionRange.options) - _has_bits_[0] &= ~0x00000001u; - ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000001u; + ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* DescriptorProto_ExtensionRange::_internal_mutable_options() { - _has_bits_[0] |= 0x00000001u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000001u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* DescriptorProto_ExtensionRange::mutable_options() { ::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* _msg = _internal_mutable_options(); @@ -9290,7 +9371,7 @@ inline void DescriptorProto_ExtensionRange::set_allocated_options(::PROTOBUF_NAMESPACE_ID::ExtensionRangeOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -9299,11 +9380,11 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - options_ = options; + _impl_.options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.ExtensionRange.options) } @@ -9313,26 +9394,26 @@ // optional int32 start = 1; inline bool DescriptorProto_ReservedRange::_internal_has_start() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool DescriptorProto_ReservedRange::has_start() const { return _internal_has_start(); } inline void DescriptorProto_ReservedRange::clear_start() { - start_ = 0; - _has_bits_[0] &= ~0x00000001u; + _impl_.start_ = 0; + _impl_._has_bits_[0] &= ~0x00000001u; } inline int32_t DescriptorProto_ReservedRange::_internal_start() const { - return start_; + return _impl_.start_; } inline int32_t DescriptorProto_ReservedRange::start() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.start) return _internal_start(); } inline void DescriptorProto_ReservedRange::_internal_set_start(int32_t value) { - _has_bits_[0] |= 0x00000001u; - start_ = value; + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.start_ = value; } inline void DescriptorProto_ReservedRange::set_start(int32_t value) { _internal_set_start(value); @@ -9341,26 +9422,26 @@ // optional int32 end = 2; inline bool DescriptorProto_ReservedRange::_internal_has_end() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool DescriptorProto_ReservedRange::has_end() const { return _internal_has_end(); } inline void DescriptorProto_ReservedRange::clear_end() { - end_ = 0; - _has_bits_[0] &= ~0x00000002u; + _impl_.end_ = 0; + _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t DescriptorProto_ReservedRange::_internal_end() const { - return end_; + return _impl_.end_; } inline int32_t DescriptorProto_ReservedRange::end() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.ReservedRange.end) return _internal_end(); } inline void DescriptorProto_ReservedRange::_internal_set_end(int32_t value) { - _has_bits_[0] |= 0x00000002u; - end_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.end_ = value; } inline void DescriptorProto_ReservedRange::set_end(int32_t value) { _internal_set_end(value); @@ -9373,15 +9454,15 @@ // optional string name = 1; inline bool DescriptorProto::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool DescriptorProto::has_name() const { return _internal_has_name(); } inline void DescriptorProto::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& DescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.name) @@ -9390,8 +9471,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void DescriptorProto::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.name) } inline std::string* DescriptorProto::mutable_name() { @@ -9400,40 +9481,40 @@ return _s; } inline const std::string& DescriptorProto::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void DescriptorProto::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* DescriptorProto::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* DescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void DescriptorProto::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.name) @@ -9441,32 +9522,32 @@ // repeated .google.protobuf.FieldDescriptorProto field = 2; inline int DescriptorProto::_internal_field_size() const { - return field_.size(); + return _impl_.field_.size(); } inline int DescriptorProto::field_size() const { return _internal_field_size(); } inline void DescriptorProto::clear_field() { - field_.Clear(); + _impl_.field_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::mutable_field(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.field) - return field_.Mutable(index); + return _impl_.field_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* DescriptorProto::mutable_field() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.field) - return &field_; + return &_impl_.field_; } inline const ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& DescriptorProto::_internal_field(int index) const { - return field_.Get(index); + return _impl_.field_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& DescriptorProto::field(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.field) return _internal_field(index); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::_internal_add_field() { - return field_.Add(); + return _impl_.field_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::add_field() { ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* _add = _internal_add_field(); @@ -9476,37 +9557,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& DescriptorProto::field() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.field) - return field_; + return _impl_.field_; } // repeated .google.protobuf.FieldDescriptorProto extension = 6; inline int DescriptorProto::_internal_extension_size() const { - return extension_.size(); + return _impl_.extension_.size(); } inline int DescriptorProto::extension_size() const { return _internal_extension_size(); } inline void DescriptorProto::clear_extension() { - extension_.Clear(); + _impl_.extension_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::mutable_extension(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.extension) - return extension_.Mutable(index); + return _impl_.extension_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >* DescriptorProto::mutable_extension() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.extension) - return &extension_; + return &_impl_.extension_; } inline const ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& DescriptorProto::_internal_extension(int index) const { - return extension_.Get(index); + return _impl_.extension_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto& DescriptorProto::extension(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension) return _internal_extension(index); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::_internal_add_extension() { - return extension_.Add(); + return _impl_.extension_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* DescriptorProto::add_extension() { ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto* _add = _internal_add_extension(); @@ -9516,37 +9597,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto >& DescriptorProto::extension() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.extension) - return extension_; + return _impl_.extension_; } // repeated .google.protobuf.DescriptorProto nested_type = 3; inline int DescriptorProto::_internal_nested_type_size() const { - return nested_type_.size(); + return _impl_.nested_type_.size(); } inline int DescriptorProto::nested_type_size() const { return _internal_nested_type_size(); } inline void DescriptorProto::clear_nested_type() { - nested_type_.Clear(); + _impl_.nested_type_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto* DescriptorProto::mutable_nested_type(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.nested_type) - return nested_type_.Mutable(index); + return _impl_.nested_type_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto >* DescriptorProto::mutable_nested_type() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.nested_type) - return &nested_type_; + return &_impl_.nested_type_; } inline const ::PROTOBUF_NAMESPACE_ID::DescriptorProto& DescriptorProto::_internal_nested_type(int index) const { - return nested_type_.Get(index); + return _impl_.nested_type_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::DescriptorProto& DescriptorProto::nested_type(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.nested_type) return _internal_nested_type(index); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto* DescriptorProto::_internal_add_nested_type() { - return nested_type_.Add(); + return _impl_.nested_type_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto* DescriptorProto::add_nested_type() { ::PROTOBUF_NAMESPACE_ID::DescriptorProto* _add = _internal_add_nested_type(); @@ -9556,37 +9637,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto >& DescriptorProto::nested_type() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.nested_type) - return nested_type_; + return _impl_.nested_type_; } // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; inline int DescriptorProto::_internal_enum_type_size() const { - return enum_type_.size(); + return _impl_.enum_type_.size(); } inline int DescriptorProto::enum_type_size() const { return _internal_enum_type_size(); } inline void DescriptorProto::clear_enum_type() { - enum_type_.Clear(); + _impl_.enum_type_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* DescriptorProto::mutable_enum_type(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.enum_type) - return enum_type_.Mutable(index); + return _impl_.enum_type_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >* DescriptorProto::mutable_enum_type() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.enum_type) - return &enum_type_; + return &_impl_.enum_type_; } inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto& DescriptorProto::_internal_enum_type(int index) const { - return enum_type_.Get(index); + return _impl_.enum_type_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto& DescriptorProto::enum_type(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.enum_type) return _internal_enum_type(index); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* DescriptorProto::_internal_add_enum_type() { - return enum_type_.Add(); + return _impl_.enum_type_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* DescriptorProto::add_enum_type() { ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto* _add = _internal_add_enum_type(); @@ -9596,37 +9677,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto >& DescriptorProto::enum_type() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.enum_type) - return enum_type_; + return _impl_.enum_type_; } // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; inline int DescriptorProto::_internal_extension_range_size() const { - return extension_range_.size(); + return _impl_.extension_range_.size(); } inline int DescriptorProto::extension_range_size() const { return _internal_extension_range_size(); } inline void DescriptorProto::clear_extension_range() { - extension_range_.Clear(); + _impl_.extension_range_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* DescriptorProto::mutable_extension_range(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.extension_range) - return extension_range_.Mutable(index); + return _impl_.extension_range_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange >* DescriptorProto::mutable_extension_range() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.extension_range) - return &extension_range_; + return &_impl_.extension_range_; } inline const ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange& DescriptorProto::_internal_extension_range(int index) const { - return extension_range_.Get(index); + return _impl_.extension_range_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange& DescriptorProto::extension_range(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.extension_range) return _internal_extension_range(index); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* DescriptorProto::_internal_add_extension_range() { - return extension_range_.Add(); + return _impl_.extension_range_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* DescriptorProto::add_extension_range() { ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange* _add = _internal_add_extension_range(); @@ -9636,37 +9717,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ExtensionRange >& DescriptorProto::extension_range() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.extension_range) - return extension_range_; + return _impl_.extension_range_; } // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; inline int DescriptorProto::_internal_oneof_decl_size() const { - return oneof_decl_.size(); + return _impl_.oneof_decl_.size(); } inline int DescriptorProto::oneof_decl_size() const { return _internal_oneof_decl_size(); } inline void DescriptorProto::clear_oneof_decl() { - oneof_decl_.Clear(); + _impl_.oneof_decl_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* DescriptorProto::mutable_oneof_decl(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.oneof_decl) - return oneof_decl_.Mutable(index); + return _impl_.oneof_decl_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto >* DescriptorProto::mutable_oneof_decl() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.oneof_decl) - return &oneof_decl_; + return &_impl_.oneof_decl_; } inline const ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto& DescriptorProto::_internal_oneof_decl(int index) const { - return oneof_decl_.Get(index); + return _impl_.oneof_decl_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto& DescriptorProto::oneof_decl(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.oneof_decl) return _internal_oneof_decl(index); } inline ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* DescriptorProto::_internal_add_oneof_decl() { - return oneof_decl_.Add(); + return _impl_.oneof_decl_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* DescriptorProto::add_oneof_decl() { ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto* _add = _internal_add_oneof_decl(); @@ -9676,24 +9757,24 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::OneofDescriptorProto >& DescriptorProto::oneof_decl() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.oneof_decl) - return oneof_decl_; + return _impl_.oneof_decl_; } // optional .google.protobuf.MessageOptions options = 7; inline bool DescriptorProto::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool DescriptorProto::has_options() const { return _internal_has_options(); } inline void DescriptorProto::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000002u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const ::PROTOBUF_NAMESPACE_ID::MessageOptions& DescriptorProto::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::MessageOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::MessageOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::MessageOptions&>( ::PROTOBUF_NAMESPACE_ID::_MessageOptions_default_instance_); } @@ -9704,20 +9785,20 @@ inline void DescriptorProto::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::MessageOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.DescriptorProto.options) } inline ::PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::release_options() { - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::MessageOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::MessageOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -9731,18 +9812,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.DescriptorProto.options) - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::MessageOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::MessageOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::_internal_mutable_options() { - _has_bits_[0] |= 0x00000002u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000002u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::MessageOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::MessageOptions* DescriptorProto::mutable_options() { ::PROTOBUF_NAMESPACE_ID::MessageOptions* _msg = _internal_mutable_options(); @@ -9752,7 +9833,7 @@ inline void DescriptorProto::set_allocated_options(::PROTOBUF_NAMESPACE_ID::MessageOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -9761,42 +9842,42 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - options_ = options; + _impl_.options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.DescriptorProto.options) } // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; inline int DescriptorProto::_internal_reserved_range_size() const { - return reserved_range_.size(); + return _impl_.reserved_range_.size(); } inline int DescriptorProto::reserved_range_size() const { return _internal_reserved_range_size(); } inline void DescriptorProto::clear_reserved_range() { - reserved_range_.Clear(); + _impl_.reserved_range_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* DescriptorProto::mutable_reserved_range(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.reserved_range) - return reserved_range_.Mutable(index); + return _impl_.reserved_range_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange >* DescriptorProto::mutable_reserved_range() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_range) - return &reserved_range_; + return &_impl_.reserved_range_; } inline const ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange& DescriptorProto::_internal_reserved_range(int index) const { - return reserved_range_.Get(index); + return _impl_.reserved_range_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange& DescriptorProto::reserved_range(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_range) return _internal_reserved_range(index); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* DescriptorProto::_internal_add_reserved_range() { - return reserved_range_.Add(); + return _impl_.reserved_range_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* DescriptorProto::add_reserved_range() { ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange* _add = _internal_add_reserved_range(); @@ -9806,18 +9887,18 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::DescriptorProto_ReservedRange >& DescriptorProto::reserved_range() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_range) - return reserved_range_; + return _impl_.reserved_range_; } // repeated string reserved_name = 10; inline int DescriptorProto::_internal_reserved_name_size() const { - return reserved_name_.size(); + return _impl_.reserved_name_.size(); } inline int DescriptorProto::reserved_name_size() const { return _internal_reserved_name_size(); } inline void DescriptorProto::clear_reserved_name() { - reserved_name_.Clear(); + _impl_.reserved_name_.Clear(); } inline std::string* DescriptorProto::add_reserved_name() { std::string* _s = _internal_add_reserved_name(); @@ -9825,7 +9906,7 @@ return _s; } inline const std::string& DescriptorProto::_internal_reserved_name(int index) const { - return reserved_name_.Get(index); + return _impl_.reserved_name_.Get(index); } inline const std::string& DescriptorProto::reserved_name(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.DescriptorProto.reserved_name) @@ -9833,55 +9914,55 @@ } inline std::string* DescriptorProto::mutable_reserved_name(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.DescriptorProto.reserved_name) - return reserved_name_.Mutable(index); + return _impl_.reserved_name_.Mutable(index); } inline void DescriptorProto::set_reserved_name(int index, const std::string& value) { - reserved_name_.Mutable(index)->assign(value); + _impl_.reserved_name_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.reserved_name) } inline void DescriptorProto::set_reserved_name(int index, std::string&& value) { - reserved_name_.Mutable(index)->assign(std::move(value)); + _impl_.reserved_name_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:google.protobuf.DescriptorProto.reserved_name) } inline void DescriptorProto::set_reserved_name(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); - reserved_name_.Mutable(index)->assign(value); + _impl_.reserved_name_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.DescriptorProto.reserved_name) } inline void DescriptorProto::set_reserved_name(int index, const char* value, size_t size) { - reserved_name_.Mutable(index)->assign( + _impl_.reserved_name_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.DescriptorProto.reserved_name) } inline std::string* DescriptorProto::_internal_add_reserved_name() { - return reserved_name_.Add(); + return _impl_.reserved_name_.Add(); } inline void DescriptorProto::add_reserved_name(const std::string& value) { - reserved_name_.Add()->assign(value); + _impl_.reserved_name_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_name) } inline void DescriptorProto::add_reserved_name(std::string&& value) { - reserved_name_.Add(std::move(value)); + _impl_.reserved_name_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.DescriptorProto.reserved_name) } inline void DescriptorProto::add_reserved_name(const char* value) { GOOGLE_DCHECK(value != nullptr); - reserved_name_.Add()->assign(value); + _impl_.reserved_name_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.DescriptorProto.reserved_name) } inline void DescriptorProto::add_reserved_name(const char* value, size_t size) { - reserved_name_.Add()->assign(reinterpret_cast<const char*>(value), size); + _impl_.reserved_name_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.DescriptorProto.reserved_name) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& DescriptorProto::reserved_name() const { // @@protoc_insertion_point(field_list:google.protobuf.DescriptorProto.reserved_name) - return reserved_name_; + return _impl_.reserved_name_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* DescriptorProto::mutable_reserved_name() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.DescriptorProto.reserved_name) - return &reserved_name_; + return &_impl_.reserved_name_; } // ------------------------------------------------------------------- @@ -9890,32 +9971,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int ExtensionRangeOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int ExtensionRangeOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void ExtensionRangeOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* ExtensionRangeOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.ExtensionRangeOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* ExtensionRangeOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.ExtensionRangeOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& ExtensionRangeOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& ExtensionRangeOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.ExtensionRangeOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* ExtensionRangeOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* ExtensionRangeOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -9925,7 +10006,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& ExtensionRangeOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.ExtensionRangeOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -9934,15 +10015,15 @@ // optional string name = 1; inline bool FieldDescriptorProto::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool FieldDescriptorProto::has_name() const { return _internal_has_name(); } inline void FieldDescriptorProto::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& FieldDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.name) @@ -9951,8 +10032,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FieldDescriptorProto::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.name) } inline std::string* FieldDescriptorProto::mutable_name() { @@ -9961,40 +10042,40 @@ return _s; } inline const std::string& FieldDescriptorProto::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void FieldDescriptorProto::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FieldDescriptorProto::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.name) @@ -10002,26 +10083,26 @@ // optional int32 number = 3; inline bool FieldDescriptorProto::_internal_has_number() const { - bool value = (_has_bits_[0] & 0x00000040u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000040u) != 0; return value; } inline bool FieldDescriptorProto::has_number() const { return _internal_has_number(); } inline void FieldDescriptorProto::clear_number() { - number_ = 0; - _has_bits_[0] &= ~0x00000040u; + _impl_.number_ = 0; + _impl_._has_bits_[0] &= ~0x00000040u; } inline int32_t FieldDescriptorProto::_internal_number() const { - return number_; + return _impl_.number_; } inline int32_t FieldDescriptorProto::number() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.number) return _internal_number(); } inline void FieldDescriptorProto::_internal_set_number(int32_t value) { - _has_bits_[0] |= 0x00000040u; - number_ = value; + _impl_._has_bits_[0] |= 0x00000040u; + _impl_.number_ = value; } inline void FieldDescriptorProto::set_number(int32_t value) { _internal_set_number(value); @@ -10030,18 +10111,18 @@ // optional .google.protobuf.FieldDescriptorProto.Label label = 4; inline bool FieldDescriptorProto::_internal_has_label() const { - bool value = (_has_bits_[0] & 0x00000200u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000200u) != 0; return value; } inline bool FieldDescriptorProto::has_label() const { return _internal_has_label(); } inline void FieldDescriptorProto::clear_label() { - label_ = 1; - _has_bits_[0] &= ~0x00000200u; + _impl_.label_ = 1; + _impl_._has_bits_[0] &= ~0x00000200u; } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label FieldDescriptorProto::_internal_label() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label >(label_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label >(_impl_.label_); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label FieldDescriptorProto::label() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.label) @@ -10049,8 +10130,8 @@ } inline void FieldDescriptorProto::_internal_set_label(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label value) { assert(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label_IsValid(value)); - _has_bits_[0] |= 0x00000200u; - label_ = value; + _impl_._has_bits_[0] |= 0x00000200u; + _impl_.label_ = value; } inline void FieldDescriptorProto::set_label(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Label value) { _internal_set_label(value); @@ -10059,18 +10140,18 @@ // optional .google.protobuf.FieldDescriptorProto.Type type = 5; inline bool FieldDescriptorProto::_internal_has_type() const { - bool value = (_has_bits_[0] & 0x00000400u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000400u) != 0; return value; } inline bool FieldDescriptorProto::has_type() const { return _internal_has_type(); } inline void FieldDescriptorProto::clear_type() { - type_ = 1; - _has_bits_[0] &= ~0x00000400u; + _impl_.type_ = 1; + _impl_._has_bits_[0] &= ~0x00000400u; } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type FieldDescriptorProto::_internal_type() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type >(type_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type >(_impl_.type_); } inline ::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type FieldDescriptorProto::type() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type) @@ -10078,8 +10159,8 @@ } inline void FieldDescriptorProto::_internal_set_type(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type value) { assert(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type_IsValid(value)); - _has_bits_[0] |= 0x00000400u; - type_ = value; + _impl_._has_bits_[0] |= 0x00000400u; + _impl_.type_ = value; } inline void FieldDescriptorProto::set_type(::PROTOBUF_NAMESPACE_ID::FieldDescriptorProto_Type value) { _internal_set_type(value); @@ -10088,15 +10169,15 @@ // optional string type_name = 6; inline bool FieldDescriptorProto::_internal_has_type_name() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool FieldDescriptorProto::has_type_name() const { return _internal_has_type_name(); } inline void FieldDescriptorProto::clear_type_name() { - type_name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000004u; + _impl_.type_name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000004u; } inline const std::string& FieldDescriptorProto::type_name() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.type_name) @@ -10105,8 +10186,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FieldDescriptorProto::set_type_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000004u; - type_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.type_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.type_name) } inline std::string* FieldDescriptorProto::mutable_type_name() { @@ -10115,40 +10196,40 @@ return _s; } inline const std::string& FieldDescriptorProto::_internal_type_name() const { - return type_name_.Get(); + return _impl_.type_name_.Get(); } inline void FieldDescriptorProto::_internal_set_type_name(const std::string& value) { - _has_bits_[0] |= 0x00000004u; - type_name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.type_name_.Set(value, GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::_internal_mutable_type_name() { - _has_bits_[0] |= 0x00000004u; - return type_name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + return _impl_.type_name_.Mutable(GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::release_type_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.type_name) if (!_internal_has_type_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000004u; - auto* p = type_name_.Release(); + _impl_._has_bits_[0] &= ~0x00000004u; + auto* p = _impl_.type_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (type_name_.IsDefault()) { - type_name_.Set("", GetArenaForAllocation()); + if (_impl_.type_name_.IsDefault()) { + _impl_.type_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FieldDescriptorProto::set_allocated_type_name(std::string* type_name) { if (type_name != nullptr) { - _has_bits_[0] |= 0x00000004u; + _impl_._has_bits_[0] |= 0x00000004u; } else { - _has_bits_[0] &= ~0x00000004u; + _impl_._has_bits_[0] &= ~0x00000004u; } - type_name_.SetAllocated(type_name, GetArenaForAllocation()); + _impl_.type_name_.SetAllocated(type_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (type_name_.IsDefault()) { - type_name_.Set("", GetArenaForAllocation()); + if (_impl_.type_name_.IsDefault()) { + _impl_.type_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.type_name) @@ -10156,15 +10237,15 @@ // optional string extendee = 2; inline bool FieldDescriptorProto::_internal_has_extendee() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool FieldDescriptorProto::has_extendee() const { return _internal_has_extendee(); } inline void FieldDescriptorProto::clear_extendee() { - extendee_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000002u; + _impl_.extendee_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& FieldDescriptorProto::extendee() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.extendee) @@ -10173,8 +10254,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FieldDescriptorProto::set_extendee(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000002u; - extendee_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.extendee_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.extendee) } inline std::string* FieldDescriptorProto::mutable_extendee() { @@ -10183,40 +10264,40 @@ return _s; } inline const std::string& FieldDescriptorProto::_internal_extendee() const { - return extendee_.Get(); + return _impl_.extendee_.Get(); } inline void FieldDescriptorProto::_internal_set_extendee(const std::string& value) { - _has_bits_[0] |= 0x00000002u; - extendee_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.extendee_.Set(value, GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::_internal_mutable_extendee() { - _has_bits_[0] |= 0x00000002u; - return extendee_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + return _impl_.extendee_.Mutable(GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::release_extendee() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.extendee) if (!_internal_has_extendee()) { return nullptr; } - _has_bits_[0] &= ~0x00000002u; - auto* p = extendee_.Release(); + _impl_._has_bits_[0] &= ~0x00000002u; + auto* p = _impl_.extendee_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (extendee_.IsDefault()) { - extendee_.Set("", GetArenaForAllocation()); + if (_impl_.extendee_.IsDefault()) { + _impl_.extendee_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FieldDescriptorProto::set_allocated_extendee(std::string* extendee) { if (extendee != nullptr) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - extendee_.SetAllocated(extendee, GetArenaForAllocation()); + _impl_.extendee_.SetAllocated(extendee, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (extendee_.IsDefault()) { - extendee_.Set("", GetArenaForAllocation()); + if (_impl_.extendee_.IsDefault()) { + _impl_.extendee_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.extendee) @@ -10224,15 +10305,15 @@ // optional string default_value = 7; inline bool FieldDescriptorProto::_internal_has_default_value() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool FieldDescriptorProto::has_default_value() const { return _internal_has_default_value(); } inline void FieldDescriptorProto::clear_default_value() { - default_value_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000008u; + _impl_.default_value_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000008u; } inline const std::string& FieldDescriptorProto::default_value() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.default_value) @@ -10241,8 +10322,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FieldDescriptorProto::set_default_value(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000008u; - default_value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000008u; + _impl_.default_value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.default_value) } inline std::string* FieldDescriptorProto::mutable_default_value() { @@ -10251,40 +10332,40 @@ return _s; } inline const std::string& FieldDescriptorProto::_internal_default_value() const { - return default_value_.Get(); + return _impl_.default_value_.Get(); } inline void FieldDescriptorProto::_internal_set_default_value(const std::string& value) { - _has_bits_[0] |= 0x00000008u; - default_value_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000008u; + _impl_.default_value_.Set(value, GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::_internal_mutable_default_value() { - _has_bits_[0] |= 0x00000008u; - return default_value_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000008u; + return _impl_.default_value_.Mutable(GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::release_default_value() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.default_value) if (!_internal_has_default_value()) { return nullptr; } - _has_bits_[0] &= ~0x00000008u; - auto* p = default_value_.Release(); + _impl_._has_bits_[0] &= ~0x00000008u; + auto* p = _impl_.default_value_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (default_value_.IsDefault()) { - default_value_.Set("", GetArenaForAllocation()); + if (_impl_.default_value_.IsDefault()) { + _impl_.default_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FieldDescriptorProto::set_allocated_default_value(std::string* default_value) { if (default_value != nullptr) { - _has_bits_[0] |= 0x00000008u; + _impl_._has_bits_[0] |= 0x00000008u; } else { - _has_bits_[0] &= ~0x00000008u; + _impl_._has_bits_[0] &= ~0x00000008u; } - default_value_.SetAllocated(default_value, GetArenaForAllocation()); + _impl_.default_value_.SetAllocated(default_value, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (default_value_.IsDefault()) { - default_value_.Set("", GetArenaForAllocation()); + if (_impl_.default_value_.IsDefault()) { + _impl_.default_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.default_value) @@ -10292,26 +10373,26 @@ // optional int32 oneof_index = 9; inline bool FieldDescriptorProto::_internal_has_oneof_index() const { - bool value = (_has_bits_[0] & 0x00000080u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000080u) != 0; return value; } inline bool FieldDescriptorProto::has_oneof_index() const { return _internal_has_oneof_index(); } inline void FieldDescriptorProto::clear_oneof_index() { - oneof_index_ = 0; - _has_bits_[0] &= ~0x00000080u; + _impl_.oneof_index_ = 0; + _impl_._has_bits_[0] &= ~0x00000080u; } inline int32_t FieldDescriptorProto::_internal_oneof_index() const { - return oneof_index_; + return _impl_.oneof_index_; } inline int32_t FieldDescriptorProto::oneof_index() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.oneof_index) return _internal_oneof_index(); } inline void FieldDescriptorProto::_internal_set_oneof_index(int32_t value) { - _has_bits_[0] |= 0x00000080u; - oneof_index_ = value; + _impl_._has_bits_[0] |= 0x00000080u; + _impl_.oneof_index_ = value; } inline void FieldDescriptorProto::set_oneof_index(int32_t value) { _internal_set_oneof_index(value); @@ -10320,15 +10401,15 @@ // optional string json_name = 10; inline bool FieldDescriptorProto::_internal_has_json_name() const { - bool value = (_has_bits_[0] & 0x00000010u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool FieldDescriptorProto::has_json_name() const { return _internal_has_json_name(); } inline void FieldDescriptorProto::clear_json_name() { - json_name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000010u; + _impl_.json_name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000010u; } inline const std::string& FieldDescriptorProto::json_name() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldDescriptorProto.json_name) @@ -10337,8 +10418,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FieldDescriptorProto::set_json_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000010u; - json_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000010u; + _impl_.json_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FieldDescriptorProto.json_name) } inline std::string* FieldDescriptorProto::mutable_json_name() { @@ -10347,40 +10428,40 @@ return _s; } inline const std::string& FieldDescriptorProto::_internal_json_name() const { - return json_name_.Get(); + return _impl_.json_name_.Get(); } inline void FieldDescriptorProto::_internal_set_json_name(const std::string& value) { - _has_bits_[0] |= 0x00000010u; - json_name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000010u; + _impl_.json_name_.Set(value, GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::_internal_mutable_json_name() { - _has_bits_[0] |= 0x00000010u; - return json_name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000010u; + return _impl_.json_name_.Mutable(GetArenaForAllocation()); } inline std::string* FieldDescriptorProto::release_json_name() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.json_name) if (!_internal_has_json_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000010u; - auto* p = json_name_.Release(); + _impl_._has_bits_[0] &= ~0x00000010u; + auto* p = _impl_.json_name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (json_name_.IsDefault()) { - json_name_.Set("", GetArenaForAllocation()); + if (_impl_.json_name_.IsDefault()) { + _impl_.json_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FieldDescriptorProto::set_allocated_json_name(std::string* json_name) { if (json_name != nullptr) { - _has_bits_[0] |= 0x00000010u; + _impl_._has_bits_[0] |= 0x00000010u; } else { - _has_bits_[0] &= ~0x00000010u; + _impl_._has_bits_[0] &= ~0x00000010u; } - json_name_.SetAllocated(json_name, GetArenaForAllocation()); + _impl_.json_name_.SetAllocated(json_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (json_name_.IsDefault()) { - json_name_.Set("", GetArenaForAllocation()); + if (_impl_.json_name_.IsDefault()) { + _impl_.json_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FieldDescriptorProto.json_name) @@ -10388,19 +10469,19 @@ // optional .google.protobuf.FieldOptions options = 8; inline bool FieldDescriptorProto::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000020u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000020u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool FieldDescriptorProto::has_options() const { return _internal_has_options(); } inline void FieldDescriptorProto::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000020u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000020u; } inline const ::PROTOBUF_NAMESPACE_ID::FieldOptions& FieldDescriptorProto::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::FieldOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::FieldOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::FieldOptions&>( ::PROTOBUF_NAMESPACE_ID::_FieldOptions_default_instance_); } @@ -10411,20 +10492,20 @@ inline void FieldDescriptorProto::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::FieldOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000020u; + _impl_._has_bits_[0] |= 0x00000020u; } else { - _has_bits_[0] &= ~0x00000020u; + _impl_._has_bits_[0] &= ~0x00000020u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.FieldDescriptorProto.options) } inline ::PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::release_options() { - _has_bits_[0] &= ~0x00000020u; - ::PROTOBUF_NAMESPACE_ID::FieldOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000020u; + ::PROTOBUF_NAMESPACE_ID::FieldOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -10438,18 +10519,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.FieldDescriptorProto.options) - _has_bits_[0] &= ~0x00000020u; - ::PROTOBUF_NAMESPACE_ID::FieldOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000020u; + ::PROTOBUF_NAMESPACE_ID::FieldOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::_internal_mutable_options() { - _has_bits_[0] |= 0x00000020u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000020u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::FieldOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::FieldOptions* FieldDescriptorProto::mutable_options() { ::PROTOBUF_NAMESPACE_ID::FieldOptions* _msg = _internal_mutable_options(); @@ -10459,7 +10540,7 @@ inline void FieldDescriptorProto::set_allocated_options(::PROTOBUF_NAMESPACE_ID::FieldOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -10468,36 +10549,36 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000020u; + _impl_._has_bits_[0] |= 0x00000020u; } else { - _has_bits_[0] &= ~0x00000020u; + _impl_._has_bits_[0] &= ~0x00000020u; } - options_ = options; + _impl_.options_ = options; // @@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; + bool value = (_impl_._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; + _impl_.proto3_optional_ = false; + _impl_._has_bits_[0] &= ~0x00000100u; } inline bool FieldDescriptorProto::_internal_proto3_optional() const { - return proto3_optional_; + return _impl_.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; + _impl_._has_bits_[0] |= 0x00000100u; + _impl_.proto3_optional_ = value; } inline void FieldDescriptorProto::set_proto3_optional(bool value) { _internal_set_proto3_optional(value); @@ -10510,15 +10591,15 @@ // optional string name = 1; inline bool OneofDescriptorProto::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool OneofDescriptorProto::has_name() const { return _internal_has_name(); } inline void OneofDescriptorProto::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& OneofDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.OneofDescriptorProto.name) @@ -10527,8 +10608,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void OneofDescriptorProto::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.OneofDescriptorProto.name) } inline std::string* OneofDescriptorProto::mutable_name() { @@ -10537,40 +10618,40 @@ return _s; } inline const std::string& OneofDescriptorProto::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void OneofDescriptorProto::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* OneofDescriptorProto::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* OneofDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void OneofDescriptorProto::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.name) @@ -10578,19 +10659,19 @@ // optional .google.protobuf.OneofOptions options = 2; inline bool OneofDescriptorProto::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool OneofDescriptorProto::has_options() const { return _internal_has_options(); } inline void OneofDescriptorProto::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000002u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const ::PROTOBUF_NAMESPACE_ID::OneofOptions& OneofDescriptorProto::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::OneofOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::OneofOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::OneofOptions&>( ::PROTOBUF_NAMESPACE_ID::_OneofOptions_default_instance_); } @@ -10601,20 +10682,20 @@ inline void OneofDescriptorProto::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::OneofOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.OneofDescriptorProto.options) } inline ::PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::release_options() { - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::OneofOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::OneofOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -10628,18 +10709,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.OneofDescriptorProto.options) - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::OneofOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::OneofOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::_internal_mutable_options() { - _has_bits_[0] |= 0x00000002u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000002u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::OneofOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::OneofOptions* OneofDescriptorProto::mutable_options() { ::PROTOBUF_NAMESPACE_ID::OneofOptions* _msg = _internal_mutable_options(); @@ -10649,7 +10730,7 @@ inline void OneofDescriptorProto::set_allocated_options(::PROTOBUF_NAMESPACE_ID::OneofOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -10658,11 +10739,11 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - options_ = options; + _impl_.options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.OneofDescriptorProto.options) } @@ -10672,26 +10753,26 @@ // optional int32 start = 1; inline bool EnumDescriptorProto_EnumReservedRange::_internal_has_start() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool EnumDescriptorProto_EnumReservedRange::has_start() const { return _internal_has_start(); } inline void EnumDescriptorProto_EnumReservedRange::clear_start() { - start_ = 0; - _has_bits_[0] &= ~0x00000001u; + _impl_.start_ = 0; + _impl_._has_bits_[0] &= ~0x00000001u; } inline int32_t EnumDescriptorProto_EnumReservedRange::_internal_start() const { - return start_; + return _impl_.start_; } inline int32_t EnumDescriptorProto_EnumReservedRange::start() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.EnumReservedRange.start) return _internal_start(); } inline void EnumDescriptorProto_EnumReservedRange::_internal_set_start(int32_t value) { - _has_bits_[0] |= 0x00000001u; - start_ = value; + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.start_ = value; } inline void EnumDescriptorProto_EnumReservedRange::set_start(int32_t value) { _internal_set_start(value); @@ -10700,26 +10781,26 @@ // optional int32 end = 2; inline bool EnumDescriptorProto_EnumReservedRange::_internal_has_end() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool EnumDescriptorProto_EnumReservedRange::has_end() const { return _internal_has_end(); } inline void EnumDescriptorProto_EnumReservedRange::clear_end() { - end_ = 0; - _has_bits_[0] &= ~0x00000002u; + _impl_.end_ = 0; + _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t EnumDescriptorProto_EnumReservedRange::_internal_end() const { - return end_; + return _impl_.end_; } inline int32_t EnumDescriptorProto_EnumReservedRange::end() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.EnumReservedRange.end) return _internal_end(); } inline void EnumDescriptorProto_EnumReservedRange::_internal_set_end(int32_t value) { - _has_bits_[0] |= 0x00000002u; - end_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.end_ = value; } inline void EnumDescriptorProto_EnumReservedRange::set_end(int32_t value) { _internal_set_end(value); @@ -10732,15 +10813,15 @@ // optional string name = 1; inline bool EnumDescriptorProto::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool EnumDescriptorProto::has_name() const { return _internal_has_name(); } inline void EnumDescriptorProto::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& EnumDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.name) @@ -10749,8 +10830,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void EnumDescriptorProto::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.name) } inline std::string* EnumDescriptorProto::mutable_name() { @@ -10759,40 +10840,40 @@ return _s; } inline const std::string& EnumDescriptorProto::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void EnumDescriptorProto::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* EnumDescriptorProto::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* EnumDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void EnumDescriptorProto::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.name) @@ -10800,32 +10881,32 @@ // repeated .google.protobuf.EnumValueDescriptorProto value = 2; inline int EnumDescriptorProto::_internal_value_size() const { - return value_.size(); + return _impl_.value_.size(); } inline int EnumDescriptorProto::value_size() const { return _internal_value_size(); } inline void EnumDescriptorProto::clear_value() { - value_.Clear(); + _impl_.value_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* EnumDescriptorProto::mutable_value(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.value) - return value_.Mutable(index); + return _impl_.value_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto >* EnumDescriptorProto::mutable_value() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.value) - return &value_; + return &_impl_.value_; } inline const ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto& EnumDescriptorProto::_internal_value(int index) const { - return value_.Get(index); + return _impl_.value_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto& EnumDescriptorProto::value(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.value) return _internal_value(index); } inline ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* EnumDescriptorProto::_internal_add_value() { - return value_.Add(); + return _impl_.value_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* EnumDescriptorProto::add_value() { ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto* _add = _internal_add_value(); @@ -10835,24 +10916,24 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValueDescriptorProto >& EnumDescriptorProto::value() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.value) - return value_; + return _impl_.value_; } // optional .google.protobuf.EnumOptions options = 3; inline bool EnumDescriptorProto::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool EnumDescriptorProto::has_options() const { return _internal_has_options(); } inline void EnumDescriptorProto::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000002u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const ::PROTOBUF_NAMESPACE_ID::EnumOptions& EnumDescriptorProto::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::EnumOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::EnumOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::EnumOptions&>( ::PROTOBUF_NAMESPACE_ID::_EnumOptions_default_instance_); } @@ -10863,20 +10944,20 @@ inline void EnumDescriptorProto::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::EnumOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumDescriptorProto.options) } inline ::PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::release_options() { - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::EnumOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::EnumOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -10890,18 +10971,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.EnumDescriptorProto.options) - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::EnumOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::EnumOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::_internal_mutable_options() { - _has_bits_[0] |= 0x00000002u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000002u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::EnumOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::EnumOptions* EnumDescriptorProto::mutable_options() { ::PROTOBUF_NAMESPACE_ID::EnumOptions* _msg = _internal_mutable_options(); @@ -10911,7 +10992,7 @@ inline void EnumDescriptorProto::set_allocated_options(::PROTOBUF_NAMESPACE_ID::EnumOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -10920,42 +11001,42 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - options_ = options; + _impl_.options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumDescriptorProto.options) } // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; inline int EnumDescriptorProto::_internal_reserved_range_size() const { - return reserved_range_.size(); + return _impl_.reserved_range_.size(); } inline int EnumDescriptorProto::reserved_range_size() const { return _internal_reserved_range_size(); } inline void EnumDescriptorProto::clear_reserved_range() { - reserved_range_.Clear(); + _impl_.reserved_range_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::mutable_reserved_range(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.reserved_range) - return reserved_range_.Mutable(index); + return _impl_.reserved_range_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange >* EnumDescriptorProto::mutable_reserved_range() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.reserved_range) - return &reserved_range_; + return &_impl_.reserved_range_; } inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto::_internal_reserved_range(int index) const { - return reserved_range_.Get(index); + return _impl_.reserved_range_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange& EnumDescriptorProto::reserved_range(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.reserved_range) return _internal_reserved_range(index); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::_internal_add_reserved_range() { - return reserved_range_.Add(); + return _impl_.reserved_range_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* EnumDescriptorProto::add_reserved_range() { ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange* _add = _internal_add_reserved_range(); @@ -10965,18 +11046,18 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumDescriptorProto_EnumReservedRange >& EnumDescriptorProto::reserved_range() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.reserved_range) - return reserved_range_; + return _impl_.reserved_range_; } // repeated string reserved_name = 5; inline int EnumDescriptorProto::_internal_reserved_name_size() const { - return reserved_name_.size(); + return _impl_.reserved_name_.size(); } inline int EnumDescriptorProto::reserved_name_size() const { return _internal_reserved_name_size(); } inline void EnumDescriptorProto::clear_reserved_name() { - reserved_name_.Clear(); + _impl_.reserved_name_.Clear(); } inline std::string* EnumDescriptorProto::add_reserved_name() { std::string* _s = _internal_add_reserved_name(); @@ -10984,7 +11065,7 @@ return _s; } inline const std::string& EnumDescriptorProto::_internal_reserved_name(int index) const { - return reserved_name_.Get(index); + return _impl_.reserved_name_.Get(index); } inline const std::string& EnumDescriptorProto::reserved_name(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumDescriptorProto.reserved_name) @@ -10992,55 +11073,55 @@ } inline std::string* EnumDescriptorProto::mutable_reserved_name(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumDescriptorProto.reserved_name) - return reserved_name_.Mutable(index); + return _impl_.reserved_name_.Mutable(index); } inline void EnumDescriptorProto::set_reserved_name(int index, const std::string& value) { - reserved_name_.Mutable(index)->assign(value); + _impl_.reserved_name_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.reserved_name) } inline void EnumDescriptorProto::set_reserved_name(int index, std::string&& value) { - reserved_name_.Mutable(index)->assign(std::move(value)); + _impl_.reserved_name_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:google.protobuf.EnumDescriptorProto.reserved_name) } inline void EnumDescriptorProto::set_reserved_name(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); - reserved_name_.Mutable(index)->assign(value); + _impl_.reserved_name_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.EnumDescriptorProto.reserved_name) } inline void EnumDescriptorProto::set_reserved_name(int index, const char* value, size_t size) { - reserved_name_.Mutable(index)->assign( + _impl_.reserved_name_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.EnumDescriptorProto.reserved_name) } inline std::string* EnumDescriptorProto::_internal_add_reserved_name() { - return reserved_name_.Add(); + return _impl_.reserved_name_.Add(); } inline void EnumDescriptorProto::add_reserved_name(const std::string& value) { - reserved_name_.Add()->assign(value); + _impl_.reserved_name_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_name) } inline void EnumDescriptorProto::add_reserved_name(std::string&& value) { - reserved_name_.Add(std::move(value)); + _impl_.reserved_name_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.EnumDescriptorProto.reserved_name) } inline void EnumDescriptorProto::add_reserved_name(const char* value) { GOOGLE_DCHECK(value != nullptr); - reserved_name_.Add()->assign(value); + _impl_.reserved_name_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.EnumDescriptorProto.reserved_name) } inline void EnumDescriptorProto::add_reserved_name(const char* value, size_t size) { - reserved_name_.Add()->assign(reinterpret_cast<const char*>(value), size); + _impl_.reserved_name_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.EnumDescriptorProto.reserved_name) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& EnumDescriptorProto::reserved_name() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumDescriptorProto.reserved_name) - return reserved_name_; + return _impl_.reserved_name_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* EnumDescriptorProto::mutable_reserved_name() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumDescriptorProto.reserved_name) - return &reserved_name_; + return &_impl_.reserved_name_; } // ------------------------------------------------------------------- @@ -11049,15 +11130,15 @@ // optional string name = 1; inline bool EnumValueDescriptorProto::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool EnumValueDescriptorProto::has_name() const { return _internal_has_name(); } inline void EnumValueDescriptorProto::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& EnumValueDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.name) @@ -11066,8 +11147,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void EnumValueDescriptorProto::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.EnumValueDescriptorProto.name) } inline std::string* EnumValueDescriptorProto::mutable_name() { @@ -11076,40 +11157,40 @@ return _s; } inline const std::string& EnumValueDescriptorProto::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void EnumValueDescriptorProto::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* EnumValueDescriptorProto::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* EnumValueDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void EnumValueDescriptorProto::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.name) @@ -11117,26 +11198,26 @@ // optional int32 number = 2; inline bool EnumValueDescriptorProto::_internal_has_number() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool EnumValueDescriptorProto::has_number() const { return _internal_has_number(); } inline void EnumValueDescriptorProto::clear_number() { - number_ = 0; - _has_bits_[0] &= ~0x00000004u; + _impl_.number_ = 0; + _impl_._has_bits_[0] &= ~0x00000004u; } inline int32_t EnumValueDescriptorProto::_internal_number() const { - return number_; + return _impl_.number_; } inline int32_t EnumValueDescriptorProto::number() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValueDescriptorProto.number) return _internal_number(); } inline void EnumValueDescriptorProto::_internal_set_number(int32_t value) { - _has_bits_[0] |= 0x00000004u; - number_ = value; + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.number_ = value; } inline void EnumValueDescriptorProto::set_number(int32_t value) { _internal_set_number(value); @@ -11145,19 +11226,19 @@ // optional .google.protobuf.EnumValueOptions options = 3; inline bool EnumValueDescriptorProto::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool EnumValueDescriptorProto::has_options() const { return _internal_has_options(); } inline void EnumValueDescriptorProto::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000002u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const ::PROTOBUF_NAMESPACE_ID::EnumValueOptions& EnumValueDescriptorProto::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::EnumValueOptions&>( ::PROTOBUF_NAMESPACE_ID::_EnumValueOptions_default_instance_); } @@ -11168,20 +11249,20 @@ inline void EnumValueDescriptorProto::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.EnumValueDescriptorProto.options) } inline ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::release_options() { - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -11195,18 +11276,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.EnumValueDescriptorProto.options) - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::_internal_mutable_options() { - _has_bits_[0] |= 0x00000002u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000002u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::EnumValueOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* EnumValueDescriptorProto::mutable_options() { ::PROTOBUF_NAMESPACE_ID::EnumValueOptions* _msg = _internal_mutable_options(); @@ -11216,7 +11297,7 @@ inline void EnumValueDescriptorProto::set_allocated_options(::PROTOBUF_NAMESPACE_ID::EnumValueOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -11225,11 +11306,11 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - options_ = options; + _impl_.options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValueDescriptorProto.options) } @@ -11239,15 +11320,15 @@ // optional string name = 1; inline bool ServiceDescriptorProto::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool ServiceDescriptorProto::has_name() const { return _internal_has_name(); } inline void ServiceDescriptorProto::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& ServiceDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.name) @@ -11256,8 +11337,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void ServiceDescriptorProto::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.ServiceDescriptorProto.name) } inline std::string* ServiceDescriptorProto::mutable_name() { @@ -11266,40 +11347,40 @@ return _s; } inline const std::string& ServiceDescriptorProto::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void ServiceDescriptorProto::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* ServiceDescriptorProto::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* ServiceDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void ServiceDescriptorProto::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.name) @@ -11307,32 +11388,32 @@ // repeated .google.protobuf.MethodDescriptorProto method = 2; inline int ServiceDescriptorProto::_internal_method_size() const { - return method_.size(); + return _impl_.method_.size(); } inline int ServiceDescriptorProto::method_size() const { return _internal_method_size(); } inline void ServiceDescriptorProto::clear_method() { - method_.Clear(); + _impl_.method_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* ServiceDescriptorProto::mutable_method(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceDescriptorProto.method) - return method_.Mutable(index); + return _impl_.method_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto >* ServiceDescriptorProto::mutable_method() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.ServiceDescriptorProto.method) - return &method_; + return &_impl_.method_; } inline const ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto& ServiceDescriptorProto::_internal_method(int index) const { - return method_.Get(index); + return _impl_.method_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto& ServiceDescriptorProto::method(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.ServiceDescriptorProto.method) return _internal_method(index); } inline ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* ServiceDescriptorProto::_internal_add_method() { - return method_.Add(); + return _impl_.method_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* ServiceDescriptorProto::add_method() { ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto* _add = _internal_add_method(); @@ -11342,24 +11423,24 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::MethodDescriptorProto >& ServiceDescriptorProto::method() const { // @@protoc_insertion_point(field_list:google.protobuf.ServiceDescriptorProto.method) - return method_; + return _impl_.method_; } // optional .google.protobuf.ServiceOptions options = 3; inline bool ServiceDescriptorProto::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool ServiceDescriptorProto::has_options() const { return _internal_has_options(); } inline void ServiceDescriptorProto::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000002u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const ::PROTOBUF_NAMESPACE_ID::ServiceOptions& ServiceDescriptorProto::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::ServiceOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::ServiceOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::ServiceOptions&>( ::PROTOBUF_NAMESPACE_ID::_ServiceOptions_default_instance_); } @@ -11370,20 +11451,20 @@ inline void ServiceDescriptorProto::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::ServiceOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.ServiceDescriptorProto.options) } inline ::PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::release_options() { - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::ServiceOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::ServiceOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -11397,18 +11478,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.ServiceDescriptorProto.options) - _has_bits_[0] &= ~0x00000002u; - ::PROTOBUF_NAMESPACE_ID::ServiceOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000002u; + ::PROTOBUF_NAMESPACE_ID::ServiceOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::_internal_mutable_options() { - _has_bits_[0] |= 0x00000002u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000002u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::ServiceOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::ServiceOptions* ServiceDescriptorProto::mutable_options() { ::PROTOBUF_NAMESPACE_ID::ServiceOptions* _msg = _internal_mutable_options(); @@ -11418,7 +11499,7 @@ inline void ServiceDescriptorProto::set_allocated_options(::PROTOBUF_NAMESPACE_ID::ServiceOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -11427,11 +11508,11 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - options_ = options; + _impl_.options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.ServiceDescriptorProto.options) } @@ -11441,15 +11522,15 @@ // optional string name = 1; inline bool MethodDescriptorProto::_internal_has_name() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool MethodDescriptorProto::has_name() const { return _internal_has_name(); } inline void MethodDescriptorProto::clear_name() { - name_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& MethodDescriptorProto::name() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.name) @@ -11458,8 +11539,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void MethodDescriptorProto::set_name(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.name) } inline std::string* MethodDescriptorProto::mutable_name() { @@ -11468,40 +11549,40 @@ return _s; } inline const std::string& MethodDescriptorProto::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void MethodDescriptorProto::_internal_set_name(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* MethodDescriptorProto::_internal_mutable_name() { - _has_bits_[0] |= 0x00000001u; - return name_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* MethodDescriptorProto::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.name) if (!_internal_has_name()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void MethodDescriptorProto::set_allocated_name(std::string* name) { if (name != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.name) @@ -11509,15 +11590,15 @@ // optional string input_type = 2; inline bool MethodDescriptorProto::_internal_has_input_type() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool MethodDescriptorProto::has_input_type() const { return _internal_has_input_type(); } inline void MethodDescriptorProto::clear_input_type() { - input_type_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000002u; + _impl_.input_type_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& MethodDescriptorProto::input_type() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.input_type) @@ -11526,8 +11607,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void MethodDescriptorProto::set_input_type(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000002u; - input_type_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.input_type_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.input_type) } inline std::string* MethodDescriptorProto::mutable_input_type() { @@ -11536,40 +11617,40 @@ return _s; } inline const std::string& MethodDescriptorProto::_internal_input_type() const { - return input_type_.Get(); + return _impl_.input_type_.Get(); } inline void MethodDescriptorProto::_internal_set_input_type(const std::string& value) { - _has_bits_[0] |= 0x00000002u; - input_type_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.input_type_.Set(value, GetArenaForAllocation()); } inline std::string* MethodDescriptorProto::_internal_mutable_input_type() { - _has_bits_[0] |= 0x00000002u; - return input_type_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + return _impl_.input_type_.Mutable(GetArenaForAllocation()); } inline std::string* MethodDescriptorProto::release_input_type() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.input_type) if (!_internal_has_input_type()) { return nullptr; } - _has_bits_[0] &= ~0x00000002u; - auto* p = input_type_.Release(); + _impl_._has_bits_[0] &= ~0x00000002u; + auto* p = _impl_.input_type_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (input_type_.IsDefault()) { - input_type_.Set("", GetArenaForAllocation()); + if (_impl_.input_type_.IsDefault()) { + _impl_.input_type_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void MethodDescriptorProto::set_allocated_input_type(std::string* input_type) { if (input_type != nullptr) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - input_type_.SetAllocated(input_type, GetArenaForAllocation()); + _impl_.input_type_.SetAllocated(input_type, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (input_type_.IsDefault()) { - input_type_.Set("", GetArenaForAllocation()); + if (_impl_.input_type_.IsDefault()) { + _impl_.input_type_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.input_type) @@ -11577,15 +11658,15 @@ // optional string output_type = 3; inline bool MethodDescriptorProto::_internal_has_output_type() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool MethodDescriptorProto::has_output_type() const { return _internal_has_output_type(); } inline void MethodDescriptorProto::clear_output_type() { - output_type_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000004u; + _impl_.output_type_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000004u; } inline const std::string& MethodDescriptorProto::output_type() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.output_type) @@ -11594,8 +11675,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void MethodDescriptorProto::set_output_type(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000004u; - output_type_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.output_type_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.MethodDescriptorProto.output_type) } inline std::string* MethodDescriptorProto::mutable_output_type() { @@ -11604,40 +11685,40 @@ return _s; } inline const std::string& MethodDescriptorProto::_internal_output_type() const { - return output_type_.Get(); + return _impl_.output_type_.Get(); } inline void MethodDescriptorProto::_internal_set_output_type(const std::string& value) { - _has_bits_[0] |= 0x00000004u; - output_type_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.output_type_.Set(value, GetArenaForAllocation()); } inline std::string* MethodDescriptorProto::_internal_mutable_output_type() { - _has_bits_[0] |= 0x00000004u; - return output_type_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + return _impl_.output_type_.Mutable(GetArenaForAllocation()); } inline std::string* MethodDescriptorProto::release_output_type() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.output_type) if (!_internal_has_output_type()) { return nullptr; } - _has_bits_[0] &= ~0x00000004u; - auto* p = output_type_.Release(); + _impl_._has_bits_[0] &= ~0x00000004u; + auto* p = _impl_.output_type_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (output_type_.IsDefault()) { - output_type_.Set("", GetArenaForAllocation()); + if (_impl_.output_type_.IsDefault()) { + _impl_.output_type_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void MethodDescriptorProto::set_allocated_output_type(std::string* output_type) { if (output_type != nullptr) { - _has_bits_[0] |= 0x00000004u; + _impl_._has_bits_[0] |= 0x00000004u; } else { - _has_bits_[0] &= ~0x00000004u; + _impl_._has_bits_[0] &= ~0x00000004u; } - output_type_.SetAllocated(output_type, GetArenaForAllocation()); + _impl_.output_type_.SetAllocated(output_type, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (output_type_.IsDefault()) { - output_type_.Set("", GetArenaForAllocation()); + if (_impl_.output_type_.IsDefault()) { + _impl_.output_type_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.output_type) @@ -11645,19 +11726,19 @@ // optional .google.protobuf.MethodOptions options = 4; inline bool MethodDescriptorProto::_internal_has_options() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; - PROTOBUF_ASSUME(!value || options_ != nullptr); + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; + PROTOBUF_ASSUME(!value || _impl_.options_ != nullptr); return value; } inline bool MethodDescriptorProto::has_options() const { return _internal_has_options(); } inline void MethodDescriptorProto::clear_options() { - if (options_ != nullptr) options_->Clear(); - _has_bits_[0] &= ~0x00000008u; + if (_impl_.options_ != nullptr) _impl_.options_->Clear(); + _impl_._has_bits_[0] &= ~0x00000008u; } inline const ::PROTOBUF_NAMESPACE_ID::MethodOptions& MethodDescriptorProto::_internal_options() const { - const ::PROTOBUF_NAMESPACE_ID::MethodOptions* p = options_; + const ::PROTOBUF_NAMESPACE_ID::MethodOptions* p = _impl_.options_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::MethodOptions&>( ::PROTOBUF_NAMESPACE_ID::_MethodOptions_default_instance_); } @@ -11668,20 +11749,20 @@ inline void MethodDescriptorProto::unsafe_arena_set_allocated_options( ::PROTOBUF_NAMESPACE_ID::MethodOptions* options) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(options_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.options_); } - options_ = options; + _impl_.options_ = options; if (options) { - _has_bits_[0] |= 0x00000008u; + _impl_._has_bits_[0] |= 0x00000008u; } else { - _has_bits_[0] &= ~0x00000008u; + _impl_._has_bits_[0] &= ~0x00000008u; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.MethodDescriptorProto.options) } inline ::PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::release_options() { - _has_bits_[0] &= ~0x00000008u; - ::PROTOBUF_NAMESPACE_ID::MethodOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000008u; + ::PROTOBUF_NAMESPACE_ID::MethodOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -11695,18 +11776,18 @@ } inline ::PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::unsafe_arena_release_options() { // @@protoc_insertion_point(field_release:google.protobuf.MethodDescriptorProto.options) - _has_bits_[0] &= ~0x00000008u; - ::PROTOBUF_NAMESPACE_ID::MethodOptions* temp = options_; - options_ = nullptr; + _impl_._has_bits_[0] &= ~0x00000008u; + ::PROTOBUF_NAMESPACE_ID::MethodOptions* temp = _impl_.options_; + _impl_.options_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::_internal_mutable_options() { - _has_bits_[0] |= 0x00000008u; - if (options_ == nullptr) { + _impl_._has_bits_[0] |= 0x00000008u; + if (_impl_.options_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::MethodOptions>(GetArenaForAllocation()); - options_ = p; + _impl_.options_ = p; } - return options_; + return _impl_.options_; } inline ::PROTOBUF_NAMESPACE_ID::MethodOptions* MethodDescriptorProto::mutable_options() { ::PROTOBUF_NAMESPACE_ID::MethodOptions* _msg = _internal_mutable_options(); @@ -11716,7 +11797,7 @@ inline void MethodDescriptorProto::set_allocated_options(::PROTOBUF_NAMESPACE_ID::MethodOptions* options) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete options_; + delete _impl_.options_; } if (options) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -11725,36 +11806,36 @@ options = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, options, submessage_arena); } - _has_bits_[0] |= 0x00000008u; + _impl_._has_bits_[0] |= 0x00000008u; } else { - _has_bits_[0] &= ~0x00000008u; + _impl_._has_bits_[0] &= ~0x00000008u; } - options_ = options; + _impl_.options_ = options; // @@protoc_insertion_point(field_set_allocated:google.protobuf.MethodDescriptorProto.options) } // optional bool client_streaming = 5 [default = false]; inline bool MethodDescriptorProto::_internal_has_client_streaming() const { - bool value = (_has_bits_[0] & 0x00000010u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool MethodDescriptorProto::has_client_streaming() const { return _internal_has_client_streaming(); } inline void MethodDescriptorProto::clear_client_streaming() { - client_streaming_ = false; - _has_bits_[0] &= ~0x00000010u; + _impl_.client_streaming_ = false; + _impl_._has_bits_[0] &= ~0x00000010u; } inline bool MethodDescriptorProto::_internal_client_streaming() const { - return client_streaming_; + return _impl_.client_streaming_; } inline bool MethodDescriptorProto::client_streaming() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.client_streaming) return _internal_client_streaming(); } inline void MethodDescriptorProto::_internal_set_client_streaming(bool value) { - _has_bits_[0] |= 0x00000010u; - client_streaming_ = value; + _impl_._has_bits_[0] |= 0x00000010u; + _impl_.client_streaming_ = value; } inline void MethodDescriptorProto::set_client_streaming(bool value) { _internal_set_client_streaming(value); @@ -11763,26 +11844,26 @@ // optional bool server_streaming = 6 [default = false]; inline bool MethodDescriptorProto::_internal_has_server_streaming() const { - bool value = (_has_bits_[0] & 0x00000020u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000020u) != 0; return value; } inline bool MethodDescriptorProto::has_server_streaming() const { return _internal_has_server_streaming(); } inline void MethodDescriptorProto::clear_server_streaming() { - server_streaming_ = false; - _has_bits_[0] &= ~0x00000020u; + _impl_.server_streaming_ = false; + _impl_._has_bits_[0] &= ~0x00000020u; } inline bool MethodDescriptorProto::_internal_server_streaming() const { - return server_streaming_; + return _impl_.server_streaming_; } inline bool MethodDescriptorProto::server_streaming() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodDescriptorProto.server_streaming) return _internal_server_streaming(); } inline void MethodDescriptorProto::_internal_set_server_streaming(bool value) { - _has_bits_[0] |= 0x00000020u; - server_streaming_ = value; + _impl_._has_bits_[0] |= 0x00000020u; + _impl_.server_streaming_ = value; } inline void MethodDescriptorProto::set_server_streaming(bool value) { _internal_set_server_streaming(value); @@ -11795,15 +11876,15 @@ // optional string java_package = 1; inline bool FileOptions::_internal_has_java_package() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool FileOptions::has_java_package() const { return _internal_has_java_package(); } inline void FileOptions::clear_java_package() { - java_package_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.java_package_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& FileOptions::java_package() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_package) @@ -11812,8 +11893,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_java_package(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - java_package_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.java_package_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_package) } inline std::string* FileOptions::mutable_java_package() { @@ -11822,40 +11903,40 @@ return _s; } inline const std::string& FileOptions::_internal_java_package() const { - return java_package_.Get(); + return _impl_.java_package_.Get(); } inline void FileOptions::_internal_set_java_package(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - java_package_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.java_package_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_java_package() { - _has_bits_[0] |= 0x00000001u; - return java_package_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.java_package_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_java_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_package) if (!_internal_has_java_package()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = java_package_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.java_package_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (java_package_.IsDefault()) { - java_package_.Set("", GetArenaForAllocation()); + if (_impl_.java_package_.IsDefault()) { + _impl_.java_package_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_java_package(std::string* java_package) { if (java_package != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - java_package_.SetAllocated(java_package, GetArenaForAllocation()); + _impl_.java_package_.SetAllocated(java_package, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (java_package_.IsDefault()) { - java_package_.Set("", GetArenaForAllocation()); + if (_impl_.java_package_.IsDefault()) { + _impl_.java_package_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_package) @@ -11863,15 +11944,15 @@ // optional string java_outer_classname = 8; inline bool FileOptions::_internal_has_java_outer_classname() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool FileOptions::has_java_outer_classname() const { return _internal_has_java_outer_classname(); } inline void FileOptions::clear_java_outer_classname() { - java_outer_classname_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000002u; + _impl_.java_outer_classname_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& FileOptions::java_outer_classname() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_outer_classname) @@ -11880,8 +11961,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_java_outer_classname(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000002u; - java_outer_classname_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.java_outer_classname_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.java_outer_classname) } inline std::string* FileOptions::mutable_java_outer_classname() { @@ -11890,40 +11971,40 @@ return _s; } inline const std::string& FileOptions::_internal_java_outer_classname() const { - return java_outer_classname_.Get(); + return _impl_.java_outer_classname_.Get(); } inline void FileOptions::_internal_set_java_outer_classname(const std::string& value) { - _has_bits_[0] |= 0x00000002u; - java_outer_classname_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.java_outer_classname_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_java_outer_classname() { - _has_bits_[0] |= 0x00000002u; - return java_outer_classname_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + return _impl_.java_outer_classname_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_java_outer_classname() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.java_outer_classname) if (!_internal_has_java_outer_classname()) { return nullptr; } - _has_bits_[0] &= ~0x00000002u; - auto* p = java_outer_classname_.Release(); + _impl_._has_bits_[0] &= ~0x00000002u; + auto* p = _impl_.java_outer_classname_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (java_outer_classname_.IsDefault()) { - java_outer_classname_.Set("", GetArenaForAllocation()); + if (_impl_.java_outer_classname_.IsDefault()) { + _impl_.java_outer_classname_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_java_outer_classname(std::string* java_outer_classname) { if (java_outer_classname != nullptr) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - java_outer_classname_.SetAllocated(java_outer_classname, GetArenaForAllocation()); + _impl_.java_outer_classname_.SetAllocated(java_outer_classname, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (java_outer_classname_.IsDefault()) { - java_outer_classname_.Set("", GetArenaForAllocation()); + if (_impl_.java_outer_classname_.IsDefault()) { + _impl_.java_outer_classname_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.java_outer_classname) @@ -11931,26 +12012,26 @@ // optional bool java_multiple_files = 10 [default = false]; inline bool FileOptions::_internal_has_java_multiple_files() const { - bool value = (_has_bits_[0] & 0x00000400u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000400u) != 0; return value; } inline bool FileOptions::has_java_multiple_files() const { return _internal_has_java_multiple_files(); } inline void FileOptions::clear_java_multiple_files() { - java_multiple_files_ = false; - _has_bits_[0] &= ~0x00000400u; + _impl_.java_multiple_files_ = false; + _impl_._has_bits_[0] &= ~0x00000400u; } inline bool FileOptions::_internal_java_multiple_files() const { - return java_multiple_files_; + return _impl_.java_multiple_files_; } inline bool FileOptions::java_multiple_files() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_multiple_files) return _internal_java_multiple_files(); } inline void FileOptions::_internal_set_java_multiple_files(bool value) { - _has_bits_[0] |= 0x00000400u; - java_multiple_files_ = value; + _impl_._has_bits_[0] |= 0x00000400u; + _impl_.java_multiple_files_ = value; } inline void FileOptions::set_java_multiple_files(bool value) { _internal_set_java_multiple_files(value); @@ -11959,26 +12040,26 @@ // optional bool java_generate_equals_and_hash = 20 [deprecated = true]; inline bool FileOptions::_internal_has_java_generate_equals_and_hash() const { - bool value = (_has_bits_[0] & 0x00000800u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000800u) != 0; return value; } inline bool FileOptions::has_java_generate_equals_and_hash() const { return _internal_has_java_generate_equals_and_hash(); } inline void FileOptions::clear_java_generate_equals_and_hash() { - java_generate_equals_and_hash_ = false; - _has_bits_[0] &= ~0x00000800u; + _impl_.java_generate_equals_and_hash_ = false; + _impl_._has_bits_[0] &= ~0x00000800u; } inline bool FileOptions::_internal_java_generate_equals_and_hash() const { - return java_generate_equals_and_hash_; + return _impl_.java_generate_equals_and_hash_; } inline bool FileOptions::java_generate_equals_and_hash() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generate_equals_and_hash) return _internal_java_generate_equals_and_hash(); } inline void FileOptions::_internal_set_java_generate_equals_and_hash(bool value) { - _has_bits_[0] |= 0x00000800u; - java_generate_equals_and_hash_ = value; + _impl_._has_bits_[0] |= 0x00000800u; + _impl_.java_generate_equals_and_hash_ = value; } inline void FileOptions::set_java_generate_equals_and_hash(bool value) { _internal_set_java_generate_equals_and_hash(value); @@ -11987,26 +12068,26 @@ // optional bool java_string_check_utf8 = 27 [default = false]; inline bool FileOptions::_internal_has_java_string_check_utf8() const { - bool value = (_has_bits_[0] & 0x00001000u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00001000u) != 0; return value; } inline bool FileOptions::has_java_string_check_utf8() const { return _internal_has_java_string_check_utf8(); } inline void FileOptions::clear_java_string_check_utf8() { - java_string_check_utf8_ = false; - _has_bits_[0] &= ~0x00001000u; + _impl_.java_string_check_utf8_ = false; + _impl_._has_bits_[0] &= ~0x00001000u; } inline bool FileOptions::_internal_java_string_check_utf8() const { - return java_string_check_utf8_; + return _impl_.java_string_check_utf8_; } inline bool FileOptions::java_string_check_utf8() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_string_check_utf8) return _internal_java_string_check_utf8(); } inline void FileOptions::_internal_set_java_string_check_utf8(bool value) { - _has_bits_[0] |= 0x00001000u; - java_string_check_utf8_ = value; + _impl_._has_bits_[0] |= 0x00001000u; + _impl_.java_string_check_utf8_ = value; } inline void FileOptions::set_java_string_check_utf8(bool value) { _internal_set_java_string_check_utf8(value); @@ -12015,18 +12096,18 @@ // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; inline bool FileOptions::_internal_has_optimize_for() const { - bool value = (_has_bits_[0] & 0x00040000u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00040000u) != 0; return value; } inline bool FileOptions::has_optimize_for() const { return _internal_has_optimize_for(); } inline void FileOptions::clear_optimize_for() { - optimize_for_ = 1; - _has_bits_[0] &= ~0x00040000u; + _impl_.optimize_for_ = 1; + _impl_._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_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode >(_impl_.optimize_for_); } inline ::PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode FileOptions::optimize_for() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.optimize_for) @@ -12034,8 +12115,8 @@ } inline void FileOptions::_internal_set_optimize_for(::PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode value) { assert(::PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode_IsValid(value)); - _has_bits_[0] |= 0x00040000u; - optimize_for_ = value; + _impl_._has_bits_[0] |= 0x00040000u; + _impl_.optimize_for_ = value; } inline void FileOptions::set_optimize_for(::PROTOBUF_NAMESPACE_ID::FileOptions_OptimizeMode value) { _internal_set_optimize_for(value); @@ -12044,15 +12125,15 @@ // optional string go_package = 11; inline bool FileOptions::_internal_has_go_package() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool FileOptions::has_go_package() const { return _internal_has_go_package(); } inline void FileOptions::clear_go_package() { - go_package_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000004u; + _impl_.go_package_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000004u; } inline const std::string& FileOptions::go_package() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.go_package) @@ -12061,8 +12142,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_go_package(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000004u; - go_package_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.go_package_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.go_package) } inline std::string* FileOptions::mutable_go_package() { @@ -12071,40 +12152,40 @@ return _s; } inline const std::string& FileOptions::_internal_go_package() const { - return go_package_.Get(); + return _impl_.go_package_.Get(); } inline void FileOptions::_internal_set_go_package(const std::string& value) { - _has_bits_[0] |= 0x00000004u; - go_package_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.go_package_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_go_package() { - _has_bits_[0] |= 0x00000004u; - return go_package_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + return _impl_.go_package_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_go_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.go_package) if (!_internal_has_go_package()) { return nullptr; } - _has_bits_[0] &= ~0x00000004u; - auto* p = go_package_.Release(); + _impl_._has_bits_[0] &= ~0x00000004u; + auto* p = _impl_.go_package_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (go_package_.IsDefault()) { - go_package_.Set("", GetArenaForAllocation()); + if (_impl_.go_package_.IsDefault()) { + _impl_.go_package_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_go_package(std::string* go_package) { if (go_package != nullptr) { - _has_bits_[0] |= 0x00000004u; + _impl_._has_bits_[0] |= 0x00000004u; } else { - _has_bits_[0] &= ~0x00000004u; + _impl_._has_bits_[0] &= ~0x00000004u; } - go_package_.SetAllocated(go_package, GetArenaForAllocation()); + _impl_.go_package_.SetAllocated(go_package, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (go_package_.IsDefault()) { - go_package_.Set("", GetArenaForAllocation()); + if (_impl_.go_package_.IsDefault()) { + _impl_.go_package_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.go_package) @@ -12112,26 +12193,26 @@ // optional bool cc_generic_services = 16 [default = false]; inline bool FileOptions::_internal_has_cc_generic_services() const { - bool value = (_has_bits_[0] & 0x00002000u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00002000u) != 0; return value; } inline bool FileOptions::has_cc_generic_services() const { return _internal_has_cc_generic_services(); } inline void FileOptions::clear_cc_generic_services() { - cc_generic_services_ = false; - _has_bits_[0] &= ~0x00002000u; + _impl_.cc_generic_services_ = false; + _impl_._has_bits_[0] &= ~0x00002000u; } inline bool FileOptions::_internal_cc_generic_services() const { - return cc_generic_services_; + return _impl_.cc_generic_services_; } inline bool FileOptions::cc_generic_services() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_generic_services) return _internal_cc_generic_services(); } inline void FileOptions::_internal_set_cc_generic_services(bool value) { - _has_bits_[0] |= 0x00002000u; - cc_generic_services_ = value; + _impl_._has_bits_[0] |= 0x00002000u; + _impl_.cc_generic_services_ = value; } inline void FileOptions::set_cc_generic_services(bool value) { _internal_set_cc_generic_services(value); @@ -12140,26 +12221,26 @@ // optional bool java_generic_services = 17 [default = false]; inline bool FileOptions::_internal_has_java_generic_services() const { - bool value = (_has_bits_[0] & 0x00004000u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00004000u) != 0; return value; } inline bool FileOptions::has_java_generic_services() const { return _internal_has_java_generic_services(); } inline void FileOptions::clear_java_generic_services() { - java_generic_services_ = false; - _has_bits_[0] &= ~0x00004000u; + _impl_.java_generic_services_ = false; + _impl_._has_bits_[0] &= ~0x00004000u; } inline bool FileOptions::_internal_java_generic_services() const { - return java_generic_services_; + return _impl_.java_generic_services_; } inline bool FileOptions::java_generic_services() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.java_generic_services) return _internal_java_generic_services(); } inline void FileOptions::_internal_set_java_generic_services(bool value) { - _has_bits_[0] |= 0x00004000u; - java_generic_services_ = value; + _impl_._has_bits_[0] |= 0x00004000u; + _impl_.java_generic_services_ = value; } inline void FileOptions::set_java_generic_services(bool value) { _internal_set_java_generic_services(value); @@ -12168,26 +12249,26 @@ // optional bool py_generic_services = 18 [default = false]; inline bool FileOptions::_internal_has_py_generic_services() const { - bool value = (_has_bits_[0] & 0x00008000u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00008000u) != 0; return value; } inline bool FileOptions::has_py_generic_services() const { return _internal_has_py_generic_services(); } inline void FileOptions::clear_py_generic_services() { - py_generic_services_ = false; - _has_bits_[0] &= ~0x00008000u; + _impl_.py_generic_services_ = false; + _impl_._has_bits_[0] &= ~0x00008000u; } inline bool FileOptions::_internal_py_generic_services() const { - return py_generic_services_; + return _impl_.py_generic_services_; } inline bool FileOptions::py_generic_services() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.py_generic_services) return _internal_py_generic_services(); } inline void FileOptions::_internal_set_py_generic_services(bool value) { - _has_bits_[0] |= 0x00008000u; - py_generic_services_ = value; + _impl_._has_bits_[0] |= 0x00008000u; + _impl_.py_generic_services_ = value; } inline void FileOptions::set_py_generic_services(bool value) { _internal_set_py_generic_services(value); @@ -12196,26 +12277,26 @@ // optional bool php_generic_services = 42 [default = false]; inline bool FileOptions::_internal_has_php_generic_services() const { - bool value = (_has_bits_[0] & 0x00010000u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00010000u) != 0; return value; } inline bool FileOptions::has_php_generic_services() const { return _internal_has_php_generic_services(); } inline void FileOptions::clear_php_generic_services() { - php_generic_services_ = false; - _has_bits_[0] &= ~0x00010000u; + _impl_.php_generic_services_ = false; + _impl_._has_bits_[0] &= ~0x00010000u; } inline bool FileOptions::_internal_php_generic_services() const { - return php_generic_services_; + return _impl_.php_generic_services_; } inline bool FileOptions::php_generic_services() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_generic_services) return _internal_php_generic_services(); } inline void FileOptions::_internal_set_php_generic_services(bool value) { - _has_bits_[0] |= 0x00010000u; - php_generic_services_ = value; + _impl_._has_bits_[0] |= 0x00010000u; + _impl_.php_generic_services_ = value; } inline void FileOptions::set_php_generic_services(bool value) { _internal_set_php_generic_services(value); @@ -12224,26 +12305,26 @@ // optional bool deprecated = 23 [default = false]; inline bool FileOptions::_internal_has_deprecated() const { - bool value = (_has_bits_[0] & 0x00020000u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00020000u) != 0; return value; } inline bool FileOptions::has_deprecated() const { return _internal_has_deprecated(); } inline void FileOptions::clear_deprecated() { - deprecated_ = false; - _has_bits_[0] &= ~0x00020000u; + _impl_.deprecated_ = false; + _impl_._has_bits_[0] &= ~0x00020000u; } inline bool FileOptions::_internal_deprecated() const { - return deprecated_; + return _impl_.deprecated_; } inline bool FileOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.deprecated) return _internal_deprecated(); } inline void FileOptions::_internal_set_deprecated(bool value) { - _has_bits_[0] |= 0x00020000u; - deprecated_ = value; + _impl_._has_bits_[0] |= 0x00020000u; + _impl_.deprecated_ = value; } inline void FileOptions::set_deprecated(bool value) { _internal_set_deprecated(value); @@ -12252,26 +12333,26 @@ // optional bool cc_enable_arenas = 31 [default = true]; inline bool FileOptions::_internal_has_cc_enable_arenas() const { - bool value = (_has_bits_[0] & 0x00080000u) != 0; + bool value = (_impl_._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_ = true; - _has_bits_[0] &= ~0x00080000u; + _impl_.cc_enable_arenas_ = true; + _impl_._has_bits_[0] &= ~0x00080000u; } inline bool FileOptions::_internal_cc_enable_arenas() const { - return cc_enable_arenas_; + return _impl_.cc_enable_arenas_; } inline bool FileOptions::cc_enable_arenas() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.cc_enable_arenas) return _internal_cc_enable_arenas(); } inline void FileOptions::_internal_set_cc_enable_arenas(bool value) { - _has_bits_[0] |= 0x00080000u; - cc_enable_arenas_ = value; + _impl_._has_bits_[0] |= 0x00080000u; + _impl_.cc_enable_arenas_ = value; } inline void FileOptions::set_cc_enable_arenas(bool value) { _internal_set_cc_enable_arenas(value); @@ -12280,15 +12361,15 @@ // optional string objc_class_prefix = 36; inline bool FileOptions::_internal_has_objc_class_prefix() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool FileOptions::has_objc_class_prefix() const { return _internal_has_objc_class_prefix(); } inline void FileOptions::clear_objc_class_prefix() { - objc_class_prefix_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000008u; + _impl_.objc_class_prefix_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000008u; } inline const std::string& FileOptions::objc_class_prefix() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.objc_class_prefix) @@ -12297,8 +12378,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_objc_class_prefix(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000008u; - objc_class_prefix_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000008u; + _impl_.objc_class_prefix_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.objc_class_prefix) } inline std::string* FileOptions::mutable_objc_class_prefix() { @@ -12307,40 +12388,40 @@ return _s; } inline const std::string& FileOptions::_internal_objc_class_prefix() const { - return objc_class_prefix_.Get(); + return _impl_.objc_class_prefix_.Get(); } inline void FileOptions::_internal_set_objc_class_prefix(const std::string& value) { - _has_bits_[0] |= 0x00000008u; - objc_class_prefix_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000008u; + _impl_.objc_class_prefix_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_objc_class_prefix() { - _has_bits_[0] |= 0x00000008u; - return objc_class_prefix_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000008u; + return _impl_.objc_class_prefix_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_objc_class_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.objc_class_prefix) if (!_internal_has_objc_class_prefix()) { return nullptr; } - _has_bits_[0] &= ~0x00000008u; - auto* p = objc_class_prefix_.Release(); + _impl_._has_bits_[0] &= ~0x00000008u; + auto* p = _impl_.objc_class_prefix_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (objc_class_prefix_.IsDefault()) { - objc_class_prefix_.Set("", GetArenaForAllocation()); + if (_impl_.objc_class_prefix_.IsDefault()) { + _impl_.objc_class_prefix_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_objc_class_prefix(std::string* objc_class_prefix) { if (objc_class_prefix != nullptr) { - _has_bits_[0] |= 0x00000008u; + _impl_._has_bits_[0] |= 0x00000008u; } else { - _has_bits_[0] &= ~0x00000008u; + _impl_._has_bits_[0] &= ~0x00000008u; } - objc_class_prefix_.SetAllocated(objc_class_prefix, GetArenaForAllocation()); + _impl_.objc_class_prefix_.SetAllocated(objc_class_prefix, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (objc_class_prefix_.IsDefault()) { - objc_class_prefix_.Set("", GetArenaForAllocation()); + if (_impl_.objc_class_prefix_.IsDefault()) { + _impl_.objc_class_prefix_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.objc_class_prefix) @@ -12348,15 +12429,15 @@ // optional string csharp_namespace = 37; inline bool FileOptions::_internal_has_csharp_namespace() const { - bool value = (_has_bits_[0] & 0x00000010u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool FileOptions::has_csharp_namespace() const { return _internal_has_csharp_namespace(); } inline void FileOptions::clear_csharp_namespace() { - csharp_namespace_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000010u; + _impl_.csharp_namespace_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000010u; } inline const std::string& FileOptions::csharp_namespace() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.csharp_namespace) @@ -12365,8 +12446,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_csharp_namespace(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000010u; - csharp_namespace_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000010u; + _impl_.csharp_namespace_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.csharp_namespace) } inline std::string* FileOptions::mutable_csharp_namespace() { @@ -12375,40 +12456,40 @@ return _s; } inline const std::string& FileOptions::_internal_csharp_namespace() const { - return csharp_namespace_.Get(); + return _impl_.csharp_namespace_.Get(); } inline void FileOptions::_internal_set_csharp_namespace(const std::string& value) { - _has_bits_[0] |= 0x00000010u; - csharp_namespace_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000010u; + _impl_.csharp_namespace_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_csharp_namespace() { - _has_bits_[0] |= 0x00000010u; - return csharp_namespace_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000010u; + return _impl_.csharp_namespace_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_csharp_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.csharp_namespace) if (!_internal_has_csharp_namespace()) { return nullptr; } - _has_bits_[0] &= ~0x00000010u; - auto* p = csharp_namespace_.Release(); + _impl_._has_bits_[0] &= ~0x00000010u; + auto* p = _impl_.csharp_namespace_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (csharp_namespace_.IsDefault()) { - csharp_namespace_.Set("", GetArenaForAllocation()); + if (_impl_.csharp_namespace_.IsDefault()) { + _impl_.csharp_namespace_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_csharp_namespace(std::string* csharp_namespace) { if (csharp_namespace != nullptr) { - _has_bits_[0] |= 0x00000010u; + _impl_._has_bits_[0] |= 0x00000010u; } else { - _has_bits_[0] &= ~0x00000010u; + _impl_._has_bits_[0] &= ~0x00000010u; } - csharp_namespace_.SetAllocated(csharp_namespace, GetArenaForAllocation()); + _impl_.csharp_namespace_.SetAllocated(csharp_namespace, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (csharp_namespace_.IsDefault()) { - csharp_namespace_.Set("", GetArenaForAllocation()); + if (_impl_.csharp_namespace_.IsDefault()) { + _impl_.csharp_namespace_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.csharp_namespace) @@ -12416,15 +12497,15 @@ // optional string swift_prefix = 39; inline bool FileOptions::_internal_has_swift_prefix() const { - bool value = (_has_bits_[0] & 0x00000020u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000020u) != 0; return value; } inline bool FileOptions::has_swift_prefix() const { return _internal_has_swift_prefix(); } inline void FileOptions::clear_swift_prefix() { - swift_prefix_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000020u; + _impl_.swift_prefix_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000020u; } inline const std::string& FileOptions::swift_prefix() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.swift_prefix) @@ -12433,8 +12514,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_swift_prefix(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000020u; - swift_prefix_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000020u; + _impl_.swift_prefix_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.swift_prefix) } inline std::string* FileOptions::mutable_swift_prefix() { @@ -12443,40 +12524,40 @@ return _s; } inline const std::string& FileOptions::_internal_swift_prefix() const { - return swift_prefix_.Get(); + return _impl_.swift_prefix_.Get(); } inline void FileOptions::_internal_set_swift_prefix(const std::string& value) { - _has_bits_[0] |= 0x00000020u; - swift_prefix_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000020u; + _impl_.swift_prefix_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_swift_prefix() { - _has_bits_[0] |= 0x00000020u; - return swift_prefix_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000020u; + return _impl_.swift_prefix_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_swift_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.swift_prefix) if (!_internal_has_swift_prefix()) { return nullptr; } - _has_bits_[0] &= ~0x00000020u; - auto* p = swift_prefix_.Release(); + _impl_._has_bits_[0] &= ~0x00000020u; + auto* p = _impl_.swift_prefix_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (swift_prefix_.IsDefault()) { - swift_prefix_.Set("", GetArenaForAllocation()); + if (_impl_.swift_prefix_.IsDefault()) { + _impl_.swift_prefix_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_swift_prefix(std::string* swift_prefix) { if (swift_prefix != nullptr) { - _has_bits_[0] |= 0x00000020u; + _impl_._has_bits_[0] |= 0x00000020u; } else { - _has_bits_[0] &= ~0x00000020u; + _impl_._has_bits_[0] &= ~0x00000020u; } - swift_prefix_.SetAllocated(swift_prefix, GetArenaForAllocation()); + _impl_.swift_prefix_.SetAllocated(swift_prefix, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (swift_prefix_.IsDefault()) { - swift_prefix_.Set("", GetArenaForAllocation()); + if (_impl_.swift_prefix_.IsDefault()) { + _impl_.swift_prefix_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.swift_prefix) @@ -12484,15 +12565,15 @@ // optional string php_class_prefix = 40; inline bool FileOptions::_internal_has_php_class_prefix() const { - bool value = (_has_bits_[0] & 0x00000040u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000040u) != 0; return value; } inline bool FileOptions::has_php_class_prefix() const { return _internal_has_php_class_prefix(); } inline void FileOptions::clear_php_class_prefix() { - php_class_prefix_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000040u; + _impl_.php_class_prefix_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000040u; } inline const std::string& FileOptions::php_class_prefix() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_class_prefix) @@ -12501,8 +12582,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_php_class_prefix(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000040u; - php_class_prefix_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000040u; + _impl_.php_class_prefix_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_class_prefix) } inline std::string* FileOptions::mutable_php_class_prefix() { @@ -12511,40 +12592,40 @@ return _s; } inline const std::string& FileOptions::_internal_php_class_prefix() const { - return php_class_prefix_.Get(); + return _impl_.php_class_prefix_.Get(); } inline void FileOptions::_internal_set_php_class_prefix(const std::string& value) { - _has_bits_[0] |= 0x00000040u; - php_class_prefix_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000040u; + _impl_.php_class_prefix_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_php_class_prefix() { - _has_bits_[0] |= 0x00000040u; - return php_class_prefix_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000040u; + return _impl_.php_class_prefix_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_php_class_prefix() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_class_prefix) if (!_internal_has_php_class_prefix()) { return nullptr; } - _has_bits_[0] &= ~0x00000040u; - auto* p = php_class_prefix_.Release(); + _impl_._has_bits_[0] &= ~0x00000040u; + auto* p = _impl_.php_class_prefix_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (php_class_prefix_.IsDefault()) { - php_class_prefix_.Set("", GetArenaForAllocation()); + if (_impl_.php_class_prefix_.IsDefault()) { + _impl_.php_class_prefix_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_php_class_prefix(std::string* php_class_prefix) { if (php_class_prefix != nullptr) { - _has_bits_[0] |= 0x00000040u; + _impl_._has_bits_[0] |= 0x00000040u; } else { - _has_bits_[0] &= ~0x00000040u; + _impl_._has_bits_[0] &= ~0x00000040u; } - php_class_prefix_.SetAllocated(php_class_prefix, GetArenaForAllocation()); + _impl_.php_class_prefix_.SetAllocated(php_class_prefix, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (php_class_prefix_.IsDefault()) { - php_class_prefix_.Set("", GetArenaForAllocation()); + if (_impl_.php_class_prefix_.IsDefault()) { + _impl_.php_class_prefix_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_class_prefix) @@ -12552,15 +12633,15 @@ // optional string php_namespace = 41; inline bool FileOptions::_internal_has_php_namespace() const { - bool value = (_has_bits_[0] & 0x00000080u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000080u) != 0; return value; } inline bool FileOptions::has_php_namespace() const { return _internal_has_php_namespace(); } inline void FileOptions::clear_php_namespace() { - php_namespace_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000080u; + _impl_.php_namespace_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000080u; } inline const std::string& FileOptions::php_namespace() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_namespace) @@ -12569,8 +12650,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_php_namespace(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000080u; - php_namespace_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000080u; + _impl_.php_namespace_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_namespace) } inline std::string* FileOptions::mutable_php_namespace() { @@ -12579,40 +12660,40 @@ return _s; } inline const std::string& FileOptions::_internal_php_namespace() const { - return php_namespace_.Get(); + return _impl_.php_namespace_.Get(); } inline void FileOptions::_internal_set_php_namespace(const std::string& value) { - _has_bits_[0] |= 0x00000080u; - php_namespace_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000080u; + _impl_.php_namespace_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_php_namespace() { - _has_bits_[0] |= 0x00000080u; - return php_namespace_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000080u; + return _impl_.php_namespace_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_php_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_namespace) if (!_internal_has_php_namespace()) { return nullptr; } - _has_bits_[0] &= ~0x00000080u; - auto* p = php_namespace_.Release(); + _impl_._has_bits_[0] &= ~0x00000080u; + auto* p = _impl_.php_namespace_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (php_namespace_.IsDefault()) { - php_namespace_.Set("", GetArenaForAllocation()); + if (_impl_.php_namespace_.IsDefault()) { + _impl_.php_namespace_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_php_namespace(std::string* php_namespace) { if (php_namespace != nullptr) { - _has_bits_[0] |= 0x00000080u; + _impl_._has_bits_[0] |= 0x00000080u; } else { - _has_bits_[0] &= ~0x00000080u; + _impl_._has_bits_[0] &= ~0x00000080u; } - php_namespace_.SetAllocated(php_namespace, GetArenaForAllocation()); + _impl_.php_namespace_.SetAllocated(php_namespace, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (php_namespace_.IsDefault()) { - php_namespace_.Set("", GetArenaForAllocation()); + if (_impl_.php_namespace_.IsDefault()) { + _impl_.php_namespace_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_namespace) @@ -12620,15 +12701,15 @@ // optional string php_metadata_namespace = 44; inline bool FileOptions::_internal_has_php_metadata_namespace() const { - bool value = (_has_bits_[0] & 0x00000100u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000100u) != 0; return value; } inline bool FileOptions::has_php_metadata_namespace() const { return _internal_has_php_metadata_namespace(); } inline void FileOptions::clear_php_metadata_namespace() { - php_metadata_namespace_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000100u; + _impl_.php_metadata_namespace_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000100u; } inline const std::string& FileOptions::php_metadata_namespace() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.php_metadata_namespace) @@ -12637,8 +12718,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_php_metadata_namespace(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000100u; - php_metadata_namespace_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000100u; + _impl_.php_metadata_namespace_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.php_metadata_namespace) } inline std::string* FileOptions::mutable_php_metadata_namespace() { @@ -12647,40 +12728,40 @@ return _s; } inline const std::string& FileOptions::_internal_php_metadata_namespace() const { - return php_metadata_namespace_.Get(); + return _impl_.php_metadata_namespace_.Get(); } inline void FileOptions::_internal_set_php_metadata_namespace(const std::string& value) { - _has_bits_[0] |= 0x00000100u; - php_metadata_namespace_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000100u; + _impl_.php_metadata_namespace_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_php_metadata_namespace() { - _has_bits_[0] |= 0x00000100u; - return php_metadata_namespace_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000100u; + return _impl_.php_metadata_namespace_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_php_metadata_namespace() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.php_metadata_namespace) if (!_internal_has_php_metadata_namespace()) { return nullptr; } - _has_bits_[0] &= ~0x00000100u; - auto* p = php_metadata_namespace_.Release(); + _impl_._has_bits_[0] &= ~0x00000100u; + auto* p = _impl_.php_metadata_namespace_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (php_metadata_namespace_.IsDefault()) { - php_metadata_namespace_.Set("", GetArenaForAllocation()); + if (_impl_.php_metadata_namespace_.IsDefault()) { + _impl_.php_metadata_namespace_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_php_metadata_namespace(std::string* php_metadata_namespace) { if (php_metadata_namespace != nullptr) { - _has_bits_[0] |= 0x00000100u; + _impl_._has_bits_[0] |= 0x00000100u; } else { - _has_bits_[0] &= ~0x00000100u; + _impl_._has_bits_[0] &= ~0x00000100u; } - php_metadata_namespace_.SetAllocated(php_metadata_namespace, GetArenaForAllocation()); + _impl_.php_metadata_namespace_.SetAllocated(php_metadata_namespace, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (php_metadata_namespace_.IsDefault()) { - php_metadata_namespace_.Set("", GetArenaForAllocation()); + if (_impl_.php_metadata_namespace_.IsDefault()) { + _impl_.php_metadata_namespace_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.php_metadata_namespace) @@ -12688,15 +12769,15 @@ // optional string ruby_package = 45; inline bool FileOptions::_internal_has_ruby_package() const { - bool value = (_has_bits_[0] & 0x00000200u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000200u) != 0; return value; } inline bool FileOptions::has_ruby_package() const { return _internal_has_ruby_package(); } inline void FileOptions::clear_ruby_package() { - ruby_package_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000200u; + _impl_.ruby_package_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000200u; } inline const std::string& FileOptions::ruby_package() const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.ruby_package) @@ -12705,8 +12786,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void FileOptions::set_ruby_package(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000200u; - ruby_package_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000200u; + _impl_.ruby_package_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.FileOptions.ruby_package) } inline std::string* FileOptions::mutable_ruby_package() { @@ -12715,40 +12796,40 @@ return _s; } inline const std::string& FileOptions::_internal_ruby_package() const { - return ruby_package_.Get(); + return _impl_.ruby_package_.Get(); } inline void FileOptions::_internal_set_ruby_package(const std::string& value) { - _has_bits_[0] |= 0x00000200u; - ruby_package_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000200u; + _impl_.ruby_package_.Set(value, GetArenaForAllocation()); } inline std::string* FileOptions::_internal_mutable_ruby_package() { - _has_bits_[0] |= 0x00000200u; - return ruby_package_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000200u; + return _impl_.ruby_package_.Mutable(GetArenaForAllocation()); } inline std::string* FileOptions::release_ruby_package() { // @@protoc_insertion_point(field_release:google.protobuf.FileOptions.ruby_package) if (!_internal_has_ruby_package()) { return nullptr; } - _has_bits_[0] &= ~0x00000200u; - auto* p = ruby_package_.Release(); + _impl_._has_bits_[0] &= ~0x00000200u; + auto* p = _impl_.ruby_package_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (ruby_package_.IsDefault()) { - ruby_package_.Set("", GetArenaForAllocation()); + if (_impl_.ruby_package_.IsDefault()) { + _impl_.ruby_package_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void FileOptions::set_allocated_ruby_package(std::string* ruby_package) { if (ruby_package != nullptr) { - _has_bits_[0] |= 0x00000200u; + _impl_._has_bits_[0] |= 0x00000200u; } else { - _has_bits_[0] &= ~0x00000200u; + _impl_._has_bits_[0] &= ~0x00000200u; } - ruby_package_.SetAllocated(ruby_package, GetArenaForAllocation()); + _impl_.ruby_package_.SetAllocated(ruby_package, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (ruby_package_.IsDefault()) { - ruby_package_.Set("", GetArenaForAllocation()); + if (_impl_.ruby_package_.IsDefault()) { + _impl_.ruby_package_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.FileOptions.ruby_package) @@ -12756,32 +12837,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int FileOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int FileOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void FileOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* FileOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FileOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* FileOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FileOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& FileOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& FileOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FileOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* FileOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* FileOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -12791,7 +12872,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& FileOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.FileOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -12800,26 +12881,26 @@ // optional bool message_set_wire_format = 1 [default = false]; inline bool MessageOptions::_internal_has_message_set_wire_format() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool MessageOptions::has_message_set_wire_format() const { return _internal_has_message_set_wire_format(); } inline void MessageOptions::clear_message_set_wire_format() { - message_set_wire_format_ = false; - _has_bits_[0] &= ~0x00000001u; + _impl_.message_set_wire_format_ = false; + _impl_._has_bits_[0] &= ~0x00000001u; } inline bool MessageOptions::_internal_message_set_wire_format() const { - return message_set_wire_format_; + return _impl_.message_set_wire_format_; } inline bool MessageOptions::message_set_wire_format() const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.message_set_wire_format) return _internal_message_set_wire_format(); } inline void MessageOptions::_internal_set_message_set_wire_format(bool value) { - _has_bits_[0] |= 0x00000001u; - message_set_wire_format_ = value; + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.message_set_wire_format_ = value; } inline void MessageOptions::set_message_set_wire_format(bool value) { _internal_set_message_set_wire_format(value); @@ -12828,26 +12909,26 @@ // optional bool no_standard_descriptor_accessor = 2 [default = false]; inline bool MessageOptions::_internal_has_no_standard_descriptor_accessor() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool MessageOptions::has_no_standard_descriptor_accessor() const { return _internal_has_no_standard_descriptor_accessor(); } inline void MessageOptions::clear_no_standard_descriptor_accessor() { - no_standard_descriptor_accessor_ = false; - _has_bits_[0] &= ~0x00000002u; + _impl_.no_standard_descriptor_accessor_ = false; + _impl_._has_bits_[0] &= ~0x00000002u; } inline bool MessageOptions::_internal_no_standard_descriptor_accessor() const { - return no_standard_descriptor_accessor_; + return _impl_.no_standard_descriptor_accessor_; } inline bool MessageOptions::no_standard_descriptor_accessor() const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.no_standard_descriptor_accessor) return _internal_no_standard_descriptor_accessor(); } inline void MessageOptions::_internal_set_no_standard_descriptor_accessor(bool value) { - _has_bits_[0] |= 0x00000002u; - no_standard_descriptor_accessor_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.no_standard_descriptor_accessor_ = value; } inline void MessageOptions::set_no_standard_descriptor_accessor(bool value) { _internal_set_no_standard_descriptor_accessor(value); @@ -12856,26 +12937,26 @@ // optional bool deprecated = 3 [default = false]; inline bool MessageOptions::_internal_has_deprecated() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool MessageOptions::has_deprecated() const { return _internal_has_deprecated(); } inline void MessageOptions::clear_deprecated() { - deprecated_ = false; - _has_bits_[0] &= ~0x00000004u; + _impl_.deprecated_ = false; + _impl_._has_bits_[0] &= ~0x00000004u; } inline bool MessageOptions::_internal_deprecated() const { - return deprecated_; + return _impl_.deprecated_; } inline bool MessageOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.deprecated) return _internal_deprecated(); } inline void MessageOptions::_internal_set_deprecated(bool value) { - _has_bits_[0] |= 0x00000004u; - deprecated_ = value; + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.deprecated_ = value; } inline void MessageOptions::set_deprecated(bool value) { _internal_set_deprecated(value); @@ -12884,26 +12965,26 @@ // optional bool map_entry = 7; inline bool MessageOptions::_internal_has_map_entry() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool MessageOptions::has_map_entry() const { return _internal_has_map_entry(); } inline void MessageOptions::clear_map_entry() { - map_entry_ = false; - _has_bits_[0] &= ~0x00000008u; + _impl_.map_entry_ = false; + _impl_._has_bits_[0] &= ~0x00000008u; } inline bool MessageOptions::_internal_map_entry() const { - return map_entry_; + return _impl_.map_entry_; } inline bool MessageOptions::map_entry() const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.map_entry) return _internal_map_entry(); } inline void MessageOptions::_internal_set_map_entry(bool value) { - _has_bits_[0] |= 0x00000008u; - map_entry_ = value; + _impl_._has_bits_[0] |= 0x00000008u; + _impl_.map_entry_ = value; } inline void MessageOptions::set_map_entry(bool value) { _internal_set_map_entry(value); @@ -12912,32 +12993,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int MessageOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int MessageOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void MessageOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* MessageOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.MessageOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* MessageOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.MessageOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& MessageOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& MessageOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.MessageOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* MessageOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* MessageOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -12947,7 +13028,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& MessageOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.MessageOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -12956,18 +13037,18 @@ // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; inline bool FieldOptions::_internal_has_ctype() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool FieldOptions::has_ctype() const { return _internal_has_ctype(); } inline void FieldOptions::clear_ctype() { - ctype_ = 0; - _has_bits_[0] &= ~0x00000001u; + _impl_.ctype_ = 0; + _impl_._has_bits_[0] &= ~0x00000001u; } inline ::PROTOBUF_NAMESPACE_ID::FieldOptions_CType FieldOptions::_internal_ctype() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::FieldOptions_CType >(ctype_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::FieldOptions_CType >(_impl_.ctype_); } inline ::PROTOBUF_NAMESPACE_ID::FieldOptions_CType FieldOptions::ctype() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.ctype) @@ -12975,8 +13056,8 @@ } inline void FieldOptions::_internal_set_ctype(::PROTOBUF_NAMESPACE_ID::FieldOptions_CType value) { assert(::PROTOBUF_NAMESPACE_ID::FieldOptions_CType_IsValid(value)); - _has_bits_[0] |= 0x00000001u; - ctype_ = value; + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.ctype_ = value; } inline void FieldOptions::set_ctype(::PROTOBUF_NAMESPACE_ID::FieldOptions_CType value) { _internal_set_ctype(value); @@ -12985,26 +13066,26 @@ // optional bool packed = 2; inline bool FieldOptions::_internal_has_packed() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool FieldOptions::has_packed() const { return _internal_has_packed(); } inline void FieldOptions::clear_packed() { - packed_ = false; - _has_bits_[0] &= ~0x00000004u; + _impl_.packed_ = false; + _impl_._has_bits_[0] &= ~0x00000004u; } inline bool FieldOptions::_internal_packed() const { - return packed_; + return _impl_.packed_; } inline bool FieldOptions::packed() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.packed) return _internal_packed(); } inline void FieldOptions::_internal_set_packed(bool value) { - _has_bits_[0] |= 0x00000004u; - packed_ = value; + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.packed_ = value; } inline void FieldOptions::set_packed(bool value) { _internal_set_packed(value); @@ -13013,18 +13094,18 @@ // optional .google.protobuf.FieldOptions.JSType jstype = 6 [default = JS_NORMAL]; inline bool FieldOptions::_internal_has_jstype() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool FieldOptions::has_jstype() const { return _internal_has_jstype(); } inline void FieldOptions::clear_jstype() { - jstype_ = 0; - _has_bits_[0] &= ~0x00000002u; + _impl_.jstype_ = 0; + _impl_._has_bits_[0] &= ~0x00000002u; } inline ::PROTOBUF_NAMESPACE_ID::FieldOptions_JSType FieldOptions::_internal_jstype() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::FieldOptions_JSType >(jstype_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::FieldOptions_JSType >(_impl_.jstype_); } inline ::PROTOBUF_NAMESPACE_ID::FieldOptions_JSType FieldOptions::jstype() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.jstype) @@ -13032,8 +13113,8 @@ } inline void FieldOptions::_internal_set_jstype(::PROTOBUF_NAMESPACE_ID::FieldOptions_JSType value) { assert(::PROTOBUF_NAMESPACE_ID::FieldOptions_JSType_IsValid(value)); - _has_bits_[0] |= 0x00000002u; - jstype_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.jstype_ = value; } inline void FieldOptions::set_jstype(::PROTOBUF_NAMESPACE_ID::FieldOptions_JSType value) { _internal_set_jstype(value); @@ -13042,26 +13123,26 @@ // optional bool lazy = 5 [default = false]; inline bool FieldOptions::_internal_has_lazy() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool FieldOptions::has_lazy() const { return _internal_has_lazy(); } inline void FieldOptions::clear_lazy() { - lazy_ = false; - _has_bits_[0] &= ~0x00000008u; + _impl_.lazy_ = false; + _impl_._has_bits_[0] &= ~0x00000008u; } inline bool FieldOptions::_internal_lazy() const { - return lazy_; + return _impl_.lazy_; } inline bool FieldOptions::lazy() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.lazy) return _internal_lazy(); } inline void FieldOptions::_internal_set_lazy(bool value) { - _has_bits_[0] |= 0x00000008u; - lazy_ = value; + _impl_._has_bits_[0] |= 0x00000008u; + _impl_.lazy_ = value; } inline void FieldOptions::set_lazy(bool value) { _internal_set_lazy(value); @@ -13070,26 +13151,26 @@ // optional bool unverified_lazy = 15 [default = false]; inline bool FieldOptions::_internal_has_unverified_lazy() const { - bool value = (_has_bits_[0] & 0x00000010u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool FieldOptions::has_unverified_lazy() const { return _internal_has_unverified_lazy(); } inline void FieldOptions::clear_unverified_lazy() { - unverified_lazy_ = false; - _has_bits_[0] &= ~0x00000010u; + _impl_.unverified_lazy_ = false; + _impl_._has_bits_[0] &= ~0x00000010u; } inline bool FieldOptions::_internal_unverified_lazy() const { - return unverified_lazy_; + return _impl_.unverified_lazy_; } inline bool FieldOptions::unverified_lazy() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.unverified_lazy) return _internal_unverified_lazy(); } inline void FieldOptions::_internal_set_unverified_lazy(bool value) { - _has_bits_[0] |= 0x00000010u; - unverified_lazy_ = value; + _impl_._has_bits_[0] |= 0x00000010u; + _impl_.unverified_lazy_ = value; } inline void FieldOptions::set_unverified_lazy(bool value) { _internal_set_unverified_lazy(value); @@ -13098,26 +13179,26 @@ // optional bool deprecated = 3 [default = false]; inline bool FieldOptions::_internal_has_deprecated() const { - bool value = (_has_bits_[0] & 0x00000020u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000020u) != 0; return value; } inline bool FieldOptions::has_deprecated() const { return _internal_has_deprecated(); } inline void FieldOptions::clear_deprecated() { - deprecated_ = false; - _has_bits_[0] &= ~0x00000020u; + _impl_.deprecated_ = false; + _impl_._has_bits_[0] &= ~0x00000020u; } inline bool FieldOptions::_internal_deprecated() const { - return deprecated_; + return _impl_.deprecated_; } inline bool FieldOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.deprecated) return _internal_deprecated(); } inline void FieldOptions::_internal_set_deprecated(bool value) { - _has_bits_[0] |= 0x00000020u; - deprecated_ = value; + _impl_._has_bits_[0] |= 0x00000020u; + _impl_.deprecated_ = value; } inline void FieldOptions::set_deprecated(bool value) { _internal_set_deprecated(value); @@ -13126,26 +13207,26 @@ // optional bool weak = 10 [default = false]; inline bool FieldOptions::_internal_has_weak() const { - bool value = (_has_bits_[0] & 0x00000040u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000040u) != 0; return value; } inline bool FieldOptions::has_weak() const { return _internal_has_weak(); } inline void FieldOptions::clear_weak() { - weak_ = false; - _has_bits_[0] &= ~0x00000040u; + _impl_.weak_ = false; + _impl_._has_bits_[0] &= ~0x00000040u; } inline bool FieldOptions::_internal_weak() const { - return weak_; + return _impl_.weak_; } inline bool FieldOptions::weak() const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.weak) return _internal_weak(); } inline void FieldOptions::_internal_set_weak(bool value) { - _has_bits_[0] |= 0x00000040u; - weak_ = value; + _impl_._has_bits_[0] |= 0x00000040u; + _impl_.weak_ = value; } inline void FieldOptions::set_weak(bool value) { _internal_set_weak(value); @@ -13154,32 +13235,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int FieldOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int FieldOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void FieldOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* FieldOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FieldOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* FieldOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& FieldOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& FieldOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FieldOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* FieldOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* FieldOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -13189,7 +13270,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& FieldOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.FieldOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -13198,32 +13279,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int OneofOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int OneofOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void OneofOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* OneofOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.OneofOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* OneofOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.OneofOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& OneofOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& OneofOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.OneofOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* OneofOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* OneofOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -13233,7 +13314,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& OneofOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.OneofOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -13242,26 +13323,26 @@ // optional bool allow_alias = 2; inline bool EnumOptions::_internal_has_allow_alias() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool EnumOptions::has_allow_alias() const { return _internal_has_allow_alias(); } inline void EnumOptions::clear_allow_alias() { - allow_alias_ = false; - _has_bits_[0] &= ~0x00000001u; + _impl_.allow_alias_ = false; + _impl_._has_bits_[0] &= ~0x00000001u; } inline bool EnumOptions::_internal_allow_alias() const { - return allow_alias_; + return _impl_.allow_alias_; } inline bool EnumOptions::allow_alias() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.allow_alias) return _internal_allow_alias(); } inline void EnumOptions::_internal_set_allow_alias(bool value) { - _has_bits_[0] |= 0x00000001u; - allow_alias_ = value; + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.allow_alias_ = value; } inline void EnumOptions::set_allow_alias(bool value) { _internal_set_allow_alias(value); @@ -13270,26 +13351,26 @@ // optional bool deprecated = 3 [default = false]; inline bool EnumOptions::_internal_has_deprecated() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool EnumOptions::has_deprecated() const { return _internal_has_deprecated(); } inline void EnumOptions::clear_deprecated() { - deprecated_ = false; - _has_bits_[0] &= ~0x00000002u; + _impl_.deprecated_ = false; + _impl_._has_bits_[0] &= ~0x00000002u; } inline bool EnumOptions::_internal_deprecated() const { - return deprecated_; + return _impl_.deprecated_; } inline bool EnumOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.deprecated) return _internal_deprecated(); } inline void EnumOptions::_internal_set_deprecated(bool value) { - _has_bits_[0] |= 0x00000002u; - deprecated_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.deprecated_ = value; } inline void EnumOptions::set_deprecated(bool value) { _internal_set_deprecated(value); @@ -13298,32 +13379,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int EnumOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int EnumOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void EnumOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* EnumOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& EnumOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& EnumOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -13333,7 +13414,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& EnumOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -13342,26 +13423,26 @@ // optional bool deprecated = 1 [default = false]; inline bool EnumValueOptions::_internal_has_deprecated() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool EnumValueOptions::has_deprecated() const { return _internal_has_deprecated(); } inline void EnumValueOptions::clear_deprecated() { - deprecated_ = false; - _has_bits_[0] &= ~0x00000001u; + _impl_.deprecated_ = false; + _impl_._has_bits_[0] &= ~0x00000001u; } inline bool EnumValueOptions::_internal_deprecated() const { - return deprecated_; + return _impl_.deprecated_; } inline bool EnumValueOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.deprecated) return _internal_deprecated(); } inline void EnumValueOptions::_internal_set_deprecated(bool value) { - _has_bits_[0] |= 0x00000001u; - deprecated_ = value; + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.deprecated_ = value; } inline void EnumValueOptions::set_deprecated(bool value) { _internal_set_deprecated(value); @@ -13370,32 +13451,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int EnumValueOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int EnumValueOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void EnumValueOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumValueOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValueOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* EnumValueOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumValueOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& EnumValueOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& EnumValueOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValueOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumValueOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* EnumValueOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -13405,7 +13486,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& EnumValueOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumValueOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -13414,26 +13495,26 @@ // optional bool deprecated = 33 [default = false]; inline bool ServiceOptions::_internal_has_deprecated() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool ServiceOptions::has_deprecated() const { return _internal_has_deprecated(); } inline void ServiceOptions::clear_deprecated() { - deprecated_ = false; - _has_bits_[0] &= ~0x00000001u; + _impl_.deprecated_ = false; + _impl_._has_bits_[0] &= ~0x00000001u; } inline bool ServiceOptions::_internal_deprecated() const { - return deprecated_; + return _impl_.deprecated_; } inline bool ServiceOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.deprecated) return _internal_deprecated(); } inline void ServiceOptions::_internal_set_deprecated(bool value) { - _has_bits_[0] |= 0x00000001u; - deprecated_ = value; + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.deprecated_ = value; } inline void ServiceOptions::set_deprecated(bool value) { _internal_set_deprecated(value); @@ -13442,32 +13523,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int ServiceOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int ServiceOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void ServiceOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* ServiceOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.ServiceOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* ServiceOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.ServiceOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& ServiceOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& ServiceOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.ServiceOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* ServiceOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* ServiceOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -13477,7 +13558,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& ServiceOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.ServiceOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -13486,26 +13567,26 @@ // optional bool deprecated = 33 [default = false]; inline bool MethodOptions::_internal_has_deprecated() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool MethodOptions::has_deprecated() const { return _internal_has_deprecated(); } inline void MethodOptions::clear_deprecated() { - deprecated_ = false; - _has_bits_[0] &= ~0x00000001u; + _impl_.deprecated_ = false; + _impl_._has_bits_[0] &= ~0x00000001u; } inline bool MethodOptions::_internal_deprecated() const { - return deprecated_; + return _impl_.deprecated_; } inline bool MethodOptions::deprecated() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.deprecated) return _internal_deprecated(); } inline void MethodOptions::_internal_set_deprecated(bool value) { - _has_bits_[0] |= 0x00000001u; - deprecated_ = value; + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.deprecated_ = value; } inline void MethodOptions::set_deprecated(bool value) { _internal_set_deprecated(value); @@ -13514,18 +13595,18 @@ // optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34 [default = IDEMPOTENCY_UNKNOWN]; inline bool MethodOptions::_internal_has_idempotency_level() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool MethodOptions::has_idempotency_level() const { return _internal_has_idempotency_level(); } inline void MethodOptions::clear_idempotency_level() { - idempotency_level_ = 0; - _has_bits_[0] &= ~0x00000002u; + _impl_.idempotency_level_ = 0; + _impl_._has_bits_[0] &= ~0x00000002u; } inline ::PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel MethodOptions::_internal_idempotency_level() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel >(idempotency_level_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel >(_impl_.idempotency_level_); } inline ::PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel MethodOptions::idempotency_level() const { // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.idempotency_level) @@ -13533,8 +13614,8 @@ } inline void MethodOptions::_internal_set_idempotency_level(::PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel value) { assert(::PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel_IsValid(value)); - _has_bits_[0] |= 0x00000002u; - idempotency_level_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.idempotency_level_ = value; } inline void MethodOptions::set_idempotency_level(::PROTOBUF_NAMESPACE_ID::MethodOptions_IdempotencyLevel value) { _internal_set_idempotency_level(value); @@ -13543,32 +13624,32 @@ // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; inline int MethodOptions::_internal_uninterpreted_option_size() const { - return uninterpreted_option_.size(); + return _impl_.uninterpreted_option_.size(); } inline int MethodOptions::uninterpreted_option_size() const { return _internal_uninterpreted_option_size(); } inline void MethodOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); + _impl_.uninterpreted_option_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* MethodOptions::mutable_uninterpreted_option(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.MethodOptions.uninterpreted_option) - return uninterpreted_option_.Mutable(index); + return _impl_.uninterpreted_option_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >* MethodOptions::mutable_uninterpreted_option() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.MethodOptions.uninterpreted_option) - return &uninterpreted_option_; + return &_impl_.uninterpreted_option_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& MethodOptions::_internal_uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); + return _impl_.uninterpreted_option_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption& MethodOptions::uninterpreted_option(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.MethodOptions.uninterpreted_option) return _internal_uninterpreted_option(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* MethodOptions::_internal_add_uninterpreted_option() { - return uninterpreted_option_.Add(); + return _impl_.uninterpreted_option_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* MethodOptions::add_uninterpreted_option() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption* _add = _internal_add_uninterpreted_option(); @@ -13578,7 +13659,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption >& MethodOptions::uninterpreted_option() const { // @@protoc_insertion_point(field_list:google.protobuf.MethodOptions.uninterpreted_option) - return uninterpreted_option_; + return _impl_.uninterpreted_option_; } // ------------------------------------------------------------------- @@ -13587,15 +13668,15 @@ // required string name_part = 1; inline bool UninterpretedOption_NamePart::_internal_has_name_part() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool UninterpretedOption_NamePart::has_name_part() const { return _internal_has_name_part(); } inline void UninterpretedOption_NamePart::clear_name_part() { - name_part_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.name_part_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& UninterpretedOption_NamePart::name_part() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.name_part) @@ -13604,8 +13685,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void UninterpretedOption_NamePart::set_name_part(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - name_part_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_part_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.NamePart.name_part) } inline std::string* UninterpretedOption_NamePart::mutable_name_part() { @@ -13614,40 +13695,40 @@ return _s; } inline const std::string& UninterpretedOption_NamePart::_internal_name_part() const { - return name_part_.Get(); + return _impl_.name_part_.Get(); } inline void UninterpretedOption_NamePart::_internal_set_name_part(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - name_part_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.name_part_.Set(value, GetArenaForAllocation()); } inline std::string* UninterpretedOption_NamePart::_internal_mutable_name_part() { - _has_bits_[0] |= 0x00000001u; - return name_part_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.name_part_.Mutable(GetArenaForAllocation()); } inline std::string* UninterpretedOption_NamePart::release_name_part() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.NamePart.name_part) if (!_internal_has_name_part()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = name_part_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.name_part_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_part_.IsDefault()) { - name_part_.Set("", GetArenaForAllocation()); + if (_impl_.name_part_.IsDefault()) { + _impl_.name_part_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void UninterpretedOption_NamePart::set_allocated_name_part(std::string* name_part) { if (name_part != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - name_part_.SetAllocated(name_part, GetArenaForAllocation()); + _impl_.name_part_.SetAllocated(name_part, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_part_.IsDefault()) { - name_part_.Set("", GetArenaForAllocation()); + if (_impl_.name_part_.IsDefault()) { + _impl_.name_part_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.NamePart.name_part) @@ -13655,26 +13736,26 @@ // required bool is_extension = 2; inline bool UninterpretedOption_NamePart::_internal_has_is_extension() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool UninterpretedOption_NamePart::has_is_extension() const { return _internal_has_is_extension(); } inline void UninterpretedOption_NamePart::clear_is_extension() { - is_extension_ = false; - _has_bits_[0] &= ~0x00000002u; + _impl_.is_extension_ = false; + _impl_._has_bits_[0] &= ~0x00000002u; } inline bool UninterpretedOption_NamePart::_internal_is_extension() const { - return is_extension_; + return _impl_.is_extension_; } inline bool UninterpretedOption_NamePart::is_extension() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.NamePart.is_extension) return _internal_is_extension(); } inline void UninterpretedOption_NamePart::_internal_set_is_extension(bool value) { - _has_bits_[0] |= 0x00000002u; - is_extension_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.is_extension_ = value; } inline void UninterpretedOption_NamePart::set_is_extension(bool value) { _internal_set_is_extension(value); @@ -13687,32 +13768,32 @@ // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; inline int UninterpretedOption::_internal_name_size() const { - return name_.size(); + return _impl_.name_.size(); } inline int UninterpretedOption::name_size() const { return _internal_name_size(); } inline void UninterpretedOption::clear_name() { - name_.Clear(); + _impl_.name_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* UninterpretedOption::mutable_name(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.UninterpretedOption.name) - return name_.Mutable(index); + return _impl_.name_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart >* UninterpretedOption::mutable_name() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.UninterpretedOption.name) - return &name_; + return &_impl_.name_; } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart& UninterpretedOption::_internal_name(int index) const { - return name_.Get(index); + return _impl_.name_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart& UninterpretedOption::name(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.name) return _internal_name(index); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* UninterpretedOption::_internal_add_name() { - return name_.Add(); + return _impl_.name_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* UninterpretedOption::add_name() { ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart* _add = _internal_add_name(); @@ -13722,20 +13803,20 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::UninterpretedOption_NamePart >& UninterpretedOption::name() const { // @@protoc_insertion_point(field_list:google.protobuf.UninterpretedOption.name) - return name_; + return _impl_.name_; } // optional string identifier_value = 3; inline bool UninterpretedOption::_internal_has_identifier_value() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool UninterpretedOption::has_identifier_value() const { return _internal_has_identifier_value(); } inline void UninterpretedOption::clear_identifier_value() { - identifier_value_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.identifier_value_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& UninterpretedOption::identifier_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.identifier_value) @@ -13744,8 +13825,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void UninterpretedOption::set_identifier_value(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - identifier_value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.identifier_value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.identifier_value) } inline std::string* UninterpretedOption::mutable_identifier_value() { @@ -13754,40 +13835,40 @@ return _s; } inline const std::string& UninterpretedOption::_internal_identifier_value() const { - return identifier_value_.Get(); + return _impl_.identifier_value_.Get(); } inline void UninterpretedOption::_internal_set_identifier_value(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - identifier_value_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.identifier_value_.Set(value, GetArenaForAllocation()); } inline std::string* UninterpretedOption::_internal_mutable_identifier_value() { - _has_bits_[0] |= 0x00000001u; - return identifier_value_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.identifier_value_.Mutable(GetArenaForAllocation()); } inline std::string* UninterpretedOption::release_identifier_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.identifier_value) if (!_internal_has_identifier_value()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = identifier_value_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.identifier_value_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (identifier_value_.IsDefault()) { - identifier_value_.Set("", GetArenaForAllocation()); + if (_impl_.identifier_value_.IsDefault()) { + _impl_.identifier_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void UninterpretedOption::set_allocated_identifier_value(std::string* identifier_value) { if (identifier_value != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - identifier_value_.SetAllocated(identifier_value, GetArenaForAllocation()); + _impl_.identifier_value_.SetAllocated(identifier_value, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (identifier_value_.IsDefault()) { - identifier_value_.Set("", GetArenaForAllocation()); + if (_impl_.identifier_value_.IsDefault()) { + _impl_.identifier_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.identifier_value) @@ -13795,26 +13876,26 @@ // optional uint64 positive_int_value = 4; inline bool UninterpretedOption::_internal_has_positive_int_value() const { - bool value = (_has_bits_[0] & 0x00000008u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000008u) != 0; return value; } inline bool UninterpretedOption::has_positive_int_value() const { return _internal_has_positive_int_value(); } inline void UninterpretedOption::clear_positive_int_value() { - positive_int_value_ = uint64_t{0u}; - _has_bits_[0] &= ~0x00000008u; + _impl_.positive_int_value_ = uint64_t{0u}; + _impl_._has_bits_[0] &= ~0x00000008u; } inline uint64_t UninterpretedOption::_internal_positive_int_value() const { - return positive_int_value_; + return _impl_.positive_int_value_; } inline uint64_t UninterpretedOption::positive_int_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.positive_int_value) return _internal_positive_int_value(); } inline void UninterpretedOption::_internal_set_positive_int_value(uint64_t value) { - _has_bits_[0] |= 0x00000008u; - positive_int_value_ = value; + _impl_._has_bits_[0] |= 0x00000008u; + _impl_.positive_int_value_ = value; } inline void UninterpretedOption::set_positive_int_value(uint64_t value) { _internal_set_positive_int_value(value); @@ -13823,26 +13904,26 @@ // optional int64 negative_int_value = 5; inline bool UninterpretedOption::_internal_has_negative_int_value() const { - bool value = (_has_bits_[0] & 0x00000010u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000010u) != 0; return value; } inline bool UninterpretedOption::has_negative_int_value() const { return _internal_has_negative_int_value(); } inline void UninterpretedOption::clear_negative_int_value() { - negative_int_value_ = int64_t{0}; - _has_bits_[0] &= ~0x00000010u; + _impl_.negative_int_value_ = int64_t{0}; + _impl_._has_bits_[0] &= ~0x00000010u; } inline int64_t UninterpretedOption::_internal_negative_int_value() const { - return negative_int_value_; + return _impl_.negative_int_value_; } inline int64_t UninterpretedOption::negative_int_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.negative_int_value) return _internal_negative_int_value(); } inline void UninterpretedOption::_internal_set_negative_int_value(int64_t value) { - _has_bits_[0] |= 0x00000010u; - negative_int_value_ = value; + _impl_._has_bits_[0] |= 0x00000010u; + _impl_.negative_int_value_ = value; } inline void UninterpretedOption::set_negative_int_value(int64_t value) { _internal_set_negative_int_value(value); @@ -13851,26 +13932,26 @@ // optional double double_value = 6; inline bool UninterpretedOption::_internal_has_double_value() const { - bool value = (_has_bits_[0] & 0x00000020u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000020u) != 0; return value; } inline bool UninterpretedOption::has_double_value() const { return _internal_has_double_value(); } inline void UninterpretedOption::clear_double_value() { - double_value_ = 0; - _has_bits_[0] &= ~0x00000020u; + _impl_.double_value_ = 0; + _impl_._has_bits_[0] &= ~0x00000020u; } inline double UninterpretedOption::_internal_double_value() const { - return double_value_; + return _impl_.double_value_; } inline double UninterpretedOption::double_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.double_value) return _internal_double_value(); } inline void UninterpretedOption::_internal_set_double_value(double value) { - _has_bits_[0] |= 0x00000020u; - double_value_ = value; + _impl_._has_bits_[0] |= 0x00000020u; + _impl_.double_value_ = value; } inline void UninterpretedOption::set_double_value(double value) { _internal_set_double_value(value); @@ -13879,15 +13960,15 @@ // optional bytes string_value = 7; inline bool UninterpretedOption::_internal_has_string_value() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool UninterpretedOption::has_string_value() const { return _internal_has_string_value(); } inline void UninterpretedOption::clear_string_value() { - string_value_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000002u; + _impl_.string_value_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& UninterpretedOption::string_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.string_value) @@ -13896,8 +13977,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void UninterpretedOption::set_string_value(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000002u; - string_value_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.string_value_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.string_value) } inline std::string* UninterpretedOption::mutable_string_value() { @@ -13906,40 +13987,40 @@ return _s; } inline const std::string& UninterpretedOption::_internal_string_value() const { - return string_value_.Get(); + return _impl_.string_value_.Get(); } inline void UninterpretedOption::_internal_set_string_value(const std::string& value) { - _has_bits_[0] |= 0x00000002u; - string_value_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.string_value_.Set(value, GetArenaForAllocation()); } inline std::string* UninterpretedOption::_internal_mutable_string_value() { - _has_bits_[0] |= 0x00000002u; - return string_value_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + return _impl_.string_value_.Mutable(GetArenaForAllocation()); } inline std::string* UninterpretedOption::release_string_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.string_value) if (!_internal_has_string_value()) { return nullptr; } - _has_bits_[0] &= ~0x00000002u; - auto* p = string_value_.Release(); + _impl_._has_bits_[0] &= ~0x00000002u; + auto* p = _impl_.string_value_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (string_value_.IsDefault()) { - string_value_.Set("", GetArenaForAllocation()); + if (_impl_.string_value_.IsDefault()) { + _impl_.string_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void UninterpretedOption::set_allocated_string_value(std::string* string_value) { if (string_value != nullptr) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - string_value_.SetAllocated(string_value, GetArenaForAllocation()); + _impl_.string_value_.SetAllocated(string_value, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (string_value_.IsDefault()) { - string_value_.Set("", GetArenaForAllocation()); + if (_impl_.string_value_.IsDefault()) { + _impl_.string_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.string_value) @@ -13947,15 +14028,15 @@ // optional string aggregate_value = 8; inline bool UninterpretedOption::_internal_has_aggregate_value() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool UninterpretedOption::has_aggregate_value() const { return _internal_has_aggregate_value(); } inline void UninterpretedOption::clear_aggregate_value() { - aggregate_value_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000004u; + _impl_.aggregate_value_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000004u; } inline const std::string& UninterpretedOption::aggregate_value() const { // @@protoc_insertion_point(field_get:google.protobuf.UninterpretedOption.aggregate_value) @@ -13964,8 +14045,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void UninterpretedOption::set_aggregate_value(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000004u; - aggregate_value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.aggregate_value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.UninterpretedOption.aggregate_value) } inline std::string* UninterpretedOption::mutable_aggregate_value() { @@ -13974,40 +14055,40 @@ return _s; } inline const std::string& UninterpretedOption::_internal_aggregate_value() const { - return aggregate_value_.Get(); + return _impl_.aggregate_value_.Get(); } inline void UninterpretedOption::_internal_set_aggregate_value(const std::string& value) { - _has_bits_[0] |= 0x00000004u; - aggregate_value_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.aggregate_value_.Set(value, GetArenaForAllocation()); } inline std::string* UninterpretedOption::_internal_mutable_aggregate_value() { - _has_bits_[0] |= 0x00000004u; - return aggregate_value_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000004u; + return _impl_.aggregate_value_.Mutable(GetArenaForAllocation()); } inline std::string* UninterpretedOption::release_aggregate_value() { // @@protoc_insertion_point(field_release:google.protobuf.UninterpretedOption.aggregate_value) if (!_internal_has_aggregate_value()) { return nullptr; } - _has_bits_[0] &= ~0x00000004u; - auto* p = aggregate_value_.Release(); + _impl_._has_bits_[0] &= ~0x00000004u; + auto* p = _impl_.aggregate_value_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (aggregate_value_.IsDefault()) { - aggregate_value_.Set("", GetArenaForAllocation()); + if (_impl_.aggregate_value_.IsDefault()) { + _impl_.aggregate_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void UninterpretedOption::set_allocated_aggregate_value(std::string* aggregate_value) { if (aggregate_value != nullptr) { - _has_bits_[0] |= 0x00000004u; + _impl_._has_bits_[0] |= 0x00000004u; } else { - _has_bits_[0] &= ~0x00000004u; + _impl_._has_bits_[0] &= ~0x00000004u; } - aggregate_value_.SetAllocated(aggregate_value, GetArenaForAllocation()); + _impl_.aggregate_value_.SetAllocated(aggregate_value, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (aggregate_value_.IsDefault()) { - aggregate_value_.Set("", GetArenaForAllocation()); + if (_impl_.aggregate_value_.IsDefault()) { + _impl_.aggregate_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.UninterpretedOption.aggregate_value) @@ -14019,27 +14100,27 @@ // repeated int32 path = 1 [packed = true]; inline int SourceCodeInfo_Location::_internal_path_size() const { - return path_.size(); + return _impl_.path_.size(); } inline int SourceCodeInfo_Location::path_size() const { return _internal_path_size(); } inline void SourceCodeInfo_Location::clear_path() { - path_.Clear(); + _impl_.path_.Clear(); } inline int32_t SourceCodeInfo_Location::_internal_path(int index) const { - return path_.Get(index); + return _impl_.path_.Get(index); } inline int32_t SourceCodeInfo_Location::path(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.path) return _internal_path(index); } inline void SourceCodeInfo_Location::set_path(int index, int32_t value) { - path_.Set(index, value); + _impl_.path_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.path) } inline void SourceCodeInfo_Location::_internal_add_path(int32_t value) { - path_.Add(value); + _impl_.path_.Add(value); } inline void SourceCodeInfo_Location::add_path(int32_t value) { _internal_add_path(value); @@ -14047,7 +14128,7 @@ } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& SourceCodeInfo_Location::_internal_path() const { - return path_; + return _impl_.path_; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& SourceCodeInfo_Location::path() const { @@ -14056,7 +14137,7 @@ } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* SourceCodeInfo_Location::_internal_mutable_path() { - return &path_; + return &_impl_.path_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* SourceCodeInfo_Location::mutable_path() { @@ -14066,27 +14147,27 @@ // repeated int32 span = 2 [packed = true]; inline int SourceCodeInfo_Location::_internal_span_size() const { - return span_.size(); + return _impl_.span_.size(); } inline int SourceCodeInfo_Location::span_size() const { return _internal_span_size(); } inline void SourceCodeInfo_Location::clear_span() { - span_.Clear(); + _impl_.span_.Clear(); } inline int32_t SourceCodeInfo_Location::_internal_span(int index) const { - return span_.Get(index); + return _impl_.span_.Get(index); } inline int32_t SourceCodeInfo_Location::span(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.span) return _internal_span(index); } inline void SourceCodeInfo_Location::set_span(int index, int32_t value) { - span_.Set(index, value); + _impl_.span_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.span) } inline void SourceCodeInfo_Location::_internal_add_span(int32_t value) { - span_.Add(value); + _impl_.span_.Add(value); } inline void SourceCodeInfo_Location::add_span(int32_t value) { _internal_add_span(value); @@ -14094,7 +14175,7 @@ } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& SourceCodeInfo_Location::_internal_span() const { - return span_; + return _impl_.span_; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& SourceCodeInfo_Location::span() const { @@ -14103,7 +14184,7 @@ } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* SourceCodeInfo_Location::_internal_mutable_span() { - return &span_; + return &_impl_.span_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* SourceCodeInfo_Location::mutable_span() { @@ -14113,15 +14194,15 @@ // optional string leading_comments = 3; inline bool SourceCodeInfo_Location::_internal_has_leading_comments() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool SourceCodeInfo_Location::has_leading_comments() const { return _internal_has_leading_comments(); } inline void SourceCodeInfo_Location::clear_leading_comments() { - leading_comments_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.leading_comments_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& SourceCodeInfo_Location::leading_comments() const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_comments) @@ -14130,8 +14211,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void SourceCodeInfo_Location::set_leading_comments(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - leading_comments_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.leading_comments_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_comments) } inline std::string* SourceCodeInfo_Location::mutable_leading_comments() { @@ -14140,40 +14221,40 @@ return _s; } inline const std::string& SourceCodeInfo_Location::_internal_leading_comments() const { - return leading_comments_.Get(); + return _impl_.leading_comments_.Get(); } inline void SourceCodeInfo_Location::_internal_set_leading_comments(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - leading_comments_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.leading_comments_.Set(value, GetArenaForAllocation()); } inline std::string* SourceCodeInfo_Location::_internal_mutable_leading_comments() { - _has_bits_[0] |= 0x00000001u; - return leading_comments_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.leading_comments_.Mutable(GetArenaForAllocation()); } inline std::string* SourceCodeInfo_Location::release_leading_comments() { // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.leading_comments) if (!_internal_has_leading_comments()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = leading_comments_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.leading_comments_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (leading_comments_.IsDefault()) { - leading_comments_.Set("", GetArenaForAllocation()); + if (_impl_.leading_comments_.IsDefault()) { + _impl_.leading_comments_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void SourceCodeInfo_Location::set_allocated_leading_comments(std::string* leading_comments) { if (leading_comments != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - leading_comments_.SetAllocated(leading_comments, GetArenaForAllocation()); + _impl_.leading_comments_.SetAllocated(leading_comments, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (leading_comments_.IsDefault()) { - leading_comments_.Set("", GetArenaForAllocation()); + if (_impl_.leading_comments_.IsDefault()) { + _impl_.leading_comments_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.leading_comments) @@ -14181,15 +14262,15 @@ // optional string trailing_comments = 4; inline bool SourceCodeInfo_Location::_internal_has_trailing_comments() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool SourceCodeInfo_Location::has_trailing_comments() const { return _internal_has_trailing_comments(); } inline void SourceCodeInfo_Location::clear_trailing_comments() { - trailing_comments_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000002u; + _impl_.trailing_comments_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000002u; } inline const std::string& SourceCodeInfo_Location::trailing_comments() const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.trailing_comments) @@ -14198,8 +14279,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void SourceCodeInfo_Location::set_trailing_comments(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000002u; - trailing_comments_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.trailing_comments_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.trailing_comments) } inline std::string* SourceCodeInfo_Location::mutable_trailing_comments() { @@ -14208,40 +14289,40 @@ return _s; } inline const std::string& SourceCodeInfo_Location::_internal_trailing_comments() const { - return trailing_comments_.Get(); + return _impl_.trailing_comments_.Get(); } inline void SourceCodeInfo_Location::_internal_set_trailing_comments(const std::string& value) { - _has_bits_[0] |= 0x00000002u; - trailing_comments_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.trailing_comments_.Set(value, GetArenaForAllocation()); } inline std::string* SourceCodeInfo_Location::_internal_mutable_trailing_comments() { - _has_bits_[0] |= 0x00000002u; - return trailing_comments_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000002u; + return _impl_.trailing_comments_.Mutable(GetArenaForAllocation()); } inline std::string* SourceCodeInfo_Location::release_trailing_comments() { // @@protoc_insertion_point(field_release:google.protobuf.SourceCodeInfo.Location.trailing_comments) if (!_internal_has_trailing_comments()) { return nullptr; } - _has_bits_[0] &= ~0x00000002u; - auto* p = trailing_comments_.Release(); + _impl_._has_bits_[0] &= ~0x00000002u; + auto* p = _impl_.trailing_comments_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (trailing_comments_.IsDefault()) { - trailing_comments_.Set("", GetArenaForAllocation()); + if (_impl_.trailing_comments_.IsDefault()) { + _impl_.trailing_comments_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void SourceCodeInfo_Location::set_allocated_trailing_comments(std::string* trailing_comments) { if (trailing_comments != nullptr) { - _has_bits_[0] |= 0x00000002u; + _impl_._has_bits_[0] |= 0x00000002u; } else { - _has_bits_[0] &= ~0x00000002u; + _impl_._has_bits_[0] &= ~0x00000002u; } - trailing_comments_.SetAllocated(trailing_comments, GetArenaForAllocation()); + _impl_.trailing_comments_.SetAllocated(trailing_comments, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (trailing_comments_.IsDefault()) { - trailing_comments_.Set("", GetArenaForAllocation()); + if (_impl_.trailing_comments_.IsDefault()) { + _impl_.trailing_comments_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceCodeInfo.Location.trailing_comments) @@ -14249,13 +14330,13 @@ // repeated string leading_detached_comments = 6; inline int SourceCodeInfo_Location::_internal_leading_detached_comments_size() const { - return leading_detached_comments_.size(); + return _impl_.leading_detached_comments_.size(); } inline int SourceCodeInfo_Location::leading_detached_comments_size() const { return _internal_leading_detached_comments_size(); } inline void SourceCodeInfo_Location::clear_leading_detached_comments() { - leading_detached_comments_.Clear(); + _impl_.leading_detached_comments_.Clear(); } inline std::string* SourceCodeInfo_Location::add_leading_detached_comments() { std::string* _s = _internal_add_leading_detached_comments(); @@ -14263,7 +14344,7 @@ return _s; } inline const std::string& SourceCodeInfo_Location::_internal_leading_detached_comments(int index) const { - return leading_detached_comments_.Get(index); + return _impl_.leading_detached_comments_.Get(index); } inline const std::string& SourceCodeInfo_Location::leading_detached_comments(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) @@ -14271,55 +14352,55 @@ } inline std::string* SourceCodeInfo_Location::mutable_leading_detached_comments(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) - return leading_detached_comments_.Mutable(index); + return _impl_.leading_detached_comments_.Mutable(index); } inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, const std::string& value) { - leading_detached_comments_.Mutable(index)->assign(value); + _impl_.leading_detached_comments_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, std::string&& value) { - leading_detached_comments_.Mutable(index)->assign(std::move(value)); + _impl_.leading_detached_comments_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); - leading_detached_comments_.Mutable(index)->assign(value); + _impl_.leading_detached_comments_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } inline void SourceCodeInfo_Location::set_leading_detached_comments(int index, const char* value, size_t size) { - leading_detached_comments_.Mutable(index)->assign( + _impl_.leading_detached_comments_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } inline std::string* SourceCodeInfo_Location::_internal_add_leading_detached_comments() { - return leading_detached_comments_.Add(); + return _impl_.leading_detached_comments_.Add(); } inline void SourceCodeInfo_Location::add_leading_detached_comments(const std::string& value) { - leading_detached_comments_.Add()->assign(value); + _impl_.leading_detached_comments_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } inline void SourceCodeInfo_Location::add_leading_detached_comments(std::string&& value) { - leading_detached_comments_.Add(std::move(value)); + _impl_.leading_detached_comments_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } inline void SourceCodeInfo_Location::add_leading_detached_comments(const char* value) { GOOGLE_DCHECK(value != nullptr); - leading_detached_comments_.Add()->assign(value); + _impl_.leading_detached_comments_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } inline void SourceCodeInfo_Location::add_leading_detached_comments(const char* value, size_t size) { - leading_detached_comments_.Add()->assign(reinterpret_cast<const char*>(value), size); + _impl_.leading_detached_comments_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& SourceCodeInfo_Location::leading_detached_comments() const { // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) - return leading_detached_comments_; + return _impl_.leading_detached_comments_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* SourceCodeInfo_Location::mutable_leading_detached_comments() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) - return &leading_detached_comments_; + return &_impl_.leading_detached_comments_; } // ------------------------------------------------------------------- @@ -14328,32 +14409,32 @@ // repeated .google.protobuf.SourceCodeInfo.Location location = 1; inline int SourceCodeInfo::_internal_location_size() const { - return location_.size(); + return _impl_.location_.size(); } inline int SourceCodeInfo::location_size() const { return _internal_location_size(); } inline void SourceCodeInfo::clear_location() { - location_.Clear(); + _impl_.location_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* SourceCodeInfo::mutable_location(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.SourceCodeInfo.location) - return location_.Mutable(index); + return _impl_.location_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location >* SourceCodeInfo::mutable_location() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.SourceCodeInfo.location) - return &location_; + return &_impl_.location_; } inline const ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location& SourceCodeInfo::_internal_location(int index) const { - return location_.Get(index); + return _impl_.location_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location& SourceCodeInfo::location(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.SourceCodeInfo.location) return _internal_location(index); } inline ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* SourceCodeInfo::_internal_add_location() { - return location_.Add(); + return _impl_.location_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* SourceCodeInfo::add_location() { ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location* _add = _internal_add_location(); @@ -14363,7 +14444,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::SourceCodeInfo_Location >& SourceCodeInfo::location() const { // @@protoc_insertion_point(field_list:google.protobuf.SourceCodeInfo.location) - return location_; + return _impl_.location_; } // ------------------------------------------------------------------- @@ -14372,27 +14453,27 @@ // repeated int32 path = 1 [packed = true]; inline int GeneratedCodeInfo_Annotation::_internal_path_size() const { - return path_.size(); + return _impl_.path_.size(); } inline int GeneratedCodeInfo_Annotation::path_size() const { return _internal_path_size(); } inline void GeneratedCodeInfo_Annotation::clear_path() { - path_.Clear(); + _impl_.path_.Clear(); } inline int32_t GeneratedCodeInfo_Annotation::_internal_path(int index) const { - return path_.Get(index); + return _impl_.path_.Get(index); } inline int32_t GeneratedCodeInfo_Annotation::path(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.path) return _internal_path(index); } inline void GeneratedCodeInfo_Annotation::set_path(int index, int32_t value) { - path_.Set(index, value); + _impl_.path_.Set(index, value); // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.path) } inline void GeneratedCodeInfo_Annotation::_internal_add_path(int32_t value) { - path_.Add(value); + _impl_.path_.Add(value); } inline void GeneratedCodeInfo_Annotation::add_path(int32_t value) { _internal_add_path(value); @@ -14400,7 +14481,7 @@ } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& GeneratedCodeInfo_Annotation::_internal_path() const { - return path_; + return _impl_.path_; } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >& GeneratedCodeInfo_Annotation::path() const { @@ -14409,7 +14490,7 @@ } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* GeneratedCodeInfo_Annotation::_internal_mutable_path() { - return &path_; + return &_impl_.path_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >* GeneratedCodeInfo_Annotation::mutable_path() { @@ -14419,15 +14500,15 @@ // optional string source_file = 2; inline bool GeneratedCodeInfo_Annotation::_internal_has_source_file() const { - bool value = (_has_bits_[0] & 0x00000001u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000001u) != 0; return value; } inline bool GeneratedCodeInfo_Annotation::has_source_file() const { return _internal_has_source_file(); } inline void GeneratedCodeInfo_Annotation::clear_source_file() { - source_file_.ClearToEmpty(); - _has_bits_[0] &= ~0x00000001u; + _impl_.source_file_.ClearToEmpty(); + _impl_._has_bits_[0] &= ~0x00000001u; } inline const std::string& GeneratedCodeInfo_Annotation::source_file() const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.source_file) @@ -14436,8 +14517,8 @@ template <typename ArgT0, typename... ArgT> inline PROTOBUF_ALWAYS_INLINE void GeneratedCodeInfo_Annotation::set_source_file(ArgT0&& arg0, ArgT... args) { - _has_bits_[0] |= 0x00000001u; - source_file_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.source_file_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.GeneratedCodeInfo.Annotation.source_file) } inline std::string* GeneratedCodeInfo_Annotation::mutable_source_file() { @@ -14446,40 +14527,40 @@ return _s; } inline const std::string& GeneratedCodeInfo_Annotation::_internal_source_file() const { - return source_file_.Get(); + return _impl_.source_file_.Get(); } inline void GeneratedCodeInfo_Annotation::_internal_set_source_file(const std::string& value) { - _has_bits_[0] |= 0x00000001u; - source_file_.Set(value, GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + _impl_.source_file_.Set(value, GetArenaForAllocation()); } inline std::string* GeneratedCodeInfo_Annotation::_internal_mutable_source_file() { - _has_bits_[0] |= 0x00000001u; - return source_file_.Mutable(GetArenaForAllocation()); + _impl_._has_bits_[0] |= 0x00000001u; + return _impl_.source_file_.Mutable(GetArenaForAllocation()); } inline std::string* GeneratedCodeInfo_Annotation::release_source_file() { // @@protoc_insertion_point(field_release:google.protobuf.GeneratedCodeInfo.Annotation.source_file) if (!_internal_has_source_file()) { return nullptr; } - _has_bits_[0] &= ~0x00000001u; - auto* p = source_file_.Release(); + _impl_._has_bits_[0] &= ~0x00000001u; + auto* p = _impl_.source_file_.Release(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (source_file_.IsDefault()) { - source_file_.Set("", GetArenaForAllocation()); + if (_impl_.source_file_.IsDefault()) { + _impl_.source_file_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING return p; } inline void GeneratedCodeInfo_Annotation::set_allocated_source_file(std::string* source_file) { if (source_file != nullptr) { - _has_bits_[0] |= 0x00000001u; + _impl_._has_bits_[0] |= 0x00000001u; } else { - _has_bits_[0] &= ~0x00000001u; + _impl_._has_bits_[0] &= ~0x00000001u; } - source_file_.SetAllocated(source_file, GetArenaForAllocation()); + _impl_.source_file_.SetAllocated(source_file, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (source_file_.IsDefault()) { - source_file_.Set("", GetArenaForAllocation()); + if (_impl_.source_file_.IsDefault()) { + _impl_.source_file_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.GeneratedCodeInfo.Annotation.source_file) @@ -14487,26 +14568,26 @@ // optional int32 begin = 3; inline bool GeneratedCodeInfo_Annotation::_internal_has_begin() const { - bool value = (_has_bits_[0] & 0x00000002u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000002u) != 0; return value; } inline bool GeneratedCodeInfo_Annotation::has_begin() const { return _internal_has_begin(); } inline void GeneratedCodeInfo_Annotation::clear_begin() { - begin_ = 0; - _has_bits_[0] &= ~0x00000002u; + _impl_.begin_ = 0; + _impl_._has_bits_[0] &= ~0x00000002u; } inline int32_t GeneratedCodeInfo_Annotation::_internal_begin() const { - return begin_; + return _impl_.begin_; } inline int32_t GeneratedCodeInfo_Annotation::begin() const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.begin) return _internal_begin(); } inline void GeneratedCodeInfo_Annotation::_internal_set_begin(int32_t value) { - _has_bits_[0] |= 0x00000002u; - begin_ = value; + _impl_._has_bits_[0] |= 0x00000002u; + _impl_.begin_ = value; } inline void GeneratedCodeInfo_Annotation::set_begin(int32_t value) { _internal_set_begin(value); @@ -14515,26 +14596,26 @@ // optional int32 end = 4; inline bool GeneratedCodeInfo_Annotation::_internal_has_end() const { - bool value = (_has_bits_[0] & 0x00000004u) != 0; + bool value = (_impl_._has_bits_[0] & 0x00000004u) != 0; return value; } inline bool GeneratedCodeInfo_Annotation::has_end() const { return _internal_has_end(); } inline void GeneratedCodeInfo_Annotation::clear_end() { - end_ = 0; - _has_bits_[0] &= ~0x00000004u; + _impl_.end_ = 0; + _impl_._has_bits_[0] &= ~0x00000004u; } inline int32_t GeneratedCodeInfo_Annotation::_internal_end() const { - return end_; + return _impl_.end_; } inline int32_t GeneratedCodeInfo_Annotation::end() const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.Annotation.end) return _internal_end(); } inline void GeneratedCodeInfo_Annotation::_internal_set_end(int32_t value) { - _has_bits_[0] |= 0x00000004u; - end_ = value; + _impl_._has_bits_[0] |= 0x00000004u; + _impl_.end_ = value; } inline void GeneratedCodeInfo_Annotation::set_end(int32_t value) { _internal_set_end(value); @@ -14547,32 +14628,32 @@ // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; inline int GeneratedCodeInfo::_internal_annotation_size() const { - return annotation_.size(); + return _impl_.annotation_.size(); } inline int GeneratedCodeInfo::annotation_size() const { return _internal_annotation_size(); } inline void GeneratedCodeInfo::clear_annotation() { - annotation_.Clear(); + _impl_.annotation_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::mutable_annotation(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.GeneratedCodeInfo.annotation) - return annotation_.Mutable(index); + return _impl_.annotation_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation >* GeneratedCodeInfo::mutable_annotation() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.GeneratedCodeInfo.annotation) - return &annotation_; + return &_impl_.annotation_; } inline const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation& GeneratedCodeInfo::_internal_annotation(int index) const { - return annotation_.Get(index); + return _impl_.annotation_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation& GeneratedCodeInfo::annotation(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.GeneratedCodeInfo.annotation) return _internal_annotation(index); } inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::_internal_add_annotation() { - return annotation_.Add(); + return _impl_.annotation_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* GeneratedCodeInfo::add_annotation() { ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation* _add = _internal_add_annotation(); @@ -14582,7 +14663,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::GeneratedCodeInfo_Annotation >& GeneratedCodeInfo::annotation() const { // @@protoc_insertion_point(field_list:google.protobuf.GeneratedCodeInfo.annotation) - return annotation_; + return _impl_.annotation_; } #ifdef __GNUC__
diff --git a/src/google/protobuf/descriptor.proto b/src/google/protobuf/descriptor.proto index 49ec653..f8eb216 100644 --- a/src/google/protobuf/descriptor.proto +++ b/src/google/protobuf/descriptor.proto
@@ -740,8 +740,8 @@ // The name of the uninterpreted option. Each string represents a segment in // a dot-separated name. is_extension is true iff a segment represents an // extension (denoted with parentheses in options specs in .proto files). - // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - // "foo.(bar.baz).qux". + // E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + // "foo.(bar.baz).moo". message NamePart { required string name_part = 1; required bool is_extension = 2; @@ -868,13 +868,13 @@ // // Comment attached to baz. // // Another line attached to baz. // - // // Comment attached to qux. + // // Comment attached to moo. // // - // // Another line attached to qux. - // optional double qux = 4; + // // Another line attached to moo. + // optional double moo = 4; // // // Detached comment for corge. This is not leading or trailing comments - // // to qux or corge because there are blank lines separating it from + // // to moo or corge because there are blank lines separating it from // // both. // // // Detached comment for corge paragraph 2.
diff --git a/src/google/protobuf/descriptor_unittest.cc b/src/google/protobuf/descriptor_unittest.cc index 2f57cd7..70cfd41 100644 --- a/src/google/protobuf/descriptor_unittest.cc +++ b/src/google/protobuf/descriptor_unittest.cc
@@ -628,7 +628,7 @@ // required string foo = 1; // optional TestEnum bar = 6; // repeated TestForeign baz = 500000000; - // optional group qux = 15 {} + // optional group moo = 15 {} // } // // // in "bar.proto" @@ -636,7 +636,7 @@ // message TestMessage2 { // required string foo = 1; // required string bar = 2; - // required string quux = 6; + // required string mooo = 6; // } // // // in "map.proto" @@ -654,7 +654,7 @@ // optional int32 field_name6 = 6 [json_name = "@type"]; // } // - // We cheat and use TestForeign as the type for qux rather than create + // We cheat and use TestForeign as the type for moo rather than create // an actual nested type. // // Since all primitive types (including string) use the same building @@ -678,7 +678,7 @@ AddField(message, "baz", 500000000, FieldDescriptorProto::LABEL_REPEATED, FieldDescriptorProto::TYPE_MESSAGE) ->set_type_name("TestForeign"); - AddField(message, "qux", 15, FieldDescriptorProto::LABEL_OPTIONAL, + AddField(message, "moo", 15, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_GROUP) ->set_type_name("TestForeign"); @@ -691,7 +691,7 @@ FieldDescriptorProto::TYPE_STRING); AddField(message2, "bar", 2, FieldDescriptorProto::LABEL_REQUIRED, FieldDescriptorProto::TYPE_STRING); - AddField(message2, "quux", 6, FieldDescriptorProto::LABEL_REQUIRED, + AddField(message2, "mooo", 6, FieldDescriptorProto::LABEL_REQUIRED, FieldDescriptorProto::TYPE_STRING); FileDescriptorProto map_file; @@ -754,7 +754,7 @@ foo_ = message_->field(0); bar_ = message_->field(1); baz_ = message_->field(2); - qux_ = message_->field(3); + moo_ = message_->field(3); ASSERT_EQ(1, bar_file_->message_type_count()); message2_ = bar_file_->message_type(0); @@ -762,7 +762,7 @@ ASSERT_EQ(3, message2_->field_count()); foo2_ = message2_->field(0); bar2_ = message2_->field(1); - quux2_ = message2_->field(2); + mooo2_ = message2_->field(2); ASSERT_EQ(1, map_file_->message_type_count()); message3_ = map_file_->message_type(0); @@ -801,11 +801,11 @@ const FieldDescriptor* foo_; const FieldDescriptor* bar_; const FieldDescriptor* baz_; - const FieldDescriptor* qux_; + const FieldDescriptor* moo_; const FieldDescriptor* foo2_; const FieldDescriptor* bar2_; - const FieldDescriptor* quux2_; + const FieldDescriptor* mooo2_; const FieldDescriptor* map_; }; @@ -886,7 +886,7 @@ EXPECT_EQ(foo_, message_->field(0)); EXPECT_EQ(bar_, message_->field(1)); EXPECT_EQ(baz_, message_->field(2)); - EXPECT_EQ(qux_, message_->field(3)); + EXPECT_EQ(moo_, message_->field(3)); } TEST_F(DescriptorTest, FindFieldByName) { @@ -898,28 +898,28 @@ EXPECT_EQ(foo_, message_->FindFieldByName("foo")); EXPECT_EQ(bar_, message_->FindFieldByName("bar")); EXPECT_EQ(baz_, message_->FindFieldByName("baz")); - EXPECT_EQ(qux_, message_->FindFieldByName("qux")); + EXPECT_EQ(moo_, message_->FindFieldByName("moo")); EXPECT_TRUE(message_->FindFieldByName("no_such_field") == nullptr); - EXPECT_TRUE(message_->FindFieldByName("quux") == nullptr); + EXPECT_TRUE(message_->FindFieldByName("mooo") == nullptr); EXPECT_EQ(foo2_, message2_->FindFieldByName("foo")); EXPECT_EQ(bar2_, message2_->FindFieldByName("bar")); - EXPECT_EQ(quux2_, message2_->FindFieldByName("quux")); + EXPECT_EQ(mooo2_, message2_->FindFieldByName("mooo")); EXPECT_TRUE(message2_->FindFieldByName("baz") == nullptr); - EXPECT_TRUE(message2_->FindFieldByName("qux") == nullptr); + EXPECT_TRUE(message2_->FindFieldByName("moo") == nullptr); } TEST_F(DescriptorTest, FindFieldByNumber) { EXPECT_EQ(foo_, message_->FindFieldByNumber(1)); EXPECT_EQ(bar_, message_->FindFieldByNumber(6)); EXPECT_EQ(baz_, message_->FindFieldByNumber(500000000)); - EXPECT_EQ(qux_, message_->FindFieldByNumber(15)); + EXPECT_EQ(moo_, message_->FindFieldByNumber(15)); EXPECT_TRUE(message_->FindFieldByNumber(837592) == nullptr); EXPECT_TRUE(message_->FindFieldByNumber(2) == nullptr); EXPECT_EQ(foo2_, message2_->FindFieldByNumber(1)); EXPECT_EQ(bar2_, message2_->FindFieldByNumber(2)); - EXPECT_EQ(quux2_, message2_->FindFieldByNumber(6)); + EXPECT_EQ(mooo2_, message2_->FindFieldByNumber(6)); EXPECT_TRUE(message2_->FindFieldByNumber(15) == nullptr); EXPECT_TRUE(message2_->FindFieldByNumber(500000000) == nullptr); } @@ -928,32 +928,32 @@ EXPECT_EQ("foo", foo_->name()); EXPECT_EQ("bar", bar_->name()); EXPECT_EQ("baz", baz_->name()); - EXPECT_EQ("qux", qux_->name()); + EXPECT_EQ("moo", moo_->name()); } TEST_F(DescriptorTest, FieldFullName) { EXPECT_EQ("TestMessage.foo", foo_->full_name()); EXPECT_EQ("TestMessage.bar", bar_->full_name()); EXPECT_EQ("TestMessage.baz", baz_->full_name()); - EXPECT_EQ("TestMessage.qux", qux_->full_name()); + EXPECT_EQ("TestMessage.moo", moo_->full_name()); EXPECT_EQ("corge.grault.TestMessage2.foo", foo2_->full_name()); EXPECT_EQ("corge.grault.TestMessage2.bar", bar2_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.quux", quux2_->full_name()); + EXPECT_EQ("corge.grault.TestMessage2.mooo", mooo2_->full_name()); } TEST_F(DescriptorTest, PrintableNameIsFullNameForNonExtensionFields) { EXPECT_EQ("TestMessage.foo", foo_->PrintableNameForExtension()); EXPECT_EQ("TestMessage.bar", bar_->PrintableNameForExtension()); EXPECT_EQ("TestMessage.baz", baz_->PrintableNameForExtension()); - EXPECT_EQ("TestMessage.qux", qux_->PrintableNameForExtension()); + EXPECT_EQ("TestMessage.moo", moo_->PrintableNameForExtension()); EXPECT_EQ("corge.grault.TestMessage2.foo", foo2_->PrintableNameForExtension()); EXPECT_EQ("corge.grault.TestMessage2.bar", bar2_->PrintableNameForExtension()); - EXPECT_EQ("corge.grault.TestMessage2.quux", - quux2_->PrintableNameForExtension()); + EXPECT_EQ("corge.grault.TestMessage2.mooo", + mooo2_->PrintableNameForExtension()); } TEST_F(DescriptorTest, PrintableNameIsFullNameForNonMessageSetExtension) { @@ -1016,39 +1016,39 @@ EXPECT_EQ(foo_file_, foo_->file()); EXPECT_EQ(foo_file_, bar_->file()); EXPECT_EQ(foo_file_, baz_->file()); - EXPECT_EQ(foo_file_, qux_->file()); + EXPECT_EQ(foo_file_, moo_->file()); EXPECT_EQ(bar_file_, foo2_->file()); EXPECT_EQ(bar_file_, bar2_->file()); - EXPECT_EQ(bar_file_, quux2_->file()); + EXPECT_EQ(bar_file_, mooo2_->file()); } TEST_F(DescriptorTest, FieldIndex) { EXPECT_EQ(0, foo_->index()); EXPECT_EQ(1, bar_->index()); EXPECT_EQ(2, baz_->index()); - EXPECT_EQ(3, qux_->index()); + EXPECT_EQ(3, moo_->index()); } TEST_F(DescriptorTest, FieldNumber) { EXPECT_EQ(1, foo_->number()); EXPECT_EQ(6, bar_->number()); EXPECT_EQ(500000000, baz_->number()); - EXPECT_EQ(15, qux_->number()); + EXPECT_EQ(15, moo_->number()); } TEST_F(DescriptorTest, FieldType) { EXPECT_EQ(FieldDescriptor::TYPE_STRING, foo_->type()); EXPECT_EQ(FieldDescriptor::TYPE_ENUM, bar_->type()); EXPECT_EQ(FieldDescriptor::TYPE_MESSAGE, baz_->type()); - EXPECT_EQ(FieldDescriptor::TYPE_GROUP, qux_->type()); + EXPECT_EQ(FieldDescriptor::TYPE_GROUP, moo_->type()); } TEST_F(DescriptorTest, FieldLabel) { EXPECT_EQ(FieldDescriptor::LABEL_REQUIRED, foo_->label()); EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, bar_->label()); EXPECT_EQ(FieldDescriptor::LABEL_REPEATED, baz_->label()); - EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, qux_->label()); + EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, moo_->label()); EXPECT_TRUE(foo_->is_required()); EXPECT_FALSE(foo_->is_optional()); @@ -1089,18 +1089,18 @@ EXPECT_FALSE(foo_->has_default_value()); EXPECT_FALSE(bar_->has_default_value()); EXPECT_FALSE(baz_->has_default_value()); - EXPECT_FALSE(qux_->has_default_value()); + EXPECT_FALSE(moo_->has_default_value()); } TEST_F(DescriptorTest, FieldContainingType) { EXPECT_EQ(message_, foo_->containing_type()); EXPECT_EQ(message_, bar_->containing_type()); EXPECT_EQ(message_, baz_->containing_type()); - EXPECT_EQ(message_, qux_->containing_type()); + EXPECT_EQ(message_, moo_->containing_type()); EXPECT_EQ(message2_, foo2_->containing_type()); EXPECT_EQ(message2_, bar2_->containing_type()); - EXPECT_EQ(message2_, quux2_->containing_type()); + EXPECT_EQ(message2_, mooo2_->containing_type()); } TEST_F(DescriptorTest, FieldMessageType) { @@ -1108,13 +1108,13 @@ EXPECT_TRUE(bar_->message_type() == nullptr); EXPECT_EQ(foreign_, baz_->message_type()); - EXPECT_EQ(foreign_, qux_->message_type()); + EXPECT_EQ(foreign_, moo_->message_type()); } TEST_F(DescriptorTest, FieldEnumType) { EXPECT_TRUE(foo_->enum_type() == nullptr); EXPECT_TRUE(baz_->enum_type() == nullptr); - EXPECT_TRUE(qux_->enum_type() == nullptr); + EXPECT_TRUE(moo_->enum_type() == nullptr); EXPECT_EQ(enum_, bar_->enum_type()); } @@ -1708,7 +1708,7 @@ // message Foo {} // message Bar {} // enum Baz { A = 1; } - // enum Qux { B = 1; } + // enum Moo { B = 1; } // } // // // in "bar.proto" @@ -1716,8 +1716,8 @@ // message TestMessage2 { // message Foo {} // message Baz {} - // enum Qux { A = 1; } - // enum Quux { C = 1; } + // enum Moo { A = 1; } + // enum Mooo { C = 1; } // } // // TestMessage2 is primarily here to test FindNestedTypeByName and friends. @@ -1735,8 +1735,8 @@ AddNestedMessage(message, "Bar"); EnumDescriptorProto* baz = AddNestedEnum(message, "Baz"); AddEnumValue(baz, "A", 1); - EnumDescriptorProto* qux = AddNestedEnum(message, "Qux"); - AddEnumValue(qux, "B", 1); + EnumDescriptorProto* moo = AddNestedEnum(message, "Moo"); + AddEnumValue(moo, "B", 1); FileDescriptorProto bar_file; bar_file.set_name("bar.proto"); @@ -1745,10 +1745,10 @@ DescriptorProto* message2 = AddMessage(&bar_file, "TestMessage2"); AddNestedMessage(message2, "Foo"); AddNestedMessage(message2, "Baz"); - EnumDescriptorProto* qux2 = AddNestedEnum(message2, "Qux"); - AddEnumValue(qux2, "A", 1); - EnumDescriptorProto* quux2 = AddNestedEnum(message2, "Quux"); - AddEnumValue(quux2, "C", 1); + EnumDescriptorProto* moo2 = AddNestedEnum(message2, "Moo"); + AddEnumValue(moo2, "A", 1); + EnumDescriptorProto* mooo2 = AddNestedEnum(message2, "Mooo"); + AddEnumValue(mooo2, "C", 1); // Build the descriptors and get the pointers. foo_file_ = pool_.BuildFile(foo_file); @@ -1766,12 +1766,12 @@ ASSERT_EQ(2, message_->enum_type_count()); baz_ = message_->enum_type(0); - qux_ = message_->enum_type(1); + moo_ = message_->enum_type(1); ASSERT_EQ(1, baz_->value_count()); a_ = baz_->value(0); - ASSERT_EQ(1, qux_->value_count()); - b_ = qux_->value(0); + ASSERT_EQ(1, moo_->value_count()); + b_ = moo_->value(0); ASSERT_EQ(1, bar_file_->message_type_count()); message2_ = bar_file_->message_type(0); @@ -1781,13 +1781,13 @@ baz2_ = message2_->nested_type(1); ASSERT_EQ(2, message2_->enum_type_count()); - qux2_ = message2_->enum_type(0); - quux2_ = message2_->enum_type(1); + moo2_ = message2_->enum_type(0); + mooo2_ = message2_->enum_type(1); - ASSERT_EQ(1, qux2_->value_count()); - a2_ = qux2_->value(0); - ASSERT_EQ(1, quux2_->value_count()); - c2_ = quux2_->value(0); + ASSERT_EQ(1, moo2_->value_count()); + a2_ = moo2_->value(0); + ASSERT_EQ(1, mooo2_->value_count()); + c2_ = mooo2_->value(0); } DescriptorPool pool_; @@ -1801,14 +1801,14 @@ const Descriptor* foo_; const Descriptor* bar_; const EnumDescriptor* baz_; - const EnumDescriptor* qux_; + const EnumDescriptor* moo_; const EnumValueDescriptor* a_; const EnumValueDescriptor* b_; const Descriptor* foo2_; const Descriptor* baz2_; - const EnumDescriptor* qux2_; - const EnumDescriptor* quux2_; + const EnumDescriptor* moo2_; + const EnumDescriptor* mooo2_; const EnumValueDescriptor* a2_; const EnumValueDescriptor* c2_; }; @@ -1840,9 +1840,9 @@ TEST_F(NestedDescriptorTest, FindFieldByNameDoesntFindNestedTypes) { EXPECT_TRUE(message_->FindFieldByName("Foo") == nullptr); - EXPECT_TRUE(message_->FindFieldByName("Qux") == nullptr); + EXPECT_TRUE(message_->FindFieldByName("Moo") == nullptr); EXPECT_TRUE(message_->FindExtensionByName("Foo") == nullptr); - EXPECT_TRUE(message_->FindExtensionByName("Qux") == nullptr); + EXPECT_TRUE(message_->FindExtensionByName("Moo") == nullptr); } TEST_F(NestedDescriptorTest, FindNestedTypeByName) { @@ -1855,26 +1855,26 @@ EXPECT_TRUE(message_->FindNestedTypeByName("Baz") == nullptr); EXPECT_TRUE(message2_->FindNestedTypeByName("Bar") == nullptr); - EXPECT_TRUE(message_->FindNestedTypeByName("Qux") == nullptr); + EXPECT_TRUE(message_->FindNestedTypeByName("Moo") == nullptr); } TEST_F(NestedDescriptorTest, EnumName) { EXPECT_EQ("Baz", baz_->name()); - EXPECT_EQ("Qux", qux_->name()); - EXPECT_EQ("Qux", qux2_->name()); - EXPECT_EQ("Quux", quux2_->name()); + EXPECT_EQ("Moo", moo_->name()); + EXPECT_EQ("Moo", moo2_->name()); + EXPECT_EQ("Mooo", mooo2_->name()); EXPECT_EQ("TestMessage.Baz", baz_->full_name()); - EXPECT_EQ("TestMessage.Qux", qux_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.Qux", qux2_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.Quux", quux2_->full_name()); + EXPECT_EQ("TestMessage.Moo", moo_->full_name()); + EXPECT_EQ("corge.grault.TestMessage2.Moo", moo2_->full_name()); + EXPECT_EQ("corge.grault.TestMessage2.Mooo", mooo2_->full_name()); } TEST_F(NestedDescriptorTest, EnumContainingType) { EXPECT_EQ(message_, baz_->containing_type()); - EXPECT_EQ(message_, qux_->containing_type()); - EXPECT_EQ(message2_, qux2_->containing_type()); - EXPECT_EQ(message2_, quux2_->containing_type()); + EXPECT_EQ(message_, moo_->containing_type()); + EXPECT_EQ(message2_, moo2_->containing_type()); + EXPECT_EQ(message2_, mooo2_->containing_type()); } TEST_F(NestedDescriptorTest, NestedEnumsByIndex) { @@ -1885,12 +1885,12 @@ TEST_F(NestedDescriptorTest, FindEnumTypeByName) { EXPECT_EQ(baz_, message_->FindEnumTypeByName("Baz")); - EXPECT_EQ(qux_, message_->FindEnumTypeByName("Qux")); - EXPECT_EQ(qux2_, message2_->FindEnumTypeByName("Qux")); - EXPECT_EQ(quux2_, message2_->FindEnumTypeByName("Quux")); + EXPECT_EQ(moo_, message_->FindEnumTypeByName("Moo")); + EXPECT_EQ(moo2_, message2_->FindEnumTypeByName("Moo")); + EXPECT_EQ(mooo2_, message2_->FindEnumTypeByName("Mooo")); EXPECT_TRUE(message_->FindEnumTypeByName("NoSuchType") == nullptr); - EXPECT_TRUE(message_->FindEnumTypeByName("Quux") == nullptr); + EXPECT_TRUE(message_->FindEnumTypeByName("Mooo") == nullptr); EXPECT_TRUE(message2_->FindEnumTypeByName("Baz") == nullptr); EXPECT_TRUE(message_->FindEnumTypeByName("Foo") == nullptr); @@ -1918,7 +1918,7 @@ // Build descriptors for the following definitions: // // enum Baz {} - // message Qux {} + // message Moo {} // // message Foo { // extensions 10 to 19; @@ -1933,8 +1933,8 @@ // message Bar { // optional int32 non_ext_int32 = 1; // extend Foo { - // optional Qux foo_message = 30; - // repeated Qux foo_group = 39; // (but internally set to TYPE_GROUP) + // optional Moo foo_message = 30; + // repeated Moo foo_group = 39; // (but internally set to TYPE_GROUP) // } // } @@ -1942,7 +1942,7 @@ foo_file.set_name("foo.proto"); AddEmptyEnum(&foo_file, "Baz"); - AddMessage(&foo_file, "Qux"); + AddMessage(&foo_file, "Moo"); DescriptorProto* foo = AddMessage(&foo_file, "Foo"); AddExtensionRange(foo, 10, 20); @@ -1962,11 +1962,11 @@ AddNestedExtension(bar, "Foo", "foo_message", 30, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_MESSAGE) - ->set_type_name("Qux"); + ->set_type_name("Moo"); AddNestedExtension(bar, "Foo", "foo_group", 39, FieldDescriptorProto::LABEL_REPEATED, FieldDescriptorProto::TYPE_GROUP) - ->set_type_name("Qux"); + ->set_type_name("Moo"); // Build the descriptors and get the pointers. foo_file_ = pool_.BuildFile(foo_file); @@ -1976,7 +1976,7 @@ baz_ = foo_file_->enum_type(0); ASSERT_EQ(3, foo_file_->message_type_count()); - qux_ = foo_file_->message_type(0); + moo_ = foo_file_->message_type(0); foo_ = foo_file_->message_type(1); bar_ = foo_file_->message_type(2); } @@ -1988,7 +1988,7 @@ const Descriptor* foo_; const Descriptor* bar_; const EnumDescriptor* baz_; - const Descriptor* qux_; + const Descriptor* moo_; }; TEST_F(ExtensionDescriptorTest, ExtensionRanges) { @@ -2028,8 +2028,8 @@ EXPECT_EQ(FieldDescriptor::TYPE_GROUP, bar_->extension(1)->type()); EXPECT_EQ(baz_, foo_file_->extension(1)->enum_type()); - EXPECT_EQ(qux_, bar_->extension(0)->message_type()); - EXPECT_EQ(qux_, bar_->extension(1)->message_type()); + EXPECT_EQ(moo_, bar_->extension(0)->message_type()); + EXPECT_EQ(moo_, bar_->extension(1)->message_type()); EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, foo_file_->extension(0)->label()); EXPECT_EQ(FieldDescriptor::LABEL_REPEATED, foo_file_->extension(1)->label()); @@ -2863,8 +2863,8 @@ " name: 'Foo'" " field { name:'bar' number:1 label:LABEL_OPTIONAL type_name:'Bar' }" " field { name:'baz' number:2 label:LABEL_OPTIONAL type_name:'Baz' }" - " field { name:'qux' number:3 label:LABEL_OPTIONAL" - " type_name: '.corge.Qux'" + " field { name:'moo' number:3 label:LABEL_OPTIONAL" + " type_name: '.corge.Moo'" " type: TYPE_ENUM" " options {" " uninterpreted_option {" @@ -2902,7 +2902,7 @@ ASSERT_EQ(3, foo_type_->field_count()); bar_field_ = foo_type_->field(0); baz_field_ = foo_type_->field(1); - qux_field_ = foo_type_->field(2); + moo_field_ = foo_type_->field(2); } const FileDescriptor* BuildFile(const FileDescriptorProto& proto) { @@ -2925,7 +2925,7 @@ const Descriptor* foo_type_; const FieldDescriptor* bar_field_; const FieldDescriptor* baz_field_; - const FieldDescriptor* qux_field_; + const FieldDescriptor* moo_field_; SimpleDescriptorDatabase db_; // used if in FALLBACK_DATABASE mode. std::unique_ptr<DescriptorPool> pool_; @@ -2964,18 +2964,18 @@ EXPECT_EQ(0, baz_type->extension_range_count()); EXPECT_TRUE(baz_type->is_placeholder()); - ASSERT_EQ(FieldDescriptor::TYPE_ENUM, qux_field_->type()); - const EnumDescriptor* qux_type = qux_field_->enum_type(); - EXPECT_EQ("Qux", qux_type->name()); - EXPECT_EQ("corge.Qux", qux_type->full_name()); - EXPECT_TRUE(qux_type->is_placeholder()); + ASSERT_EQ(FieldDescriptor::TYPE_ENUM, moo_field_->type()); + const EnumDescriptor* moo_type = moo_field_->enum_type(); + EXPECT_EQ("Moo", moo_type->name()); + EXPECT_EQ("corge.Moo", moo_type->full_name()); + EXPECT_TRUE(moo_type->is_placeholder()); // Placeholder enum values should not be findable. - EXPECT_EQ(qux_type->FindValueByNumber(0), nullptr); + EXPECT_EQ(moo_type->FindValueByNumber(0), nullptr); // Placeholder types should not be findable. EXPECT_EQ(bar_type_, pool_->FindMessageTypeByName(bar_type_->full_name())); EXPECT_TRUE(pool_->FindMessageTypeByName(baz_type->full_name()) == nullptr); - EXPECT_TRUE(pool_->FindEnumTypeByName(qux_type->full_name()) == nullptr); + EXPECT_TRUE(pool_->FindEnumTypeByName(moo_type->full_name()) == nullptr); } TEST_P(AllowUnknownDependenciesTest, CopyTo) { @@ -2994,18 +2994,18 @@ EXPECT_EQ("Baz", proto.type_name()); EXPECT_FALSE(proto.has_type()); - // Qux is a fully-qualified placeholder. + // Moo is a fully-qualified placeholder. proto.Clear(); - qux_field_->CopyTo(&proto); - EXPECT_EQ(".corge.Qux", proto.type_name()); + moo_field_->CopyTo(&proto); + EXPECT_EQ(".corge.Moo", proto.type_name()); EXPECT_EQ(FieldDescriptorProto::TYPE_ENUM, proto.type()); } TEST_P(AllowUnknownDependenciesTest, CustomOptions) { - // Qux should still have the uninterpreted option attached. - ASSERT_EQ(1, qux_field_->options().uninterpreted_option_size()); + // Moo should still have the uninterpreted option attached. + ASSERT_EQ(1, moo_field_->options().uninterpreted_option_size()); const UninterpretedOption& option = - qux_field_->options().uninterpreted_option(0); + moo_field_->options().uninterpreted_option(0); ASSERT_EQ(1, option.name_size()); EXPECT_EQ("grault", option.name(0).name_part()); } @@ -3103,12 +3103,12 @@ "name: \"invalid_file_as_undeclared_dep.proto\" " "package: \"undeclared\" " "message_type: { " - " name: \"Quux\" " + " name: \"Mooo\" " " field { " - " name:'qux' number:1 label:LABEL_OPTIONAL type: TYPE_INT32 " + " name:'moo' number:1 label:LABEL_OPTIONAL type: TYPE_INT32 " " }" " field { " - " name:'quux' number:1 label:LABEL_OPTIONAL type: TYPE_INT64 " + " name:'mooo' number:1 label:LABEL_OPTIONAL type: TYPE_INT64 " " }" "}", &undeclared_dep_proto)); @@ -3132,8 +3132,8 @@ "message_type: { " " name: \"Corge\" " " field { " - " name:'quux' number:1 label: LABEL_OPTIONAL " - " type_name:'undeclared.Quux' type: TYPE_MESSAGE " + " name:'mooo' number:1 label: LABEL_OPTIONAL " + " type_name:'undeclared.Mooo' type: TYPE_MESSAGE " " }" "}", &test_proto)); @@ -3149,13 +3149,13 @@ ASSERT_EQ(1, corge_desc->field_count()); EXPECT_FALSE(corge_desc->is_placeholder()); - const FieldDescriptor* quux_field = corge_desc->field(0); - ASSERT_EQ(FieldDescriptor::TYPE_MESSAGE, quux_field->type()); - ASSERT_EQ("Quux", quux_field->message_type()->name()); - ASSERT_EQ("undeclared.Quux", quux_field->message_type()->full_name()); - EXPECT_TRUE(quux_field->message_type()->is_placeholder()); + const FieldDescriptor* mooo_field = corge_desc->field(0); + ASSERT_EQ(FieldDescriptor::TYPE_MESSAGE, mooo_field->type()); + ASSERT_EQ("Mooo", mooo_field->message_type()->name()); + ASSERT_EQ("undeclared.Mooo", mooo_field->message_type()->full_name()); + EXPECT_TRUE(mooo_field->message_type()->is_placeholder()); // The place holder type should not be findable. - ASSERT_TRUE(pool_->FindMessageTypeByName("undeclared.Quux") == nullptr); + ASSERT_TRUE(pool_->FindMessageTypeByName("undeclared.Mooo") == nullptr); } INSTANTIATE_TEST_SUITE_P(DatabaseSource, AllowUnknownDependenciesTest, @@ -3271,11 +3271,11 @@ &protobuf_unittest::VariousComplexOptions::descriptor()->options(); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1).foo(), 42); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1) - .GetExtension(protobuf_unittest::quux), + .GetExtension(protobuf_unittest::mooo), 324); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1) .GetExtension(protobuf_unittest::corge) - .qux(), + .moo(), 876); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).baz(), 987); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) @@ -3285,12 +3285,12 @@ 743); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) .bar() - .GetExtension(protobuf_unittest::quux), + .GetExtension(protobuf_unittest::mooo), 1999); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) .bar() .GetExtension(protobuf_unittest::corge) - .qux(), + .moo(), 2008); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) .GetExtension(protobuf_unittest::garply) @@ -3298,12 +3298,12 @@ 741); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) .GetExtension(protobuf_unittest::garply) - .GetExtension(protobuf_unittest::quux), + .GetExtension(protobuf_unittest::mooo), 1998); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2) .GetExtension(protobuf_unittest::garply) .GetExtension(protobuf_unittest::corge) - .qux(), + .moo(), 2121); EXPECT_EQ(options ->GetExtension(protobuf_unittest::ComplexOptionType2:: @@ -3312,7 +3312,7 @@ 1971); EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).fred().waldo(), 321); - EXPECT_EQ(9, options->GetExtension(protobuf_unittest::complex_opt3).qux()); + EXPECT_EQ(9, options->GetExtension(protobuf_unittest::complex_opt3).moo()); EXPECT_EQ(22, options->GetExtension(protobuf_unittest::complex_opt3) .complexoptiontype5() .plugh()); @@ -4114,7 +4114,7 @@ "}" " field { name: \"baz\" number: 19 label:LABEL_OPTIONAL type:TYPE_INT32 " "}" - " field { name: \"qux\" number: 20 label:LABEL_OPTIONAL type:TYPE_INT32 " + " field { name: \"moo\" number: 20 label:LABEL_OPTIONAL type:TYPE_INT32 " "}" " extension_range { start: 10 end: 20 }" "}", @@ -4122,7 +4122,8 @@ "foo.proto: Foo.bar: NUMBER: Extension range 10 to 19 includes field " "\"bar\" (10).\n" "foo.proto: Foo.baz: NUMBER: Extension range 10 to 19 includes field " - "\"baz\" (19).\n"); + "\"baz\" (19).\n" + "foo.proto: Foo: NUMBER: Suggested field numbers for Foo: 1, 2\n"); } TEST_F(ValidationErrorTest, OverlappingExtensionRanges) { @@ -4151,7 +4152,8 @@ " reserved_range { start: 10 end: 20 }" "}", - "foo.proto: Foo.foo: NUMBER: Field \"foo\" uses reserved number 15.\n"); + "foo.proto: Foo.foo: NUMBER: Field \"foo\" uses reserved number 15.\n" + "foo.proto: Foo: NUMBER: Suggested field numbers for Foo: 1\n"); } TEST_F(ValidationErrorTest, ReservedExtensionRangeError) { @@ -4446,13 +4448,13 @@ " default_value: \"abc\" }" // Messages can't have defaults. - " field { name: \"qux\" number: 4 label: LABEL_OPTIONAL type: " + " field { name: \"moo\" number: 4 label: LABEL_OPTIONAL type: " "TYPE_MESSAGE" " default_value: \"abc\" type_name: \"Foo\" }" // Same thing, but we don't know that this field has message type until // we look up the type name. - " field { name: \"quux\" number: 5 label: LABEL_OPTIONAL" + " field { name: \"mooo\" number: 5 label: LABEL_OPTIONAL" " default_value: \"abc\" type_name: \"Foo\" }" // Repeateds can't have defaults. @@ -4466,12 +4468,12 @@ "foo.proto: Foo.bar: DEFAULT_VALUE: Couldn't parse default value \"\".\n" "foo.proto: Foo.baz: DEFAULT_VALUE: Boolean default must be true or " "false.\n" - "foo.proto: Foo.qux: DEFAULT_VALUE: Messages can't have default values.\n" + "foo.proto: Foo.moo: DEFAULT_VALUE: Messages can't have default values.\n" "foo.proto: Foo.corge: DEFAULT_VALUE: Repeated fields can't have default " "values.\n" // This ends up being reported later because the error is detected at // cross-linking time. - "foo.proto: Foo.quux: DEFAULT_VALUE: Messages can't have default " + "foo.proto: Foo.mooo: DEFAULT_VALUE: Messages can't have default " "values.\n"); } @@ -4484,7 +4486,8 @@ "}" "}", - "foo.proto: Foo.foo: NUMBER: Field numbers must be positive integers.\n"); + "foo.proto: Foo.foo: NUMBER: Field numbers must be positive integers.\n" + "foo.proto: Foo: NUMBER: Suggested field numbers for Foo: 1\n"); } TEST_F(ValidationErrorTest, HugeFieldNumber) { @@ -4497,7 +4500,8 @@ "}", "foo.proto: Foo.foo: NUMBER: Field numbers cannot be greater than " - "536870911.\n"); + "536870911.\n" + "foo.proto: Foo: NUMBER: Suggested field numbers for Foo: 1\n"); } TEST_F(ValidationErrorTest, ReservedFieldNumber) { @@ -4511,14 +4515,15 @@ "type:TYPE_INT32 }" " field {name:\"baz\" number: 19999 label:LABEL_OPTIONAL " "type:TYPE_INT32 }" - " field {name:\"qux\" number: 20000 label:LABEL_OPTIONAL " + " field {name:\"moo\" number: 20000 label:LABEL_OPTIONAL " "type:TYPE_INT32 }" "}", "foo.proto: Foo.bar: NUMBER: Field numbers 19000 through 19999 are " "reserved for the protocol buffer library implementation.\n" "foo.proto: Foo.baz: NUMBER: Field numbers 19000 through 19999 are " - "reserved for the protocol buffer library implementation.\n"); + "reserved for the protocol buffer library implementation.\n" + "foo.proto: Foo: NUMBER: Suggested field numbers for Foo: 1, 2\n"); } TEST_F(ValidationErrorTest, ExtensionMissingExtendee) { @@ -4716,7 +4721,8 @@ " extension_range { start: -10 end: -1 }" "}", - "foo.proto: Foo: NUMBER: Extension numbers must be positive integers.\n"); + "foo.proto: Foo: NUMBER: Extension numbers must be positive integers.\n" + "foo.proto: Foo: NUMBER: Suggested field numbers for Foo: 1, 2, 3\n"); } TEST_F(ValidationErrorTest, HugeExtensionRangeNumber) { @@ -5108,7 +5114,7 @@ // baz.proto: // package foo; // import "bar.proto" - // message Baz { optional bar.Bar qux = 1; } + // message Baz { optional bar.Bar moo = 1; } // // When validating baz.proto, we will look up "bar.Bar". As part of this // lookup, we first lookup "bar" then try to find "Bar" within it. "bar" @@ -5132,7 +5138,7 @@ "dependency: \"bar.proto\" " "message_type { " " name: \"Baz\" " - " field { name:\"qux\" number:1 label:LABEL_OPTIONAL " + " field { name:\"moo\" number:1 label:LABEL_OPTIONAL " " type_name:\"bar.Bar\" }" "}"); } @@ -5472,12 +5478,12 @@ // message Bar { optional int32 foo = 1; } // extend FileOptions { optional Bar bar = 7672757; } // - // qux.proto: - // package qux.baz + // moo.proto: + // package moo.baz // option (baz.bar).foo = 1; // // Although "baz.bar" is already defined, the lookup code will try - // "qux.baz.bar", since it's the match from the innermost scope, which will + // "moo.baz.bar", since it's the match from the innermost scope, which will // cause a symbol not defined error. BuildDescriptorMessagesInTestPool(); @@ -5493,16 +5499,16 @@ " extendee: \"google.protobuf.FileOptions\" }"); BuildFileWithErrors( - "name: \"qux.proto\" " - "package: \"qux.baz\" " + "name: \"moo.proto\" " + "package: \"moo.baz\" " "options { uninterpreted_option { name { name_part: \"baz.bar\" " " is_extension: true } " " name { name_part: \"foo\" " " is_extension: false } " " positive_int_value: 1 } }", - "qux.proto: qux.proto: OPTION_NAME: Option \"(baz.bar)\" is resolved to " - "\"(qux.baz.bar)\"," + "moo.proto: moo.proto: OPTION_NAME: Option \"(baz.bar)\" is resolved to " + "\"(moo.baz.bar)\"," " which is not defined. The innermost scope is searched first in name " "resolution. Consider using a leading '.'(i.e., \"(.baz.bar)\") to start " "from the outermost scope.\n"); @@ -5510,15 +5516,15 @@ TEST_F(ValidationErrorTest, UnknownOption) { BuildFileWithErrors( - "name: \"qux.proto\" " - "package: \"qux.baz\" " + "name: \"moo.proto\" " + "package: \"moo.baz\" " "options { uninterpreted_option { name { name_part: \"baaz.bar\" " " is_extension: true } " " name { name_part: \"foo\" " " is_extension: false } " " positive_int_value: 1 } }", - "qux.proto: qux.proto: OPTION_NAME: Option \"(baaz.bar)\" unknown. " + "moo.proto: moo.proto: OPTION_NAME: Option \"(baaz.bar)\" unknown. " "Ensure " "that your proto definition file imports the proto which defines the " "option.\n"); @@ -5732,7 +5738,7 @@ " extendee: \"google.protobuf.FileOptions\" }" "options { uninterpreted_option { name { name_part: \"foo\" " " is_extension: true } " - " string_value: \"QUUX\" } }", + " string_value: \"MOOO\" } }", "foo.proto: foo.proto: OPTION_VALUE: Value must be identifier for " "enum-valued option \"foo\".\n"); @@ -5751,10 +5757,10 @@ " extendee: \"google.protobuf.FileOptions\" }" "options { uninterpreted_option { name { name_part: \"foo\" " " is_extension: true } " - " identifier_value: \"QUUX\" } }", + " identifier_value: \"MOOO\" } }", "foo.proto: foo.proto: OPTION_VALUE: Enum type \"FooEnum\" has no value " - "named \"QUUX\" for option \"foo\".\n"); + "named \"MOOO\" for option \"foo\".\n"); } TEST_F(ValidationErrorTest, EnumOptionValueIsSiblingEnumValueName) { @@ -5765,17 +5771,17 @@ "dependency: \"google/protobuf/descriptor.proto\" " "enum_type { name: \"FooEnum1\" value { name: \"BAR\" number: 1 } " " value { name: \"BAZ\" number: 2 } }" - "enum_type { name: \"FooEnum2\" value { name: \"QUX\" number: 1 } " - " value { name: \"QUUX\" number: 2 } }" + "enum_type { name: \"FooEnum2\" value { name: \"MOO\" number: 1 } " + " value { name: \"MOOO\" number: 2 } }" "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " " type: TYPE_ENUM type_name: \"FooEnum1\" " " extendee: \"google.protobuf.FileOptions\" }" "options { uninterpreted_option { name { name_part: \"foo\" " " is_extension: true } " - " identifier_value: \"QUUX\" } }", + " identifier_value: \"MOOO\" } }", "foo.proto: foo.proto: OPTION_VALUE: Enum type \"FooEnum1\" has no value " - "named \"QUUX\" for option \"foo\". This appears to be a value from a " + "named \"MOOO\" for option \"foo\". This appears to be a value from a " "sibling type.\n"); } @@ -5789,7 +5795,7 @@ " type: TYPE_STRING extendee: \"google.protobuf.FileOptions\" }" "options { uninterpreted_option { name { name_part: \"foo\" " " is_extension: true } " - " identifier_value: \"QUUX\" } }", + " identifier_value: \"MOOO\" } }", "foo.proto: foo.proto: OPTION_VALUE: Value must be quoted string " "for " @@ -6731,16 +6737,64 @@ ASSERT_TRUE(pool.BuildFile(file_proto) != nullptr); // Add "foo.proto": // import "google/protobuf/descriptor.proto"; + // extend google.protobuf.FileOptions { + // optional string test_file_opt = 1001; + // } + // extend google.protobuf.MessageOptions { + // optional string test_msg_opt = 1002; + // } // extend google.protobuf.FieldOptions { - // optional int32 option1 = 1000; + // optional string test_field_opt = 1003; + // } + // extend google.protobuf.EnumOptions { + // repeated int32 test_enum_opt = 1004; + // } + // extend google.protobuf.EnumValueOptions { + // optional int32 test_enumval_opt = 1005; + // } + // extend google.protobuf.ServiceOptions { + // repeated int32 test_svc_opt = 1006; + // } + // extend google.protobuf.MethodOptions { + // optional string test_method_opt = 1007; + // } + // extend google.protobuf.OneofOptions { + // optional string test_oneof_opt = 1008; + // } + // extend google.protobuf.ExtensionRangeOptions { + // optional string test_ext_opt = 1009; // } file_proto.Clear(); file_proto.set_name("foo.proto"); file_proto.set_syntax("proto3"); file_proto.add_dependency("google/protobuf/descriptor.proto"); - AddExtension(&file_proto, "google.protobuf.FieldOptions", "option1", 1000, + AddExtension(&file_proto, "google.protobuf.FileOptions", "test_file_opt", 1001, + FieldDescriptorProto::LABEL_OPTIONAL, + FieldDescriptorProto::TYPE_STRING); + AddExtension(&file_proto, "google.protobuf.MessageOptions", "test_msg_opt", 1001, + FieldDescriptorProto::LABEL_OPTIONAL, + FieldDescriptorProto::TYPE_STRING); + AddExtension(&file_proto, "google.protobuf.FieldOptions", "test_field_opt", 1003, + FieldDescriptorProto::LABEL_OPTIONAL, + FieldDescriptorProto::TYPE_STRING); + AddExtension(&file_proto, "google.protobuf.EnumOptions", "test_enum_opt", 1004, + FieldDescriptorProto::LABEL_REPEATED, + FieldDescriptorProto::TYPE_INT32); + AddExtension(&file_proto, "google.protobuf.EnumValueOptions", "test_enumval_opt", 1005, FieldDescriptorProto::LABEL_OPTIONAL, FieldDescriptorProto::TYPE_INT32); + AddExtension(&file_proto, "google.protobuf.ServiceOptions", "test_svc_opt", 1006, + FieldDescriptorProto::LABEL_REPEATED, + FieldDescriptorProto::TYPE_INT32); + AddExtension(&file_proto, "google.protobuf.MethodOptions", "test_method_opt", 1007, + FieldDescriptorProto::LABEL_OPTIONAL, + FieldDescriptorProto::TYPE_STRING); + AddExtension(&file_proto, "google.protobuf.OneofOptions", "test_oneof_opt", 1008, + FieldDescriptorProto::LABEL_OPTIONAL, + FieldDescriptorProto::TYPE_STRING); + AddExtension(&file_proto, "google.protobuf.ExtensionRangeOptions", "test_ext_opt", + 1009, FieldDescriptorProto::LABEL_OPTIONAL, + FieldDescriptorProto::TYPE_STRING); ASSERT_TRUE(pool.BuildFile(file_proto) != nullptr); // Copy and change the package of the descriptor.proto @@ -6811,6 +6865,30 @@ } +TEST_F(ValidationErrorTest, PackageTooLong) { + BuildFileWithErrors( + "name: \"foo.proto\" " + "syntax: \"proto3\" " + "package: " + "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaa\"", + "foo.proto: " + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaa: NAME: Package name is too long\n"); +} + // =================================================================== // DescriptorDatabase
diff --git a/src/google/protobuf/drop_unknown_fields_test.cc b/src/google/protobuf/drop_unknown_fields_test.cc index 55b9ecd..55c6b67 100644 --- a/src/google/protobuf/drop_unknown_fields_test.cc +++ b/src/google/protobuf/drop_unknown_fields_test.cc
@@ -44,19 +44,19 @@ TEST(DropUnknownFieldsTest, GeneratedMessage) { FooWithExtraFields foo_with_extra_fields; foo_with_extra_fields.set_int32_value(1); - foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX); + foo_with_extra_fields.set_enum_value(FooWithExtraFields::MOO); foo_with_extra_fields.set_extra_int32_value(2); Foo foo; ASSERT_TRUE(foo.ParseFromString(foo_with_extra_fields.SerializeAsString())); EXPECT_EQ(1, foo.int32_value()); - EXPECT_EQ(static_cast<int>(FooWithExtraFields::QUX), + EXPECT_EQ(static_cast<int>(FooWithExtraFields::MOO), static_cast<int>(foo.enum_value())); EXPECT_FALSE(foo.GetReflection()->GetUnknownFields(foo).empty()); ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo.SerializeAsString())); EXPECT_EQ(1, foo_with_extra_fields.int32_value()); - EXPECT_EQ(FooWithExtraFields::QUX, foo_with_extra_fields.enum_value()); + EXPECT_EQ(FooWithExtraFields::MOO, foo_with_extra_fields.enum_value()); // The "extra_int32_value" field should not be lost. EXPECT_EQ(2, foo_with_extra_fields.extra_int32_value()); } @@ -64,7 +64,7 @@ TEST(DropUnknownFieldsTest, DynamicMessage) { FooWithExtraFields foo_with_extra_fields; foo_with_extra_fields.set_int32_value(1); - foo_with_extra_fields.set_enum_value(FooWithExtraFields::QUX); + foo_with_extra_fields.set_enum_value(FooWithExtraFields::MOO); foo_with_extra_fields.set_extra_int32_value(2); DynamicMessageFactory factory; @@ -74,7 +74,7 @@ ASSERT_TRUE(foo_with_extra_fields.ParseFromString(foo->SerializeAsString())); EXPECT_EQ(1, foo_with_extra_fields.int32_value()); - EXPECT_EQ(FooWithExtraFields::QUX, foo_with_extra_fields.enum_value()); + EXPECT_EQ(FooWithExtraFields::MOO, foo_with_extra_fields.enum_value()); // The "extra_int32_value" field should not be lost. EXPECT_EQ(2, foo_with_extra_fields.extra_int32_value()); }
diff --git a/src/google/protobuf/duration.pb.cc b/src/google/protobuf/duration.pb.cc index 6dd8cd5..e8baf91 100644 --- a/src/google/protobuf/duration.pb.cc +++ b/src/google/protobuf/duration.pb.cc
@@ -22,9 +22,10 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Duration::Duration( - ::_pbi::ConstantInitialized) - : seconds_(int64_t{0}) - , nanos_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.seconds_)*/int64_t{0} + , /*decltype(_impl_.nanos_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct DurationDefaultTypeInternal { PROTOBUF_CONSTEXPR DurationDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -46,8 +47,8 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, seconds_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, nanos_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, _impl_.seconds_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Duration, _impl_.nanos_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Duration)}, @@ -91,23 +92,32 @@ Duration::Duration(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Duration) } Duration::Duration(const Duration& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.seconds_){} + , decltype(_impl_.nanos_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _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_)); + ::memcpy(&_impl_.seconds_, &from._impl_.seconds_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.nanos_) - + reinterpret_cast<char*>(&_impl_.seconds_)) + sizeof(_impl_.nanos_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.Duration) } -inline void Duration::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&seconds_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&nanos_) - - reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_)); +inline void Duration::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.seconds_){int64_t{0}} + , decltype(_impl_.nanos_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; } Duration::~Duration() { @@ -124,7 +134,7 @@ } void Duration::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Duration::Clear() { @@ -133,9 +143,9 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - ::memset(&seconds_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&nanos_) - - reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_)); + ::memset(&_impl_.seconds_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.nanos_) - + reinterpret_cast<char*>(&_impl_.seconds_)) + sizeof(_impl_.nanos_)); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -148,7 +158,7 @@ // int64 seconds = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { - seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -156,7 +166,7 @@ // int32 nanos = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { - nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -228,11 +238,11 @@ total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_nanos()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Duration::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Duration::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Duration::GetClassData() const { return &_class_data_; } @@ -274,11 +284,11 @@ using std::swap; _internal_metadata_.InternalSwap(&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_FIELD_OFFSET(Duration, _impl_.nanos_) + + sizeof(Duration::_impl_.nanos_) + - PROTOBUF_FIELD_OFFSET(Duration, _impl_.seconds_)>( + reinterpret_cast<char*>(&_impl_.seconds_), + reinterpret_cast<char*>(&other->_impl_.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 8e128d1..12633a3 100644 --- a/src/google/protobuf/duration.pb.h +++ b/src/google/protobuf/duration.pb.h
@@ -147,10 +147,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Duration* other); @@ -203,9 +203,12 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - int64_t seconds_; - int32_t nanos_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + int64_t seconds_; + int32_t nanos_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fduration_2eproto; }; // =================================================================== @@ -221,10 +224,10 @@ // int64 seconds = 1; inline void Duration::clear_seconds() { - seconds_ = int64_t{0}; + _impl_.seconds_ = int64_t{0}; } inline int64_t Duration::_internal_seconds() const { - return seconds_; + return _impl_.seconds_; } inline int64_t Duration::seconds() const { // @@protoc_insertion_point(field_get:google.protobuf.Duration.seconds) @@ -232,7 +235,7 @@ } inline void Duration::_internal_set_seconds(int64_t value) { - seconds_ = value; + _impl_.seconds_ = value; } inline void Duration::set_seconds(int64_t value) { _internal_set_seconds(value); @@ -241,10 +244,10 @@ // int32 nanos = 2; inline void Duration::clear_nanos() { - nanos_ = 0; + _impl_.nanos_ = 0; } inline int32_t Duration::_internal_nanos() const { - return nanos_; + return _impl_.nanos_; } inline int32_t Duration::nanos() const { // @@protoc_insertion_point(field_get:google.protobuf.Duration.nanos) @@ -252,7 +255,7 @@ } inline void Duration::_internal_set_nanos(int32_t value) { - nanos_ = value; + _impl_.nanos_ = value; } inline void Duration::set_nanos(int32_t value) { _internal_set_nanos(value);
diff --git a/src/google/protobuf/dynamic_message_unittest.cc b/src/google/protobuf/dynamic_message_unittest.cc index 9391c8e..7ac2029 100644 --- a/src/google/protobuf/dynamic_message_unittest.cc +++ b/src/google/protobuf/dynamic_message_unittest.cc
@@ -40,19 +40,19 @@ // reflection_ops_unittest, cover the rest of the functionality used by // DynamicMessage. +#include <google/protobuf/dynamic_message.h> + #include <memory> -#include <google/protobuf/test_util.h> +#include <google/protobuf/stubs/logging.h> +#include <google/protobuf/stubs/common.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_no_field_presence.pb.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/descriptor.h> -#include <google/protobuf/dynamic_message.h> - -#include <google/protobuf/stubs/logging.h> -#include <google/protobuf/stubs/common.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> +#include <google/protobuf/test_util.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/empty.pb.cc b/src/google/protobuf/empty.pb.cc index 929e5d2..0c49797 100644 --- a/src/google/protobuf/empty.pb.cc +++ b/src/google/protobuf/empty.pb.cc
@@ -22,7 +22,7 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Empty::Empty( - ::_pbi::ConstantInitialized){} + ::_pbi::ConstantInitialized) {} struct EmptyDefaultTypeInternal { PROTOBUF_CONSTEXPR EmptyDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {}
diff --git a/src/google/protobuf/empty.pb.h b/src/google/protobuf/empty.pb.h index 5d1f880..38480a7 100644 --- a/src/google/protobuf/empty.pb.h +++ b/src/google/protobuf/empty.pb.h
@@ -169,6 +169,8 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; + struct Impl_ { + }; friend struct ::TableStruct_google_2fprotobuf_2fempty_2eproto; }; // ===================================================================
diff --git a/src/google/protobuf/empty.proto b/src/google/protobuf/empty.proto index 5f992de..2227462 100644 --- a/src/google/protobuf/empty.proto +++ b/src/google/protobuf/empty.proto
@@ -48,5 +48,4 @@ // rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); // } // -// The JSON representation for `Empty` is empty JSON object `{}`. message Empty {}
diff --git a/src/google/protobuf/endian.h b/src/google/protobuf/endian.h new file mode 100644 index 0000000..e0ee6cd --- /dev/null +++ b/src/google/protobuf/endian.h
@@ -0,0 +1,198 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#ifndef GOOGLE_PROTOBUF_ENDIAN_H__ +#define GOOGLE_PROTOBUF_ENDIAN_H__ + +#if defined(_MSC_VER) +#include <stdlib.h> +#endif + +#include <cstdint> + +// Must be included last. +#include <google/protobuf/port_def.inc> + +namespace google { +namespace protobuf { +namespace internal { + +inline uint64_t BSwap64(uint64_t host_int) { +#if defined(PROTOBUF_BUILTIN_BSWAP64) + return PROTOBUF_BUILTIN_BSWAP64(host_int); +#elif defined(_MSC_VER) + return _byteswap_uint64(host_int); +#else + return (((host_int & uint64_t{0xFF}) << 56) | + ((host_int & uint64_t{0xFF00}) << 40) | + ((host_int & uint64_t{0xFF0000}) << 24) | + ((host_int & uint64_t{0xFF000000}) << 8) | + ((host_int & uint64_t{0xFF00000000}) >> 8) | + ((host_int & uint64_t{0xFF0000000000}) >> 24) | + ((host_int & uint64_t{0xFF000000000000}) >> 40) | + ((host_int & uint64_t{0xFF00000000000000}) >> 56)); +#endif +} + +inline uint32_t BSwap32(uint32_t host_int) { +#if defined(PROTOBUF_BUILTIN_BSWAP32) + return PROTOBUF_BUILTIN_BSWAP32(host_int); +#elif defined(_MSC_VER) + return _byteswap_ulong(host_int); +#else + return (((host_int & uint32_t{0xFF}) << 24) | + ((host_int & uint32_t{0xFF00}) << 8) | + ((host_int & uint32_t{0xFF0000}) >> 8) | + ((host_int & uint32_t{0xFF000000}) >> 24)); +#endif +} + +inline uint16_t BSwap16(uint16_t host_int) { +#if defined(PROTOBUF_BUILTIN_BSWAP16) + return PROTOBUF_BUILTIN_BSWAP16(host_int); +#elif defined(_MSC_VER) + return _byteswap_ushort(host_int); +#else + return (((host_int & uint16_t{0xFF}) << 8) | + ((host_int & uint16_t{0xFF00}) >> 8)); +#endif +} + +namespace little_endian { + +inline uint16_t FromHost(uint16_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return BSwap16(value); +#else + return value; +#endif +} + +inline uint32_t FromHost(uint32_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return BSwap32(value); +#else + return value; +#endif +} + +inline uint64_t FromHost(uint64_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return BSwap64(value); +#else + return value; +#endif +} + +inline uint16_t ToHost(uint16_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return BSwap16(value); +#else + return value; +#endif +} + +inline uint32_t ToHost(uint32_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return BSwap32(value); +#else + return value; +#endif +} + +inline uint64_t ToHost(uint64_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return BSwap64(value); +#else + return value; +#endif +} + +} // namespace little_endian + +namespace big_endian { + +inline uint16_t FromHost(uint16_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return value; +#else + return BSwap16(value); +#endif +} + +inline uint32_t FromHost(uint32_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return value; +#else + return BSwap32(value); +#endif +} + +inline uint64_t FromHost(uint64_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return value; +#else + return BSwap64(value); +#endif +} + +inline uint16_t ToHost(uint16_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return value; +#else + return BSwap16(value); +#endif +} + +inline uint32_t ToHost(uint32_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return value; +#else + return BSwap32(value); +#endif +} + +inline uint64_t ToHost(uint64_t value) { +#if defined(PROTOBUF_BIG_ENDIAN) + return value; +#else + return BSwap64(value); +#endif +} + +} // namespace big_endian + +} // namespace internal +} // namespace protobuf +} // namespace google + +#include <google/protobuf/port_undef.inc> + +#endif // GOOGLE_PROTOBUF_ENDIAN_H__
diff --git a/src/google/protobuf/extension_set.cc b/src/google/protobuf/extension_set.cc index 9c8dd6d..fada4f5 100644 --- a/src/google/protobuf/extension_set.cc +++ b/src/google/protobuf/extension_set.cc
@@ -69,24 +69,6 @@ return WireFormatLite::FieldTypeToCppType(real_type(type)); } -inline bool is_packable(WireFormatLite::WireType type) { - switch (type) { - case WireFormatLite::WIRETYPE_VARINT: - case WireFormatLite::WIRETYPE_FIXED64: - case WireFormatLite::WIRETYPE_FIXED32: - return true; - case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: - case WireFormatLite::WIRETYPE_START_GROUP: - case WireFormatLite::WIRETYPE_END_GROUP: - return false; - - // Do not add a default statement. Let the compiler complain when someone - // adds a new wire type. - } - GOOGLE_LOG(FATAL) << "can't reach here."; - return false; -} - // Registry stuff. // Note that we cannot use hetererogeneous lookup for std containers since we @@ -139,8 +121,6 @@ } // namespace -ExtensionFinder::~ExtensionFinder() {} - bool GeneratedExtensionFinder::Find(int number, ExtensionInfo* output) { const ExtensionInfo* extension = FindRegisteredExtension(extendee_, number); if (extension == nullptr) { @@ -949,23 +929,35 @@ } namespace { -// Computes the size of a std::set_union without constructing the union. +// Computes the size of an ExtensionSet union without actually constructing the +// union. Note that we do not count cleared extensions from the source to be +// part of the total, because there is no need to allocate space for those. We +// do include cleared extensions in the destination, though, because those are +// already allocated and will not be going away. template <typename ItX, typename ItY> -size_t SizeOfUnion(ItX it_xs, ItX end_xs, ItY it_ys, ItY end_ys) { +size_t SizeOfUnion(ItX it_dest, ItX end_dest, ItY it_source, ItY end_source) { size_t result = 0; - while (it_xs != end_xs && it_ys != end_ys) { - ++result; - if (it_xs->first < it_ys->first) { - ++it_xs; - } else if (it_xs->first == it_ys->first) { - ++it_xs; - ++it_ys; + while (it_dest != end_dest && it_source != end_source) { + if (it_dest->first < it_source->first) { + ++result; + ++it_dest; + } else if (it_dest->first == it_source->first) { + ++result; + ++it_dest; + ++it_source; } else { - ++it_ys; + if (!it_source->second.is_cleared) { + ++result; + } + ++it_source; } } - result += std::distance(it_xs, end_xs); - result += std::distance(it_ys, end_ys); + result += std::distance(it_dest, end_dest); + for (; it_source != end_source; ++it_source) { + if (!it_source->second.is_cleared) { + ++result; + } + } return result; } } // namespace @@ -1235,40 +1227,6 @@ return true; } -bool ExtensionSet::FindExtensionInfoFromTag(uint32_t tag, - ExtensionFinder* extension_finder, - int* field_number, - ExtensionInfo* extension, - bool* was_packed_on_wire) { - *field_number = WireFormatLite::GetTagFieldNumber(tag); - WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag); - return FindExtensionInfoFromFieldNumber(wire_type, *field_number, - extension_finder, extension, - was_packed_on_wire); -} - -bool ExtensionSet::FindExtensionInfoFromFieldNumber( - int wire_type, int field_number, ExtensionFinder* extension_finder, - ExtensionInfo* extension, bool* was_packed_on_wire) const { - if (!extension_finder->Find(field_number, extension)) { - return false; - } - - WireFormatLite::WireType expected_wire_type = - WireFormatLite::WireTypeForFieldType(real_type(extension->type)); - - // Check if this is a packed field. - *was_packed_on_wire = false; - if (extension->is_repeated && - wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED && - is_packable(expected_wire_type)) { - *was_packed_on_wire = true; - return true; - } - // Otherwise the wire type must match. - return expected_wire_type == wire_type; -} - const char* ExtensionSet::ParseField(uint64_t tag, const char* ptr, const MessageLite* extendee, internal::InternalMetadata* metadata,
diff --git a/src/google/protobuf/extension_set.h b/src/google/protobuf/extension_set.h index 026b102..0e6d052 100644 --- a/src/google/protobuf/extension_set.h +++ b/src/google/protobuf/extension_set.h
@@ -147,26 +147,20 @@ LazyEagerVerifyFnType lazy_eager_verify_func = nullptr; }; -// Abstract interface for an object which looks up extension definitions. Used -// when parsing. -class PROTOBUF_EXPORT ExtensionFinder { - public: - virtual ~ExtensionFinder(); +// An ExtensionFinder is an object which looks up extension definitions. It +// must implement this method: +// +// bool Find(int number, ExtensionInfo* output); - // Find the extension with the given containing type and number. - virtual bool Find(int number, ExtensionInfo* output) = 0; -}; - -// Implementation of ExtensionFinder which finds extensions defined in .proto -// files which have been compiled into the binary. -class PROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder { +// GeneratedExtensionFinder is an ExtensionFinder which finds extensions +// defined in .proto files which have been compiled into the binary. +class PROTOBUF_EXPORT GeneratedExtensionFinder { public: explicit GeneratedExtensionFinder(const MessageLite* extendee) : extendee_(extendee) {} - ~GeneratedExtensionFinder() override {} // Returns true and fills in *output if found, otherwise returns false. - bool Find(int number, ExtensionInfo* output) override; + bool Find(int number, ExtensionInfo* output); private: const MessageLite* extendee_; @@ -746,22 +740,71 @@ const Extension& other_extension, Arena* other_arena); + inline static bool is_packable(WireFormatLite::WireType type) { + switch (type) { + case WireFormatLite::WIRETYPE_VARINT: + case WireFormatLite::WIRETYPE_FIXED64: + case WireFormatLite::WIRETYPE_FIXED32: + return true; + case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: + case WireFormatLite::WIRETYPE_START_GROUP: + case WireFormatLite::WIRETYPE_END_GROUP: + return false; + + // Do not add a default statement. Let the compiler complain when + // someone + // adds a new wire type. + } + PROTOBUF_ASSUME(false); // switch handles all possible enum values + return false; + } + // Returns true and fills field_number and extension if extension is found. // Note to support packed repeated field compatibility, it also fills whether // the tag on wire is packed, which can be different from // extension->is_packed (whether packed=true is specified). + template <typename ExtensionFinder> bool FindExtensionInfoFromTag(uint32_t tag, ExtensionFinder* extension_finder, int* field_number, ExtensionInfo* extension, - bool* was_packed_on_wire); + bool* was_packed_on_wire) { + *field_number = WireFormatLite::GetTagFieldNumber(tag); + WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag); + return FindExtensionInfoFromFieldNumber(wire_type, *field_number, + extension_finder, extension, + was_packed_on_wire); + } // Returns true and fills extension if extension is found. // Note to support packed repeated field compatibility, it also fills whether // the tag on wire is packed, which can be different from // extension->is_packed (whether packed=true is specified). + template <typename ExtensionFinder> bool FindExtensionInfoFromFieldNumber(int wire_type, int field_number, ExtensionFinder* extension_finder, ExtensionInfo* extension, - bool* was_packed_on_wire) const; + bool* was_packed_on_wire) const { + if (!extension_finder->Find(field_number, extension)) { + return false; + } + + GOOGLE_DCHECK(extension->type > 0 && + extension->type <= WireFormatLite::MAX_FIELD_TYPE); + auto real_type = static_cast<WireFormatLite::FieldType>(extension->type); + + WireFormatLite::WireType expected_wire_type = + WireFormatLite::WireTypeForFieldType(real_type); + + // Check if this is a packed field. + *was_packed_on_wire = false; + if (extension->is_repeated && + wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED && + is_packable(expected_wire_type)) { + *was_packed_on_wire = true; + return true; + } + // Otherwise the wire type must match. + return expected_wire_type == wire_type; + } // Find the prototype for a LazyMessage from the extension registry. Returns // null if the extension is not found.
diff --git a/src/google/protobuf/extension_set_heavy.cc b/src/google/protobuf/extension_set_heavy.cc index 0b23572..a4bb948 100644 --- a/src/google/protobuf/extension_set_heavy.cc +++ b/src/google/protobuf/extension_set_heavy.cc
@@ -61,15 +61,14 @@ // Implementation of ExtensionFinder which finds extensions in a given // DescriptorPool, using the given MessageFactory to construct sub-objects. // This class is implemented in extension_set_heavy.cc. -class DescriptorPoolExtensionFinder : public ExtensionFinder { +class DescriptorPoolExtensionFinder { public: DescriptorPoolExtensionFinder(const DescriptorPool* pool, MessageFactory* factory, const Descriptor* containing_type) : pool_(pool), factory_(factory), containing_type_(containing_type) {} - ~DescriptorPoolExtensionFinder() override {} - bool Find(int number, ExtensionInfo* output) override; + bool Find(int number, ExtensionInfo* output); private: const DescriptorPool* pool_; @@ -359,7 +358,8 @@ } size_t ExtensionSet::SpaceUsedExcludingSelfLong() const { - size_t total_size = Size() * sizeof(KeyValue); + size_t total_size = + (is_large() ? map_.large->size() : flat_capacity_) * sizeof(KeyValue); ForEach([&total_size](int /* number */, const Extension& ext) { total_size += ext.SpaceUsedExcludingSelfLong(); });
diff --git a/src/google/protobuf/extension_set_unittest.cc b/src/google/protobuf/extension_set_unittest.cc index 5e145f8..04b62b6 100644 --- a/src/google/protobuf/extension_set_unittest.cc +++ b/src/google/protobuf/extension_set_unittest.cc
@@ -36,8 +36,6 @@ #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/test_util.h> -#include <google/protobuf/test_util2.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_mset.pb.h> #include <google/protobuf/io/coded_stream.h> @@ -50,6 +48,8 @@ #include <google/protobuf/wire_format.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> +#include <google/protobuf/test_util.h> +#include <google/protobuf/test_util2.h> #include <google/protobuf/stubs/stl_util.h> // Must be included last. @@ -63,7 +63,7 @@ using TestUtil::EqualsToSerialized; -// This test closely mirrors net/proto2/compiler/cpp/internal/unittest.cc +// This test closely mirrors third_party/protobuf/compiler/cpp/unittest.cc // except that it uses extensions rather than regular fields. TEST(ExtensionSetTest, Defaults) { @@ -107,20 +107,6 @@ message.Clear(); TestUtil::ExpectExtensionsClear(message); - // Unlike with the defaults test, we do NOT expect that requesting embedded - // messages will return a pointer to the default instance. Instead, they - // should return the objects that were created when mutable_blah() was - // called. - EXPECT_NE(&unittest::OptionalGroup_extension::default_instance(), - &message.GetExtension(unittest::optionalgroup_extension)); - EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.GetExtension(unittest::optional_nested_message_extension)); - EXPECT_NE( - &unittest::ForeignMessage::default_instance(), - &message.GetExtension(unittest::optional_foreign_message_extension)); - EXPECT_NE(&unittest_import::ImportMessage::default_instance(), - &message.GetExtension(unittest::optional_import_message_extension)); - // Make sure setting stuff again after clearing works. (This takes slightly // different code paths since the objects are reused.) TestUtil::SetAllExtensions(&message); @@ -414,6 +400,46 @@ TestUtil::ExpectAllExtensionsSet(message2); } +TEST(ExtensionSetTest, ArenaMergeFromWithClearedExtensions) { + Arena arena; + { + auto* message1 = Arena::CreateMessage<unittest::TestAllExtensions>(&arena); + auto* message2 = Arena::CreateMessage<unittest::TestAllExtensions>(&arena); + + // Set an extension and then clear it + message1->SetExtension(unittest::optional_int32_extension, 1); + message1->ClearExtension(unittest::optional_int32_extension); + + // Since all extensions in message1 have been cleared, we should be able to + // merge it into message2 without allocating any additional memory. + uint64_t space_used_before_merge = arena.SpaceUsed(); + message2->MergeFrom(*message1); + EXPECT_EQ(space_used_before_merge, arena.SpaceUsed()); + } + { + // As more complicated case, let's have message1 and message2 share some + // uncleared extensions in common. + auto* message1 = Arena::CreateMessage<unittest::TestAllExtensions>(&arena); + auto* message2 = Arena::CreateMessage<unittest::TestAllExtensions>(&arena); + + // Set int32 and uint32 on both messages. + message1->SetExtension(unittest::optional_int32_extension, 1); + message2->SetExtension(unittest::optional_int32_extension, 2); + message1->SetExtension(unittest::optional_uint32_extension, 1); + message2->SetExtension(unittest::optional_uint32_extension, 2); + + // Set and clear int64 and uint64 on message1. + message1->SetExtension(unittest::optional_int64_extension, 0); + message1->ClearExtension(unittest::optional_int64_extension); + message1->SetExtension(unittest::optional_uint64_extension, 0); + message1->ClearExtension(unittest::optional_uint64_extension); + + uint64_t space_used_before_merge = arena.SpaceUsed(); + message2->MergeFrom(*message1); + EXPECT_EQ(space_used_before_merge, arena.SpaceUsed()); + } +} + TEST(ExtensionSetTest, ArenaSetAllocatedMessageAndRelease) { Arena arena; unittest::TestAllExtensions* message = @@ -1338,6 +1364,18 @@ EXPECT_EQ(set.NumExtensions(), 0); } +TEST(ExtensionSetTest, ExtensionSetSpaceUsed) { + unittest::TestAllExtensions msg; + size_t l = msg.SpaceUsedLong(); + msg.SetExtension(unittest::optional_int32_extension, 100); + unittest::TestAllExtensions msg2(msg); + size_t l2 = msg2.SpaceUsedLong(); + msg.ClearExtension(unittest::optional_int32_extension); + unittest::TestAllExtensions msg3(msg); + size_t l3 = msg3.SpaceUsedLong(); + EXPECT_TRUE((l2 - l) > (l3 - l)); +} + } // namespace } // namespace internal } // namespace protobuf
diff --git a/src/google/protobuf/field_mask.pb.cc b/src/google/protobuf/field_mask.pb.cc index f0021b7..d64b3bd 100644 --- a/src/google/protobuf/field_mask.pb.cc +++ b/src/google/protobuf/field_mask.pb.cc
@@ -22,8 +22,9 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR FieldMask::FieldMask( - ::_pbi::ConstantInitialized) - : paths_(){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.paths_)*/{} + , /*decltype(_impl_._cached_size_)*/{}} {} struct FieldMaskDefaultTypeInternal { PROTOBUF_CONSTEXPR FieldMaskDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -45,7 +46,7 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldMask, paths_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FieldMask, _impl_.paths_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::FieldMask)}, @@ -88,19 +89,28 @@ FieldMask::FieldMask(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - paths_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.FieldMask) } FieldMask::FieldMask(const FieldMask& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - paths_(from.paths_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.paths_){from._impl_.paths_} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.FieldMask) } -inline void FieldMask::SharedCtor() { +inline void FieldMask::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.paths_){arena} + , /*decltype(_impl_._cached_size_)*/{} + }; } FieldMask::~FieldMask() { @@ -114,10 +124,11 @@ inline void FieldMask::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_.paths_.~RepeatedPtrField(); } void FieldMask::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void FieldMask::Clear() { @@ -126,7 +137,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - paths_.Clear(); + _impl_.paths_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -208,17 +219,17 @@ // repeated string paths = 1; total_size += 1 * - ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(paths_.size()); - for (int i = 0, n = paths_.size(); i < n; i++) { + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(_impl_.paths_.size()); + for (int i = 0, n = _impl_.paths_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( - paths_.Get(i)); + _impl_.paths_.Get(i)); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData FieldMask::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, FieldMask::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*FieldMask::GetClassData() const { return &_class_data_; } @@ -236,7 +247,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - paths_.MergeFrom(from.paths_); + _impl_.paths_.MergeFrom(from._impl_.paths_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -254,7 +265,7 @@ void FieldMask::InternalSwap(FieldMask* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - paths_.InternalSwap(&other->paths_); + _impl_.paths_.InternalSwap(&other->_impl_.paths_); } ::PROTOBUF_NAMESPACE_ID::Metadata FieldMask::GetMetadata() const {
diff --git a/src/google/protobuf/field_mask.pb.h b/src/google/protobuf/field_mask.pb.h index 2a2b22f..ae350d5 100644 --- a/src/google/protobuf/field_mask.pb.h +++ b/src/google/protobuf/field_mask.pb.h
@@ -147,10 +147,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FieldMask* other); @@ -208,8 +208,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> paths_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> paths_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ffield_5fmask_2eproto; }; // =================================================================== @@ -225,13 +228,13 @@ // repeated string paths = 1; inline int FieldMask::_internal_paths_size() const { - return paths_.size(); + return _impl_.paths_.size(); } inline int FieldMask::paths_size() const { return _internal_paths_size(); } inline void FieldMask::clear_paths() { - paths_.Clear(); + _impl_.paths_.Clear(); } inline std::string* FieldMask::add_paths() { std::string* _s = _internal_add_paths(); @@ -239,7 +242,7 @@ return _s; } inline const std::string& FieldMask::_internal_paths(int index) const { - return paths_.Get(index); + return _impl_.paths_.Get(index); } inline const std::string& FieldMask::paths(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.FieldMask.paths) @@ -247,55 +250,55 @@ } inline std::string* FieldMask::mutable_paths(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.FieldMask.paths) - return paths_.Mutable(index); + return _impl_.paths_.Mutable(index); } inline void FieldMask::set_paths(int index, const std::string& value) { - paths_.Mutable(index)->assign(value); + _impl_.paths_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths) } inline void FieldMask::set_paths(int index, std::string&& value) { - paths_.Mutable(index)->assign(std::move(value)); + _impl_.paths_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:google.protobuf.FieldMask.paths) } inline void FieldMask::set_paths(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); - paths_.Mutable(index)->assign(value); + _impl_.paths_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.FieldMask.paths) } inline void FieldMask::set_paths(int index, const char* value, size_t size) { - paths_.Mutable(index)->assign( + _impl_.paths_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.FieldMask.paths) } inline std::string* FieldMask::_internal_add_paths() { - return paths_.Add(); + return _impl_.paths_.Add(); } inline void FieldMask::add_paths(const std::string& value) { - paths_.Add()->assign(value); + _impl_.paths_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths) } inline void FieldMask::add_paths(std::string&& value) { - paths_.Add(std::move(value)); + _impl_.paths_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.FieldMask.paths) } inline void FieldMask::add_paths(const char* value) { GOOGLE_DCHECK(value != nullptr); - paths_.Add()->assign(value); + _impl_.paths_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.FieldMask.paths) } inline void FieldMask::add_paths(const char* value, size_t size) { - paths_.Add()->assign(reinterpret_cast<const char*>(value), size); + _impl_.paths_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.FieldMask.paths) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& FieldMask::paths() const { // @@protoc_insertion_point(field_list:google.protobuf.FieldMask.paths) - return paths_; + return _impl_.paths_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* FieldMask::mutable_paths() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.FieldMask.paths) - return &paths_; + return &_impl_.paths_; } #ifdef __GNUC__
diff --git a/src/google/protobuf/generated_message_reflection.cc b/src/google/protobuf/generated_message_reflection.cc index c63f3ad..5cb5872 100644 --- a/src/google/protobuf/generated_message_reflection.cc +++ b/src/google/protobuf/generated_message_reflection.cc
@@ -257,7 +257,11 @@ } bool Reflection::IsLazilyVerifiedLazyField(const FieldDescriptor* field) const { - return field->options().lazy() || field->options().unverified_lazy(); + if (field->options().unverified_lazy()) return true; + + // Message fields with [lazy=true] will be eagerly verified + // (go/verified-lazy). + return field->options().lazy() && !IsEagerlyVerifiedLazyField(field); } bool Reflection::IsEagerlyVerifiedLazyField( @@ -3107,6 +3111,56 @@ } } +bool IsDescendant(Message* root, const Message& message) { + const Reflection* reflection = root->GetReflection(); + std::vector<const FieldDescriptor*> fields; + reflection->ListFieldsOmitStripped(*root, &fields); + + for (const auto* field : fields) { + // Skip non-message fields. + if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; + + // Optional messages. + if (!field->is_repeated()) { + Message* sub_message = reflection->MutableMessage(root, field); + if (sub_message == &message || IsDescendant(sub_message, message)) { + return true; + } + continue; + } + + // Repeated messages. + if (!IsMapFieldInApi(field)) { + int count = reflection->FieldSize(*root, field); + for (int i = 0; i < count; i++) { + Message* sub_message = + reflection->MutableRepeatedMessage(root, field, i); + if (sub_message == &message || IsDescendant(sub_message, message)) { + return true; + } + } + continue; + } + + // Map field: if accessed as repeated fields, messages are *copied* and + // matching pointer won't work. Must directly access map. + constexpr int kValIdx = 1; + const FieldDescriptor* val_field = field->message_type()->field(kValIdx); + // Skip map fields whose value type is not message. + if (val_field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) continue; + + MapIterator end = reflection->MapEnd(root, field); + for (auto iter = reflection->MapBegin(root, field); iter != end; ++iter) { + Message* sub_message = iter.MutableValueRef()->MutableMessageValue(); + if (sub_message == &message || IsDescendant(sub_message, message)) { + return true; + } + } + } + + return false; +} + } // namespace internal } // namespace protobuf } // namespace google
diff --git a/src/google/protobuf/generated_message_reflection_unittest.cc b/src/google/protobuf/generated_message_reflection_unittest.cc index 4979616..069b5c8 100644 --- a/src/google/protobuf/generated_message_reflection_unittest.cc +++ b/src/google/protobuf/generated_message_reflection_unittest.cc
@@ -48,9 +48,7 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/map_test_util.h> #include <google/protobuf/map_unittest.pb.h> -#include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_mset.pb.h> #include <google/protobuf/unittest_mset_wire_format.pb.h> @@ -58,6 +56,8 @@ #include <google/protobuf/descriptor.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> +#include <google/protobuf/map_test_util.h> +#include <google/protobuf/test_util.h> // Must be included last. #include <google/protobuf/port_def.inc> @@ -78,6 +78,14 @@ static bool IsLazyField(const Message& msg, const FieldDescriptor* field) { return msg.GetReflection()->IsLazyField(field); } + static bool IsEagerlyVerifiedLazyField(const Message& msg, + const FieldDescriptor* field) { + return msg.GetReflection()->IsEagerlyVerifiedLazyField(field); + } + static bool IsLazilyVerifiedLazyField(const Message& msg, + const FieldDescriptor* field) { + return msg.GetReflection()->IsLazilyVerifiedLazyField(field); + } }; namespace { @@ -152,28 +160,6 @@ } -TEST(GeneratedMessageReflectionTest, DefaultsAfterClear) { - // Check that after setting all fields and then clearing, getting an - // embedded message does NOT return the default instance. - unittest::TestAllTypes message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); - - TestUtil::SetAllFields(&message); - message.Clear(); - - const Reflection* reflection = message.GetReflection(); - - EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(), - &reflection->GetMessage(message, F("optionalgroup"))); - EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), - &reflection->GetMessage(message, F("optional_nested_message"))); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &reflection->GetMessage(message, F("optional_foreign_message"))); - EXPECT_NE(&unittest_import::ImportMessage::default_instance(), - &reflection->GetMessage(message, F("optional_import_message"))); -} - class GeneratedMessageReflectionSwapTest : public testing::TestWithParam<bool> { protected: void Swap(const Reflection* reflection, Message* lhs, Message* rhs) { @@ -567,7 +553,7 @@ auto* message1 = Arena::CreateMessage<unittest::TestOneof2>(&arena); auto* message2 = Arena::CreateMessage<unittest::TestOneof2>(&arena); TestUtil::SetOneof1(message1); - message1->mutable_foo_message()->set_qux_int(1000); + message1->mutable_foo_message()->set_moo_int(1000); auto* kept_foo_ptr = message1->mutable_foo_message(); std::vector<const FieldDescriptor*> fields; @@ -579,7 +565,7 @@ message1, message2, fields); EXPECT_TRUE(message2->has_foo_message()); - EXPECT_EQ(message2->foo_message().qux_int(), 1000); + EXPECT_EQ(message2->foo_message().moo_int(), 1000); EXPECT_EQ(kept_foo_ptr, message2->mutable_foo_message()); } @@ -1322,6 +1308,67 @@ #endif // PROTOBUF_HAS_DEATH_TEST +using internal::IsDescendant; + +TEST(GeneratedMessageReflection, IsDescendantMessage) { + unittest::TestAllTypes msg1, msg2; + TestUtil::SetAllFields(&msg1); + msg2 = msg1; + + EXPECT_TRUE(IsDescendant(&msg1, msg1.optional_nested_message())); + EXPECT_TRUE(IsDescendant(&msg1, msg1.repeated_foreign_message(0))); + + EXPECT_FALSE(IsDescendant(&msg1, msg2.optional_nested_message())); + EXPECT_FALSE(IsDescendant(&msg1, msg2.repeated_foreign_message(0))); +} + +TEST(GeneratedMessageReflection, IsDescendantMap) { + unittest::TestMap msg1, msg2; + (*msg1.mutable_map_int32_foreign_message())[0].set_c(100); + TestUtil::SetAllFields(&(*msg1.mutable_map_int32_all_types())[0]); + msg2 = msg1; + + EXPECT_TRUE(IsDescendant(&msg1, msg1.map_int32_foreign_message().at(0))); + EXPECT_TRUE(IsDescendant(&msg1, msg1.map_int32_all_types().at(0))); + + EXPECT_FALSE(IsDescendant(&msg1, msg2.map_int32_foreign_message().at(0))); + EXPECT_FALSE(IsDescendant(&msg1, msg2.map_int32_all_types().at(0))); +} + +TEST(GeneratedMessageReflection, IsDescendantExtension) { + unittest::TestAllExtensions msg1, msg2; + TestUtil::SetAllExtensions(&msg1); + msg2 = msg1; + + EXPECT_TRUE(IsDescendant( + &msg1, msg1.GetExtension(unittest::optional_nested_message_extension))); + EXPECT_TRUE(IsDescendant( + &msg1, + msg1.GetExtension(unittest::repeated_foreign_message_extension, 0))); + + EXPECT_FALSE(IsDescendant( + &msg1, msg2.GetExtension(unittest::optional_nested_message_extension))); + EXPECT_FALSE(IsDescendant( + &msg1, + msg2.GetExtension(unittest::repeated_foreign_message_extension, 0))); +} + +TEST(GeneratedMessageReflection, IsDescendantOneof) { + unittest::TestOneof msg1, msg2; + TestUtil::SetAllFields(msg1.mutable_foo_message()); + msg2 = msg1; + + EXPECT_TRUE( + IsDescendant(&msg1, msg1.foo_message().optional_nested_message())); + EXPECT_TRUE( + IsDescendant(&msg1, msg1.foo_message().repeated_foreign_message(0))); + + EXPECT_FALSE( + IsDescendant(&msg1, msg2.foo_message().optional_nested_message())); + EXPECT_FALSE( + IsDescendant(&msg1, msg2.foo_message().repeated_foreign_message(0))); +} + } // namespace } // namespace protobuf } // namespace google
diff --git a/src/google/protobuf/generated_message_tctable_impl.h b/src/google/protobuf/generated_message_tctable_impl.h index c2be089..21fa533 100644 --- a/src/google/protobuf/generated_message_tctable_impl.h +++ b/src/google/protobuf/generated_message_tctable_impl.h
@@ -400,6 +400,13 @@ return *target; } + template <typename T> + static inline T ReadAt(const void* x, size_t offset) { + T out; + memcpy(&out, static_cast<const char*>(x) + offset, sizeof(T)); + return out; + } + // Mini parsing: // // This function parses a field from incoming data based on metadata stored in
diff --git a/src/google/protobuf/generated_message_tctable_lite.cc b/src/google/protobuf/generated_message_tctable_lite.cc index d56a3f0..9993811 100644 --- a/src/google/protobuf/generated_message_tctable_lite.cc +++ b/src/google/protobuf/generated_message_tctable_lite.cc
@@ -84,10 +84,10 @@ MessageLite* msg, const char* ptr, ParseContext* ctx, const TcParseTableBase* table) { ScopedArenaSwap saved(msg, ctx); - const uint32_t has_bits_offset = table->has_bits_offset; while (!ctx->Done(&ptr)) { - uint64_t hasbits = 0; - if (has_bits_offset) hasbits = RefAt<uint32_t>(msg, has_bits_offset); + // Unconditionally read has bits, even if we don't have has bits. + // has_bits_offset will be 0 and we will just read something valid. + uint64_t hasbits = ReadAt<uint32_t>(msg, table->has_bits_offset); ptr = TagDispatch(msg, ptr, ctx, table, hasbits, {}); if (ptr == nullptr) break; if (ctx->LastTag() != 1) break; // Ended on terminating tag @@ -301,7 +301,7 @@ const char* TcParser::MiniParse(PROTOBUF_TC_PARAM_DECL) { uint32_t tag; - ptr = ReadTag(ptr, &tag); + ptr = ReadTagInlined(ptr, &tag); if (PROTOBUF_PREDICT_FALSE(ptr == nullptr)) return nullptr; auto* entry = FindFieldEntry(table, tag >> 3); @@ -371,13 +371,13 @@ auto saved_tag = UnalignedLoad<TagType>(ptr); ptr += sizeof(TagType); hasbits |= (uint64_t{1} << data.hasbit_idx()); + SyncHasbits(msg, hasbits, table); auto& field = RefAt<MessageLite*>(msg, data.offset()); if (field == nullptr) { const MessageLite* default_instance = table->field_aux(data.aux_idx())->message_default; field = default_instance->New(ctx->data().arena); } - SyncHasbits(msg, hasbits, table); if (group_coding) { return ctx->ParseGroup(field, ptr, FastDecodeTag(saved_tag)); } @@ -456,7 +456,7 @@ } ptr += sizeof(TagType); // Consume tag hasbits |= (uint64_t{1} << data.hasbit_idx()); - std::memcpy(Offset(msg, data.offset()), ptr, sizeof(LayoutType)); + RefAt<LayoutType>(msg, data.offset()) = UnalignedLoad<LayoutType>(ptr); ptr += sizeof(LayoutType); PROTOBUF_MUSTTAIL return ToTagDispatch(PROTOBUF_TC_PARAM_PASS); } @@ -501,7 +501,7 @@ auto expected_tag = UnalignedLoad<TagType>(ptr); do { ptr += sizeof(TagType); - std::memcpy(elem + (idx++), ptr, sizeof(LayoutType)); + elem[idx++] = UnalignedLoad<LayoutType>(ptr); ptr += sizeof(LayoutType); if (idx >= space) break; if (!ctx->DataAvailable(ptr)) break; @@ -580,6 +580,35 @@ namespace { +// Shift "byte" left by n * 7 bits, filling vacated bits with ones. +template <int n> +inline PROTOBUF_ALWAYS_INLINE uint64_t +shift_left_fill_with_ones(uint64_t byte, uint64_t ones) { + return (byte << (n * 7)) | (ones >> (64 - (n * 7))); +} + +// Shift "byte" left by n * 7 bits, filling vacated bits with ones, and +// put the new value in res. Return whether the result was negative. +template <int n> +inline PROTOBUF_ALWAYS_INLINE bool shift_left_fill_with_ones_was_negative( + uint64_t byte, uint64_t ones, int64_t& res) { +#if defined(__GCC_ASM_FLAG_OUTPUTS__) && defined(__x86_64__) + // For the first two rounds (ptr[1] and ptr[2]), micro benchmarks show a + // substantial improvement from capturing the sign from the condition code + // register on x86-64. + bool sign_bit; + asm("shldq %3, %2, %1" + : "=@ccs"(sign_bit), "+r"(byte) + : "r"(ones), "i"(n * 7)); + res = byte; + return sign_bit; +#else + // Generic fallback: + res = (byte << (n * 7)) | (ones >> (64 - (n * 7))); + return static_cast<int64_t>(res) < 0; +#endif +} + inline PROTOBUF_ALWAYS_INLINE std::pair<const char*, uint64_t> Parse64FallbackPair(const char* p, int64_t res1) { auto ptr = reinterpret_cast<const int8_t*>(p); @@ -601,78 +630,42 @@ // has 57 high bits of ones, which is enough for the largest shift done. GOOGLE_DCHECK_EQ(res1 >> 7, -1); uint64_t ones = res1; // save the high 1 bits from res1 (input to SHLD) - uint64_t byte; // the "next" 7-bit chunk, shifted (result from SHLD) int64_t res2, res3; // accumulated result chunks -#define SHLD(n) byte = ((byte << (n * 7)) | (ones >> (64 - (n * 7)))) - int sign_bit; -#if defined(__GCC_ASM_FLAG_OUTPUTS__) && defined(__x86_64__) - // For the first two rounds (ptr[1] and ptr[2]), micro benchmarks show a - // substantial improvement from capturing the sign from the condition code - // register on x86-64. -#define SHLD_SIGN(n) \ - asm("shldq %3, %2, %1" \ - : "=@ccs"(sign_bit), "+r"(byte) \ - : "r"(ones), "i"(n * 7)) -#else - // Generic fallback: -#define SHLD_SIGN(n) \ - do { \ - SHLD(n); \ - sign_bit = static_cast<int64_t>(byte) < 0; \ - } while (0) -#endif - - byte = ptr[1]; - SHLD_SIGN(1); - res2 = byte; - if (!sign_bit) goto done2; - byte = ptr[2]; - SHLD_SIGN(2); - res3 = byte; - if (!sign_bit) goto done3; - -#undef SHLD_SIGN + if (!shift_left_fill_with_ones_was_negative<1>(ptr[1], ones, res2)) + goto done2; + if (!shift_left_fill_with_ones_was_negative<2>(ptr[2], ones, res3)) + goto done3; // For the remainder of the chunks, check the sign of the AND result. - byte = ptr[3]; - SHLD(3); - res1 &= byte; + res1 &= shift_left_fill_with_ones<3>(ptr[3], ones); if (res1 >= 0) goto done4; - byte = ptr[4]; - SHLD(4); - res2 &= byte; + res2 &= shift_left_fill_with_ones<4>(ptr[4], ones); if (res2 >= 0) goto done5; - byte = ptr[5]; - SHLD(5); - res3 &= byte; + res3 &= shift_left_fill_with_ones<5>(ptr[5], ones); if (res3 >= 0) goto done6; - byte = ptr[6]; - SHLD(6); - res1 &= byte; + res1 &= shift_left_fill_with_ones<6>(ptr[6], ones); if (res1 >= 0) goto done7; - byte = ptr[7]; - SHLD(7); - res2 &= byte; + res2 &= shift_left_fill_with_ones<7>(ptr[7], ones); if (res2 >= 0) goto done8; - byte = ptr[8]; - SHLD(8); - res3 &= byte; + res3 &= shift_left_fill_with_ones<8>(ptr[8], ones); if (res3 >= 0) goto done9; -#undef SHLD - // For valid 64bit varints, the 10th byte/ptr[9] should be exactly 1. In this // case, the continuation bit of ptr[8] already set the top bit of res3 // correctly, so all we have to do is check that the expected case is true. - byte = ptr[9]; - if (PROTOBUF_PREDICT_TRUE(byte == 1)) goto done10; + if (PROTOBUF_PREDICT_TRUE(ptr[9] == 1)) goto done10; // A value of 0, however, represents an over-serialized varint. This case // should not happen, but if does (say, due to a nonconforming serializer), // deassert the continuation bit that came from ptr[8]. - if (byte == 0) { + if (ptr[9] == 0) { +#if defined(__GCC_ASM_FLAG_OUTPUTS__) && defined(__x86_64__) + // Use a small instruction since this is an uncommon code path. + asm("btcq $63,%0" : "+r"(res3)); +#else res3 ^= static_cast<uint64_t>(1) << 63; +#endif goto done10; } @@ -680,18 +673,24 @@ // fit in 64 bits. If the continue bit is set, it is an unterminated varint. return {nullptr, 0}; -#define DONE(n) done##n : return {p + n, res1 & res2 & res3}; done2: return {p + 2, res1 & res2}; - DONE(3) - DONE(4) - DONE(5) - DONE(6) - DONE(7) - DONE(8) - DONE(9) - DONE(10) -#undef DONE +done3: + return {p + 3, res1 & res2 & res3}; +done4: + return {p + 4, res1 & res2 & res3}; +done5: + return {p + 5, res1 & res2 & res3}; +done6: + return {p + 6, res1 & res2 & res3}; +done7: + return {p + 7, res1 & res2 & res3}; +done8: + return {p + 8, res1 & res2 & res3}; +done9: + return {p + 9, res1 & res2 & res3}; +done10: + return {p + 10, res1 & res2 & res3}; } inline PROTOBUF_ALWAYS_INLINE const char* ParseVarint(const char* p, @@ -1371,10 +1370,10 @@ } // Copy the value: if (rep == field_layout::kRep64Bits) { - std::memcpy(Offset(msg, entry.offset), ptr, sizeof(uint64_t)); + RefAt<uint64_t>(msg, entry.offset) = UnalignedLoad<uint64_t>(ptr); ptr += sizeof(uint64_t); } else { - std::memcpy(Offset(msg, entry.offset), ptr, sizeof(uint32_t)); + RefAt<uint32_t>(msg, entry.offset) = UnalignedLoad<uint32_t>(ptr); ptr += sizeof(uint32_t); } PROTOBUF_MUSTTAIL return ToTagDispatch(PROTOBUF_TC_PARAM_PASS); @@ -1402,7 +1401,7 @@ uint32_t next_tag; do { ptr = ptr2; - std::memcpy(field.Add(), ptr, size); + *field.Add() = UnalignedLoad<uint64_t>(ptr); ptr += size; if (!ctx->DataAvailable(ptr)) break; ptr2 = ReadTag(ptr, &next_tag); @@ -1418,7 +1417,7 @@ uint32_t next_tag; do { ptr = ptr2; - std::memcpy(field.Add(), ptr, size); + *field.Add() = UnalignedLoad<uint32_t>(ptr); ptr += size; if (!ctx->DataAvailable(ptr)) break; ptr2 = ReadTag(ptr, &next_tag);
diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h index 1024b40..c8fc994 100644 --- a/src/google/protobuf/io/coded_stream.h +++ b/src/google/protobuf/io/coded_stream.h
@@ -121,36 +121,13 @@ #include <type_traits> #include <utility> -#ifdef _WIN32 -// Assuming windows is always little-endian. -#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) -#define PROTOBUF_LITTLE_ENDIAN 1 -#endif #if defined(_MSC_VER) && _MSC_VER >= 1300 && !defined(__INTEL_COMPILER) // If MSVC has "/RTCc" set, it will complain about truncating casts at // runtime. This file contains some intentional truncating casts. #pragma runtime_checks("c", off) #endif -#else -#ifdef __APPLE__ -#include <machine/endian.h> // __BYTE_ORDER -#elif defined(__FreeBSD__) -#include <sys/endian.h> // __BYTE_ORDER -#elif (defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)) -#include <sys/isa_defs.h> // __BYTE_ORDER -#elif defined(_AIX) || defined(__TOS_AIX__) -#include <sys/machine.h> // BYTE_ORDER -#else -#if !defined(__QNX__) -#include <endian.h> // __BYTE_ORDER -#endif -#endif -#if ((defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)) || \ - (defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN)) && \ - !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) -#define PROTOBUF_LITTLE_ENDIAN 1 -#endif -#endif + + #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/strutil.h> @@ -957,7 +934,8 @@ template <int S> uint8_t* WriteRawLittleEndian(const void* data, int size, uint8_t* ptr); -#ifndef PROTOBUF_LITTLE_ENDIAN +#if !defined(PROTOBUF_LITTLE_ENDIAN) || \ + defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) uint8_t* WriteRawLittleEndian32(const void* data, int size, uint8_t* ptr); uint8_t* WriteRawLittleEndian64(const void* data, int size, uint8_t* ptr); #endif @@ -1004,7 +982,8 @@ inline uint8_t* EpsCopyOutputStream::WriteRawLittleEndian<4>(const void* data, int size, uint8_t* ptr) { -#ifdef PROTOBUF_LITTLE_ENDIAN +#if defined(PROTOBUF_LITTLE_ENDIAN) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) return WriteRaw(data, size, ptr); #else return WriteRawLittleEndian32(data, size, ptr); @@ -1014,7 +993,8 @@ inline uint8_t* EpsCopyOutputStream::WriteRawLittleEndian<8>(const void* data, int size, uint8_t* ptr) { -#ifdef PROTOBUF_LITTLE_ENDIAN +#if defined(PROTOBUF_LITTLE_ENDIAN) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) return WriteRaw(data, size, ptr); #else return WriteRawLittleEndian64(data, size, ptr); @@ -1357,7 +1337,8 @@ // static inline const uint8_t* CodedInputStream::ReadLittleEndian32FromArray( const uint8_t* buffer, uint32_t* value) { -#if defined(PROTOBUF_LITTLE_ENDIAN) +#if defined(PROTOBUF_LITTLE_ENDIAN) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) memcpy(value, buffer, sizeof(*value)); return buffer + sizeof(*value); #else @@ -1371,7 +1352,8 @@ // static inline const uint8_t* CodedInputStream::ReadLittleEndian64FromArray( const uint8_t* buffer, uint64_t* value) { -#if defined(PROTOBUF_LITTLE_ENDIAN) +#if defined(PROTOBUF_LITTLE_ENDIAN) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) memcpy(value, buffer, sizeof(*value)); return buffer + sizeof(*value); #else @@ -1389,7 +1371,8 @@ } inline bool CodedInputStream::ReadLittleEndian32(uint32_t* value) { -#if defined(PROTOBUF_LITTLE_ENDIAN) +#if defined(PROTOBUF_LITTLE_ENDIAN) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) { buffer_ = ReadLittleEndian32FromArray(buffer_, value); return true; @@ -1402,7 +1385,8 @@ } inline bool CodedInputStream::ReadLittleEndian64(uint64_t* value) { -#if defined(PROTOBUF_LITTLE_ENDIAN) +#if defined(PROTOBUF_LITTLE_ENDIAN) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) if (PROTOBUF_PREDICT_TRUE(BufferSize() >= static_cast<int>(sizeof(*value)))) { buffer_ = ReadLittleEndian64FromArray(buffer_, value); return true; @@ -1689,7 +1673,8 @@ inline uint8_t* CodedOutputStream::WriteLittleEndian32ToArray(uint32_t value, uint8_t* target) { -#if defined(PROTOBUF_LITTLE_ENDIAN) +#if defined(PROTOBUF_LITTLE_ENDIAN) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) memcpy(target, &value, sizeof(value)); #else target[0] = static_cast<uint8_t>(value); @@ -1702,7 +1687,8 @@ inline uint8_t* CodedOutputStream::WriteLittleEndian64ToArray(uint64_t value, uint8_t* target) { -#if defined(PROTOBUF_LITTLE_ENDIAN) +#if defined(PROTOBUF_LITTLE_ENDIAN) && \ + !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) memcpy(target, &value, sizeof(value)); #else uint32_t part0 = static_cast<uint32_t>(value);
diff --git a/src/google/protobuf/io/gzip_stream.h b/src/google/protobuf/io/gzip_stream.h index 5dc7aa8..4cf71b6 100644 --- a/src/google/protobuf/io/gzip_stream.h +++ b/src/google/protobuf/io/gzip_stream.h
@@ -47,7 +47,7 @@ #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/port.h> -#include <zlib.h> +#include "zlib.h" // Must be included last. #include <google/protobuf/port_def.inc>
diff --git a/src/google/protobuf/io/tokenizer.cc b/src/google/protobuf/io/tokenizer.cc index 6b4b92e..f9e0776 100644 --- a/src/google/protobuf/io/tokenizer.cc +++ b/src/google/protobuf/io/tokenizer.cc
@@ -98,6 +98,9 @@ #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/stubs/stl_util.h> +// Must be included last. +#include <google/protobuf/port_def.inc> + namespace google { namespace protobuf { namespace io { @@ -147,12 +150,32 @@ // Given a char, interpret it as a numeric digit and return its value. // This supports any number base up to 36. -inline int DigitValue(char digit) { - if ('0' <= digit && digit <= '9') return digit - '0'; - if ('a' <= digit && digit <= 'z') return digit - 'a' + 10; - if ('A' <= digit && digit <= 'Z') return digit - 'A' + 10; - return -1; -} +// Represents integer values of digits. +// Uses 36 to indicate an invalid character since we support +// bases up to 36. +static const int8_t kAsciiToInt[256] = { + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // 00-0F + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // 10-1F + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // ' '-'/' + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // '0'-'9' + 36, 36, 36, 36, 36, 36, 36, // ':'-'@' + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'P' + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, // 'Q'-'Z' + 36, 36, 36, 36, 36, 36, // '['-'`' + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'a'-'p' + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, // 'q'-'z' + 36, 36, 36, 36, 36, // '{'-DEL + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // 80-8F + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // 90-9F + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // A0-AF + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // B0-BF + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // C0-CF + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // D0-DF + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // E0-EF + 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // F0-FF +}; + +inline int DigitValue(char digit) { return kAsciiToInt[digit & 0xFF]; } // Inline because it's only used in one place. inline char TranslateEscape(char c) { @@ -911,25 +934,49 @@ bool Tokenizer::ParseInteger(const std::string& text, uint64_t max_value, uint64_t* output) { - // Sadly, we can't just use strtoul() since it is only 32-bit and strtoull() - // is non-standard. I hate the C standard library. :( + // We can't just use strtoull() because (a) it accepts negative numbers, + // (b) We want additional range checks, (c) it reports overflows via errno. - // return strtoull(text.c_str(), NULL, 0); +#if 0 + const char *str_begin = text.c_str(); + if (*str_begin == '-') return false; + char *str_end = nullptr; + errno = 0; + *output = std::strtoull(str_begin, &str_end, 0); + return (errno == 0 && str_end && *str_end == '\0' && *output <= max_value); +#endif const char* ptr = text.c_str(); int base = 10; + uint64_t overflow_if_mul_base = (kuint64max / 10) + 1; if (ptr[0] == '0') { if (ptr[1] == 'x' || ptr[1] == 'X') { // This is hex. base = 16; + overflow_if_mul_base = (kuint64max / 16) + 1; ptr += 2; } else { // This is octal. base = 8; + overflow_if_mul_base = (kuint64max / 8) + 1; } } uint64_t result = 0; + // For all the leading '0's, and also the first non-zero character, we + // don't need to multiply. + while (*ptr != '\0') { + int digit = DigitValue(*ptr++); + if (digit >= base) { + // The token provided by Tokenizer is invalid. i.e., 099 is an invalid + // token, but Tokenizer still think it's integer. + return false; + } + if (digit != 0) { + result = digit; + break; + } + } for (; *ptr != '\0'; ptr++) { int digit = DigitValue(*ptr); if (digit < 0 || digit >= base) { @@ -937,13 +984,18 @@ // token, but Tokenizer still think it's integer. return false; } - if (static_cast<uint64_t>(digit) > max_value || - result > (max_value - digit) / base) { - // Overflow. + if (result >= overflow_if_mul_base) { + // We know the multiply we're about to do will overflow, so exit now. return false; } + // We know that result * base won't overflow, but adding digit might... result = result * base + digit; + // C++ guarantees defined "wrap" semantics when unsigned integer + // operations overflow, making this a fast way to check if adding + // digit made result overflow, and thus, wrap around. + if (result < static_cast<uint64_t>(base)) return false; } + if (result > max_value) return false; *output = result; return true; @@ -1183,3 +1235,5 @@ } // namespace io } // namespace protobuf } // namespace google + +#include <google/protobuf/port_undef.inc>
diff --git a/src/google/protobuf/io/tokenizer_unittest.cc b/src/google/protobuf/io/tokenizer_unittest.cc index 0b2e76c..16ba940 100644 --- a/src/google/protobuf/io/tokenizer_unittest.cc +++ b/src/google/protobuf/io/tokenizer_unittest.cc
@@ -178,9 +178,10 @@ class TokenizerTest : public testing::Test { protected: // For easy testing. - uint64 ParseInteger(const std::string& text) { - uint64 result; - EXPECT_TRUE(Tokenizer::ParseInteger(text, kuint64max, &result)); + uint64_t ParseInteger(const std::string& text) { + uint64_t result; + EXPECT_TRUE(Tokenizer::ParseInteger(text, kuint64max, &result)) + << "'" << text << "'"; return result; } }; @@ -809,8 +810,8 @@ // ------------------------------------------------------------------- -// Test parse helpers. It's not really worth setting up a full data-driven -// test here. +// Test parse helpers. +// TODO(b/225783758): Add a fuzz test for this. TEST_F(TokenizerTest, ParseInteger) { EXPECT_EQ(0, ParseInteger("0")); EXPECT_EQ(123, ParseInteger("123")); @@ -823,7 +824,7 @@ // Test invalid integers that may still be tokenized as integers. EXPECT_EQ(0, ParseInteger("0x")); - uint64 i; + uint64_t i; // Test invalid integers that will never be tokenized as integers. EXPECT_FALSE(Tokenizer::ParseInteger("zxy", kuint64max, &i)); @@ -840,6 +841,107 @@ EXPECT_FALSE(Tokenizer::ParseInteger("12346", 12345, &i)); EXPECT_TRUE(Tokenizer::ParseInteger("0xFFFFFFFFFFFFFFFF", kuint64max, &i)); EXPECT_FALSE(Tokenizer::ParseInteger("0x10000000000000000", kuint64max, &i)); + + // Test near the limits of signed parsing (values in kint64max +/- 1600) + for (int64_t offset = -1600; offset <= 1600; ++offset) { + // We make sure to perform an unsigned addition so that we avoid signed + // overflow, which would be undefined behavior. + uint64_t i = 0x7FFFFFFFFFFFFFFFu + static_cast<uint64_t>(offset); + char decimal[32]; + snprintf(decimal, 32, "%llu", static_cast<unsigned long long>(i)); + if (offset > 0) { + uint64_t parsed = -1; + EXPECT_FALSE(Tokenizer::ParseInteger(decimal, kint64max, &parsed)) + << decimal << "=>" << parsed; + } else { + uint64_t parsed = -1; + EXPECT_TRUE(Tokenizer::ParseInteger(decimal, kint64max, &parsed)) + << decimal << "=>" << parsed; + EXPECT_EQ(parsed, i); + } + char octal[32]; + snprintf(octal, 32, "0%llo", static_cast<unsigned long long>(i)); + if (offset > 0) { + uint64_t parsed = -1; + EXPECT_FALSE(Tokenizer::ParseInteger(octal, kint64max, &parsed)) + << octal << "=>" << parsed; + } else { + uint64_t parsed = -1; + EXPECT_TRUE(Tokenizer::ParseInteger(octal, kint64max, &parsed)) + << octal << "=>" << parsed; + EXPECT_EQ(parsed, i); + } + char hex[32]; + snprintf(hex, 32, "0x%llx", static_cast<unsigned long long>(i)); + if (offset > 0) { + uint64_t parsed = -1; + EXPECT_FALSE(Tokenizer::ParseInteger(hex, kint64max, &parsed)) + << hex << "=>" << parsed; + } else { + uint64_t parsed = -1; + EXPECT_TRUE(Tokenizer::ParseInteger(hex, kint64max, &parsed)) << hex; + EXPECT_EQ(parsed, i); + } + // EXPECT_NE(offset, -237); + } + + // Test near the limits of unsigned parsing (values in kuint64max +/- 1600) + // By definition, values greater than kuint64max cannot be held in a uint64_t + // variable, so printing them is a little tricky; fortunately all but the + // last four digits are known, so we can hard-code them in the printf string, + // and we only need to format the last 4. + for (int64_t offset = -1600; offset <= 1600; ++offset) { + { + uint64_t i = 18446744073709551615u + offset; + char decimal[32]; + snprintf(decimal, 32, "1844674407370955%04llu", + static_cast<unsigned long long>(1615 + offset)); + if (offset > 0) { + uint64_t parsed = -1; + EXPECT_FALSE(Tokenizer::ParseInteger(decimal, kuint64max, &parsed)) + << decimal << "=>" << parsed; + } else { + uint64_t parsed = -1; + EXPECT_TRUE(Tokenizer::ParseInteger(decimal, kuint64max, &parsed)) + << decimal; + EXPECT_EQ(parsed, i); + } + } + { + uint64_t i = 01777777777777777777777u + offset; + if (offset > 0) { + char octal[32]; + snprintf(octal, 32, "0200000000000000000%04llo", + static_cast<unsigned long long>(offset - 1)); + uint64_t parsed = -1; + EXPECT_FALSE(Tokenizer::ParseInteger(octal, kuint64max, &parsed)) + << octal << "=>" << parsed; + } else { + char octal[32]; + snprintf(octal, 32, "0%llo", static_cast<unsigned long long>(i)); + uint64_t parsed = -1; + EXPECT_TRUE(Tokenizer::ParseInteger(octal, kuint64max, &parsed)) + << octal; + EXPECT_EQ(parsed, i); + } + } + { + uint64_t ui = 0xffffffffffffffffu + offset; + char hex[32]; + if (offset > 0) { + snprintf(hex, 32, "0x1000000000000%04llx", + static_cast<unsigned long long>(offset - 1)); + uint64_t parsed = -1; + EXPECT_FALSE(Tokenizer::ParseInteger(hex, kuint64max, &parsed)) + << hex << "=>" << parsed; + } else { + snprintf(hex, 32, "0x%llx", static_cast<unsigned long long>(ui)); + uint64_t parsed = -1; + EXPECT_TRUE(Tokenizer::ParseInteger(hex, kuint64max, &parsed)) << hex; + EXPECT_EQ(parsed, ui); + } + } + } } TEST_F(TokenizerTest, ParseFloat) {
diff --git a/src/google/protobuf/lite_unittest.cc b/src/google/protobuf/lite_unittest.cc index d4fe499..583d325 100644 --- a/src/google/protobuf/lite_unittest.cc +++ b/src/google/protobuf/lite_unittest.cc
@@ -30,23 +30,25 @@ // Author: kenton@google.com (Kenton Varda) +#include <climits> #include <iostream> #include <string> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/arena_test_util.h> -#include <google/protobuf/map_lite_test_util.h> #include <google/protobuf/map_lite_unittest.pb.h> -#include <google/protobuf/test_util_lite.h> #include <google/protobuf/unittest_lite.pb.h> +#include <gtest/gtest.h> +#include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/arena_test_util.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> +#include <google/protobuf/map_lite_test_util.h> +#include <google/protobuf/parse_context.h> +#include <google/protobuf/test_util_lite.h> #include <google/protobuf/wire_format_lite.h> -#include <gtest/gtest.h> -#include <google/protobuf/stubs/strutil.h> namespace google { namespace protobuf { @@ -88,6 +90,61 @@ empty_message->ParseFromString(data); } + +TEST(ParseVarintTest, Varint32) { + auto test_value = [](uint32_t value, int varint_length) { + uint8_t buffer[10]; + uint8_t* p = io::CodedOutputStream::WriteVarint32ToArray(value, buffer); + ASSERT_EQ(p - buffer, varint_length) << "Value = " << value; + + const char* cbuffer = reinterpret_cast<const char*>(buffer); + uint32_t parsed = ~value; + const char* r = internal::VarintParse(cbuffer, &parsed); + ASSERT_EQ(r - cbuffer, varint_length) << "Value = " << value; + ASSERT_EQ(parsed, value); + }; + + uint32_t base = 73; // 1001011b + for (int varint_length = 1; varint_length <= 5; ++varint_length) { + uint32_t values[] = { + base - 73, base - 72, base, base + 126 - 73, base + 126 - 72, + }; + for (uint32_t value : values) { + test_value(value, varint_length); + } + base = (base << 7) + 73; + } + + test_value(std::numeric_limits<uint32_t>::max(), 5); +} + +TEST(ParseVarintTest, Varint64) { + auto test_value = [](uint64_t value, int varint_length) { + uint8_t buffer[10]; + uint8_t* p = io::CodedOutputStream::WriteVarint64ToArray(value, buffer); + ASSERT_EQ(p - buffer, varint_length) << "Value = " << value; + + const char* cbuffer = reinterpret_cast<const char*>(buffer); + uint64_t parsed = ~value; + const char* r = internal::VarintParse(cbuffer, &parsed); + ASSERT_EQ(r - cbuffer, varint_length) << "Value = " << value; + ASSERT_EQ(parsed, value); + }; + + uint64_t base = 73; // 1001011b + for (int varint_length = 1; varint_length <= 10; ++varint_length) { + uint64_t values[] = { + base - 73, base - 72, base, base + 126 - 73, base + 126 - 72, + }; + for (uint64_t value : values) { + test_value(value, varint_length); + } + base = (base << 7) + 73; + } + + test_value(std::numeric_limits<uint64_t>::max(), 10); +} + TEST(Lite, AllLite1) { std::string data;
diff --git a/src/google/protobuf/map_field_test.cc b/src/google/protobuf/map_field_test.cc index 846f47c..1659c95 100644 --- a/src/google/protobuf/map_field_test.cc +++ b/src/google/protobuf/map_field_test.cc
@@ -34,8 +34,6 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/arena_test_util.h> -#include <google/protobuf/map_test_util.h> #include <google/protobuf/map_unittest.pb.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/arena.h> @@ -44,6 +42,8 @@ #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <gtest/gtest.h> +#include <google/protobuf/arena_test_util.h> +#include <google/protobuf/map_test_util.h> // Must be included last. #include <google/protobuf/port_def.inc>
diff --git a/src/google/protobuf/map_lite_test_util.cc b/src/google/protobuf/map_lite_test_util.cc index b65b4d6..121f267 100644 --- a/src/google/protobuf/map_lite_test_util.cc +++ b/src/google/protobuf/map_lite_test_util.cc
@@ -29,6 +29,7 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <google/protobuf/map_lite_test_util.h> + #include <google/protobuf/map_lite_unittest.pb.h> #include <google/protobuf/map_test_util_impl.h>
diff --git a/src/google/protobuf/map_test.inc b/src/google/protobuf/map_test.inc index 1f13106..2199c92 100644 --- a/src/google/protobuf/map_test.inc +++ b/src/google/protobuf/map_test.inc
@@ -49,29 +49,29 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/testing/file.h> -#include <google/protobuf/arena_test_util.h> -#include <google/protobuf/test_util2.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/io/tokenizer.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/descriptor_database.h> -#include <google/protobuf/dynamic_message.h> -#include <google/protobuf/map.h> -#include <google/protobuf/map_field_inl.h> -#include <google/protobuf/message.h> -#include <google/protobuf/reflection.h> -#include <google/protobuf/reflection_ops.h> -#include <google/protobuf/text_format.h> -#include <google/protobuf/wire_format.h> -#include <google/protobuf/util/message_differencer.h> -#include <google/protobuf/util/time_util.h> #include <gmock/gmock.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/casts.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/arena_test_util.h> +#include <google/protobuf/descriptor.h> +#include <google/protobuf/descriptor_database.h> +#include <google/protobuf/dynamic_message.h> +#include <google/protobuf/io/coded_stream.h> +#include <google/protobuf/io/tokenizer.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/map.h> +#include <google/protobuf/map_field_inl.h> +#include <google/protobuf/message.h> +#include <google/protobuf/reflection.h> +#include <google/protobuf/reflection_ops.h> +#include <google/protobuf/test_util2.h> +#include <google/protobuf/text_format.h> +#include <google/protobuf/util/message_differencer.h> +#include <google/protobuf/util/time_util.h> +#include <google/protobuf/wire_format.h> // Must be included last. @@ -3625,13 +3625,17 @@ &expected_text, true)); CleanStringLineEndings(&expected_text, false); - EXPECT_EQ(message.DebugString(), expected_text); + TextFormat::Printer printer; + std::string actual_text; + printer.PrintToString(message, &actual_text); + EXPECT_EQ(actual_text, expected_text); // Test again on the reverse order. UNITTEST::TestMap message2; tester.SetMapFieldsViaReflection(&message2); tester.SwapMapsViaReflection(&message2); - EXPECT_EQ(message2.DebugString(), expected_text); + printer.PrintToString(message2, &actual_text); + EXPECT_EQ(actual_text, expected_text); } TEST(TextFormatMapTest, ParseCorruptedString) {
diff --git a/src/google/protobuf/map_test_util.inc b/src/google/protobuf/map_test_util.inc index 600fdc3..5b12c76 100644 --- a/src/google/protobuf/map_test_util.inc +++ b/src/google/protobuf/map_test_util.inc
@@ -28,8 +28,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include <google/protobuf/map_test_util_impl.h> #include <google/protobuf/descriptor.h> +#include <google/protobuf/map_test_util_impl.h> #include <google/protobuf/message.h> namespace google {
diff --git a/src/google/protobuf/message.cc b/src/google/protobuf/message.cc index cff2165..632e66d 100644 --- a/src/google/protobuf/message.cc +++ b/src/google/protobuf/message.cc
@@ -118,20 +118,23 @@ copy_to_from(this, from); } -void Message::CopyWithSizeCheck(Message* to, const Message& from) { +void Message::CopyWithSourceCheck(Message* to, const Message& from) { #ifndef NDEBUG - size_t from_size = from.ByteSizeLong(); + FailIfCopyFromDescendant(to, from); #endif to->Clear(); -#ifndef NDEBUG - GOOGLE_CHECK_EQ(from_size, from.ByteSizeLong()) - << "Source of CopyFrom changed when clearing target. Either " - "source is a nested message in target (not allowed), or " - "another thread is modifying the source."; -#endif to->GetClassData()->merge_to_from(to, from); } +void Message::FailIfCopyFromDescendant(Message* to, const Message& from) { + auto* arena = to->GetArenaForAllocation(); + bool same_message_owned_arena = to->GetOwningArena() == nullptr && + arena != nullptr && + arena == from.GetOwningArena(); + GOOGLE_CHECK(!same_message_owned_arena && !internal::IsDescendant(to, from)) + << "Source of CopyFrom cannot be a descendant of the target."; +} + std::string Message::GetTypeName() const { return GetDescriptor()->full_name(); }
diff --git a/src/google/protobuf/message.h b/src/google/protobuf/message.h index 645ebd9..f58b500 100644 --- a/src/google/protobuf/message.h +++ b/src/google/protobuf/message.h
@@ -219,6 +219,9 @@ } bool CreateUnknownEnumValues(const FieldDescriptor* field); + +// Returns true if "message" is a descendant of "root". +PROTOBUF_EXPORT bool IsDescendant(Message* root, const Message& message); } // namespace internal // Abstract interface for protocol messages. @@ -252,7 +255,7 @@ // Make this message into a copy of the given message. The given message // must have the same descriptor, but need not necessarily be the same class. // By default this is just implemented as "Clear(); MergeFrom(from);". - virtual void CopyFrom(const Message& from); + void CopyFrom(const Message& from); // Merge the fields from the given message into this message. Singular // fields will be overwritten, if specified in from, except for embedded @@ -302,8 +305,11 @@ // Debugging & Testing---------------------------------------------- - // Generates a human readable form of this message, useful for debugging - // and other purposes. + // Generates a human-readable form of this message for debugging purposes. + // Note that the format and content of a debug string is not guaranteed, may + // change without notice, and should not be depended on. Code that does + // anything except display a string to assist in debugging should use + // TextFormat instead. std::string DebugString() const; // Like DebugString(), but with less whitespace. std::string ShortDebugString() const; @@ -375,11 +381,14 @@ // TODO(jorg): change to pure virtual virtual const ClassData* GetClassData() const { return nullptr; } - // CopyWithSizeCheck calls Clear() and then MergeFrom(), and in debug + // CopyWithSourceCheck calls Clear() and then MergeFrom(), and in debug // builds, checks that calling Clear() on the destination message doesn't - // alter the size of the source. It assumes the messages are known to be - // of the same type, and thus uses GetClassData(). - static void CopyWithSizeCheck(Message* to, const Message& from); + // alter the source. It assumes the messages are known to be of the same + // type, and thus uses GetClassData(). + static void CopyWithSourceCheck(Message* to, const Message& from); + + // Fail if "from" is a descendant of "to" as such copy is not allowed. + static void FailIfCopyFromDescendant(Message* to, const Message& from); inline explicit Message(Arena* arena, bool is_message_owned = false) : MessageLite(arena, is_message_owned) {} @@ -1021,6 +1030,7 @@ bool IsEagerlyVerifiedLazyField(const FieldDescriptor* field) const; friend class FastReflectionMessageMutator; + friend bool internal::IsDescendant(Message* root, const Message& message); const Descriptor* const descriptor_; const internal::ReflectionSchema schema_;
diff --git a/src/google/protobuf/message_lite.h b/src/google/protobuf/message_lite.h index 1c22f89..950ae1a 100644 --- a/src/google/protobuf/message_lite.h +++ b/src/google/protobuf/message_lite.h
@@ -187,10 +187,9 @@ Arena* GetArena() const { return _internal_metadata_.user_arena(); } // Clear all fields of the message and set them to their default values. - // Clear() avoids freeing memory, assuming that any memory allocated - // to hold parts of the message will be needed again to hold the next - // message. If you actually want to free the memory used by a Message, - // you must delete it. + // Clear() assumes that any memory allocated to hold parts of the message + // will likely be needed again, so the memory used may not be freed. + // To ensure that all memory used by a Message is freed, you must delete it. virtual void Clear() = 0; // Quickly check if all required fields have values set. @@ -440,6 +439,10 @@ // messages, etc), or owning incoming objects (e.g., set allocated). Arena* GetArenaForAllocation() const { return _internal_metadata_.arena(); } + // Returns true if this message is enabled for message-owned arena (MOA) + // trials. No lite messages are eligible for MOA. + static bool InMoaTrial() { return false; } + internal::InternalMetadata _internal_metadata_; public:
diff --git a/src/google/protobuf/message_unittest.inc b/src/google/protobuf/message_unittest.inc index 10c4eee..d2ef2d9 100644 --- a/src/google/protobuf/message_unittest.inc +++ b/src/google/protobuf/message_unittest.inc
@@ -51,20 +51,20 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/test_util2.h> -#include <google/protobuf/io/coded_stream.h> -#include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/descriptor.pb.h> -#include <google/protobuf/arena.h> -#include <google/protobuf/descriptor.h> -#include <google/protobuf/generated_message_reflection.h> #include <gmock/gmock.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/arena.h> +#include <google/protobuf/descriptor.h> #include <google/protobuf/io/io_win32.h> +#include <google/protobuf/generated_message_reflection.h> +#include <google/protobuf/io/coded_stream.h> +#include <google/protobuf/io/zero_copy_stream.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> +#include <google/protobuf/test_util2.h> namespace google { @@ -278,10 +278,8 @@ payload->mutable_optional_message()->set_dummy4(200); ASSERT_TRUE(p.ParsePartialFromString(o.SerializePartialAsString())); - GOOGLE_LOG(ERROR) << "seongkim: copy 1"; q.mutable_child()->set_dummy(500); q = p; - GOOGLE_LOG(ERROR) << "seongkim: copy 1 done"; q.ParsePartialFromString(q.SerializePartialAsString()); EXPECT_TRUE(TestUtil::EqualsToSerialized(q, o.SerializePartialAsString())); EXPECT_TRUE(TestUtil::EqualsToSerialized(q, p.SerializePartialAsString()));
diff --git a/src/google/protobuf/metadata_lite.h b/src/google/protobuf/metadata_lite.h index d6cf87f..11faba6 100644 --- a/src/google/protobuf/metadata_lite.h +++ b/src/google/protobuf/metadata_lite.h
@@ -60,13 +60,17 @@ // It uses bit 0 == 0 to indicate an arena pointer and bit 0 == 1 to indicate a // UFS+Arena-container pointer. Besides it uses bit 1 == 0 to indicate arena // allocation and bit 1 == 1 to indicate heap allocation. -class InternalMetadata { +class PROTOBUF_EXPORT InternalMetadata { public: constexpr InternalMetadata() : ptr_(0) {} - explicit InternalMetadata(Arena* arena, bool is_message_owned = false) - : ptr_(is_message_owned - ? reinterpret_cast<intptr_t>(arena) | kMessageOwnedArenaTagMask - : reinterpret_cast<intptr_t>(arena)) { + explicit InternalMetadata(Arena* arena, bool is_message_owned = false) { + SetArena(arena, is_message_owned); + } + + void SetArena(Arena* arena, bool is_message_owned) { + ptr_ = is_message_owned + ? reinterpret_cast<intptr_t>(arena) | kMessageOwnedArenaTagMask + : reinterpret_cast<intptr_t>(arena); GOOGLE_DCHECK(!is_message_owned || arena != nullptr); }
diff --git a/src/google/protobuf/parse_context.cc b/src/google/protobuf/parse_context.cc index edc8c5f..59852fd 100644 --- a/src/google/protobuf/parse_context.cc +++ b/src/google/protobuf/parse_context.cc
@@ -33,6 +33,7 @@ #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/arenastring.h> +#include <google/protobuf/endian.h> #include <google/protobuf/message_lite.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/stubs/strutil.h> @@ -234,19 +235,6 @@ } -template <int> -void byteswap(void* p); -template <> -void byteswap<1>(void* /*p*/) {} -template <> -void byteswap<4>(void* p) { - *static_cast<uint32_t*>(p) = bswap_32(*static_cast<uint32_t*>(p)); -} -template <> -void byteswap<8>(void* p) { - *static_cast<uint64_t*>(p) = bswap_64(*static_cast<uint64_t*>(p)); -} - const char* EpsCopyInputStream::InitFrom(io::ZeroCopyInputStream* zcis) { zcis_ = zcis; const void* data;
diff --git a/src/google/protobuf/parse_context.h b/src/google/protobuf/parse_context.h index c00048d..7c021c4 100644 --- a/src/google/protobuf/parse_context.h +++ b/src/google/protobuf/parse_context.h
@@ -34,6 +34,7 @@ #include <cstdint> #include <cstring> #include <string> +#include <type_traits> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream.h> @@ -41,6 +42,7 @@ #include <google/protobuf/port.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/arenastring.h> +#include <google/protobuf/endian.h> #include <google/protobuf/implicit_weak_message.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata_lite.h> @@ -374,6 +376,7 @@ using LazyEagerVerifyFnType = const char* (*)(const char* ptr, ParseContext* ctx); +using LazyEagerVerifyFnRef = std::remove_pointer<LazyEagerVerifyFnType>::type&; // ParseContext holds all data that is global to the entire parse. Most // importantly it contains the input stream, but also recursion depth and also @@ -484,10 +487,7 @@ static uint16_t Load(const void* p) { uint16_t tmp; std::memcpy(&tmp, p, 2); -#ifndef PROTOBUF_LITTLE_ENDIAN - tmp = bswap_16(tmp); -#endif - return tmp; + return little_endian::ToHost(tmp); } }; @@ -496,10 +496,7 @@ static uint32_t Load(const void* p) { uint32_t tmp; std::memcpy(&tmp, p, 4); -#ifndef PROTOBUF_LITTLE_ENDIAN - tmp = bswap_32(tmp); -#endif - return tmp; + return little_endian::ToHost(tmp); } }; @@ -508,10 +505,7 @@ static uint64_t Load(const void* p) { uint64_t tmp; std::memcpy(&tmp, p, 8); -#ifndef PROTOBUF_LITTLE_ENDIAN - tmp = bswap_64(tmp); -#endif - return tmp; + return little_endian::ToHost(tmp); } }; @@ -582,6 +576,82 @@ return tmp.first; } +// As above, but optimized to consume very few registers while still being fast, +// ReadTagInlined is useful for callers that don't mind the extra code but would +// like to avoid an extern function call causing spills into the stack. +// +// Two support routines for ReadTagInlined come first... +template <class T> +PROTOBUF_NODISCARD PROTOBUF_ALWAYS_INLINE constexpr T RotateLeft( + T x, int s) noexcept { + return static_cast<T>(x << (s & (std::numeric_limits<T>::digits - 1))) | + static_cast<T>(x >> ((-s) & (std::numeric_limits<T>::digits - 1))); +} + +PROTOBUF_NODISCARD inline PROTOBUF_ALWAYS_INLINE uint64_t +RotRight7AndReplaceLowByte(uint64_t res, const char& byte) { +#if defined(__x86_64__) && defined(__GNUC__) + // This will only use one register for `res`. + // `byte` comes as a reference to allow the compiler to generate code like: + // + // rorq $7, %rcx + // movb 1(%rax), %cl + // + // which avoids loading the incoming bytes into a separate register first. + asm("ror $7,%0\n\t" + "movb %1,%b0" + : "+r"(res) + : "m"(byte)); +#else + res = RotateLeft(res, -7); + res = res & ~0xFF; + res |= 0xFF & byte; +#endif + return res; +}; + +inline PROTOBUF_ALWAYS_INLINE +const char* ReadTagInlined(const char* ptr, uint32_t* out) { + uint64_t res = 0xFF & ptr[0]; + if (PROTOBUF_PREDICT_FALSE(res >= 128)) { + res = RotRight7AndReplaceLowByte(res, ptr[1]); + if (PROTOBUF_PREDICT_FALSE(res & 0x80)) { + res = RotRight7AndReplaceLowByte(res, ptr[2]); + if (PROTOBUF_PREDICT_FALSE(res & 0x80)) { + res = RotRight7AndReplaceLowByte(res, ptr[3]); + if (PROTOBUF_PREDICT_FALSE(res & 0x80)) { + // Note: this wouldn't work if res were 32-bit, + // because then replacing the low byte would overwrite + // the bottom 4 bits of the result. + res = RotRight7AndReplaceLowByte(res, ptr[4]); + if (PROTOBUF_PREDICT_FALSE(res & 0x80)) { + // The proto format does not permit longer than 5-byte encodings for + // tags. + *out = 0; + return nullptr; + } + *out = RotateLeft(res, 28); +#if defined(__GNUC__) + // Note: this asm statement prevents the compiler from + // trying to share the "return ptr + constant" among all + // branches. + asm("" : "+r"(ptr)); +#endif + return ptr + 5; + } + *out = RotateLeft(res, 21); + return ptr + 4; + } + *out = RotateLeft(res, 14); + return ptr + 3; + } + *out = RotateLeft(res, 7); + return ptr + 2; + } + *out = res; + return ptr + 1; +} + // Decode 2 consecutive bytes of a varint and returns the value, shifted left // by 1. It simultaneous updates *ptr to *ptr + 1 or *ptr + 2 depending if the // first byte's continuation bit is set.
diff --git a/src/google/protobuf/port_def.inc b/src/google/protobuf/port_def.inc index 1e360cc..14185af 100644 --- a/src/google/protobuf/port_def.inc +++ b/src/google/protobuf/port_def.inc
@@ -118,6 +118,27 @@ #define PROTOBUF_has_builtin_DEFINED_ #endif +// Portable PROTOBUF_BUILTIN_BSWAPxx definitions +// Code must check for availability, e.g.: `defined(PROTOBUF_BUILTIN_BSWAP32)` +#ifdef PROTOBUF_BUILTIN_BSWAP16 +#error PROTOBUF_BUILTIN_BSWAP16 was previously defined +#endif +#ifdef PROTOBUF_BUILTIN_BSWAP32 +#error PROTOBUF_BUILTIN_BSWAP32 was previously defined +#endif +#ifdef PROTOBUF_BUILTIN_BSWAP64 +#error PROTOBUF_BUILTIN_BSWAP64 was previously defined +#endif +#if defined(__GNUC__) || __has_builtin(__builtin_bswap16) +#define PROTOBUF_BUILTIN_BSWAP16(x) __builtin_bswap16(x) +#endif +#if defined(__GNUC__) || __has_builtin(__builtin_bswap32) +#define PROTOBUF_BUILTIN_BSWAP32(x) __builtin_bswap32(x) +#endif +#if defined(__GNUC__) || __has_builtin(__builtin_bswap64) +#define PROTOBUF_BUILTIN_BSWAP64(x) __builtin_bswap64(x) +#endif + // Portable check for GCC minimum version: // https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html #if defined(__GNUC__) && defined(__GNUC_MINOR__) \ @@ -172,7 +193,7 @@ #ifdef PROTOBUF_VERSION_SUFFIX #error PROTOBUF_VERSION_SUFFIX was previously defined #endif -#define PROTOBUF_VERSION_SUFFIX "" +#define PROTOBUF_VERSION_SUFFIX "-rc1" #if defined(PROTOBUF_NAMESPACE) || defined(PROTOBUF_NAMESPACE_ID) #error PROTOBUF_NAMESPACE or PROTOBUF_NAMESPACE_ID was previously defined @@ -501,6 +522,10 @@ #error PROTOBUF_FORCE_COPY_IN_MOVE was previously defined #endif +#ifdef PROTOBUF_FORCE_RESET_IN_CLEAR +#error PROTOBUF_FORCE_RESET_IN_CLEAR was previously defined +#endif + // Force copy the default string to a string field so that non-optimized builds // have harder-to-rely-on address stability. #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING @@ -582,6 +607,22 @@ #define PROTOBUF_THREAD_LOCAL __thread #endif +// TODO(b/228173843): cleanup PROTOBUF_LITTLE_ENDIAN in various 3p forks. +#if (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +#define PROTOBUF_LITTLE_ENDIAN 1 +#ifdef PROTOBUF_BIG_ENDIAN +#error Conflicting PROTOBUF_BIG_ENDIAN was previously defined +#endif +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define PROTOBUF_BIG_ENDIAN 1 +#elif defined(_WIN32) || defined(__x86_64__) || defined(__aarch64__) +#define PROTOBUF_LITTLE_ENDIAN 1 +#else +#error "endian detection failed for current compiler" +#endif + // For enabling message owned arena, one major blocker is semantic change from // moving to copying when there is ownership transfer (e.g., move ctor, swap, // set allocated, release). This change not only causes performance regression @@ -771,8 +812,12 @@ #undef ERROR_INSTALL_FAILED #pragma push_macro("ERROR_NOT_FOUND") #undef ERROR_NOT_FOUND +#pragma push_macro("GetClassName") +#undef GetClassName #pragma push_macro("GetMessage") #undef GetMessage +#pragma push_macro("GetObject") +#undef GetObject #pragma push_macro("IGNORE") #undef IGNORE #pragma push_macro("IN")
diff --git a/src/google/protobuf/port_undef.inc b/src/google/protobuf/port_undef.inc index 58136a4..6cb8eac 100644 --- a/src/google/protobuf/port_undef.inc +++ b/src/google/protobuf/port_undef.inc
@@ -34,6 +34,10 @@ #ifndef PROTOBUF_NAMESPACE #error "port_undef.inc must be included after port_def.inc" #endif + +#undef PROTOBUF_BUILTIN_BSWAP16 +#undef PROTOBUF_BUILTIN_BSWAP32 +#undef PROTOBUF_BUILTIN_BSWAP64 #undef PROTOBUF_GNUC_MIN #undef PROTOBUF_MSC_VER_MIN #undef PROTOBUF_CPLUSPLUS_MIN @@ -67,6 +71,7 @@ #undef PROTOBUF_FORCE_COPY_IN_RELEASE #undef PROTOBUF_FORCE_COPY_IN_SWAP #undef PROTOBUF_FORCE_COPY_IN_MOVE +#undef PROTOBUF_FORCE_RESET_IN_CLEAR #undef PROTOBUF_FORCE_COPY_DEFAULT_STRING #undef PROTOBUF_NAMESPACE_OPEN #undef PROTOBUF_NAMESPACE_CLOSE @@ -78,6 +83,8 @@ #undef PROTOBUF_FINAL #undef PROTOBUF_FUTURE_FINAL #undef PROTOBUF_THREAD_LOCAL +#undef PROTOBUF_LITTLE_ENDIAN +#undef PROTOBUF_BIG_ENDIAN #undef PROTOBUF_MESSAGE_OWNED_ARENA_EXPERIMENT #undef PROTOBUF_CONSTINIT #undef PROTOBUF_CONSTEXPR @@ -111,7 +118,9 @@ #pragma pop_macro("ERROR_BUSY") #pragma pop_macro("ERROR_INSTALL_FAILED") #pragma pop_macro("ERROR_NOT_FOUND") +#pragma pop_macro("GetClassName") #pragma pop_macro("GetMessage") +#pragma pop_macro("GetObject") #pragma pop_macro("IGNORE") #pragma pop_macro("IN") #pragma pop_macro("INPUT_KEYBOARD")
diff --git a/src/google/protobuf/proto3_arena_unittest.cc b/src/google/protobuf/proto3_arena_unittest.cc index 5588f91..cfbe198 100644 --- a/src/google/protobuf/proto3_arena_unittest.cc +++ b/src/google/protobuf/proto3_arena_unittest.cc
@@ -32,7 +32,6 @@ #include <string> #include <vector> -#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> @@ -41,6 +40,7 @@ #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/test_util.h> // Must be included last. #include <google/protobuf/port_def.inc> @@ -75,6 +75,7 @@ m->set_optional_nested_enum(proto3_arena_unittest::TestAllTypes::BAZ); m->set_optional_foreign_enum(proto3_arena_unittest::FOREIGN_BAZ); m->mutable_optional_lazy_message()->set_bb(45); + m->mutable_optional_unverified_lazy_message()->set_bb(46); m->add_repeated_int32(100); m->add_repeated_string("asdf"); m->add_repeated_bytes("jkl;"); @@ -101,6 +102,8 @@ EXPECT_EQ(proto3_arena_unittest::FOREIGN_BAZ, m.optional_foreign_enum()); EXPECT_EQ(true, m.has_optional_lazy_message()); EXPECT_EQ(45, m.optional_lazy_message().bb()); + EXPECT_EQ(true, m.has_optional_unverified_lazy_message()); + EXPECT_EQ(46, m.optional_unverified_lazy_message().bb()); EXPECT_EQ(1, m.repeated_int32_size()); EXPECT_EQ(100, m.repeated_int32(0));
diff --git a/src/google/protobuf/proto3_lite_unittest.inc b/src/google/protobuf/proto3_lite_unittest.inc index 85f428a..5878163 100644 --- a/src/google/protobuf/proto3_lite_unittest.inc +++ b/src/google/protobuf/proto3_lite_unittest.inc
@@ -53,6 +53,7 @@ m->set_optional_foreign_enum( UNITTEST::FOREIGN_BAZ); m->mutable_optional_lazy_message()->set_bb(45); + m->mutable_optional_unverified_lazy_message()->set_bb(46); m->add_repeated_int32(100); m->add_repeated_string("asdf"); m->add_repeated_bytes("jkl;"); @@ -81,6 +82,8 @@ m.optional_foreign_enum()); EXPECT_EQ(true, m.has_optional_lazy_message()); EXPECT_EQ(45, m.optional_lazy_message().bb()); + EXPECT_EQ(true, m.has_optional_unverified_lazy_message()); + EXPECT_EQ(46, m.optional_unverified_lazy_message().bb()); EXPECT_EQ(1, m.repeated_int32_size()); EXPECT_EQ(100, m.repeated_int32(0));
diff --git a/src/google/protobuf/reflection_ops.cc b/src/google/protobuf/reflection_ops.cc index b9f8e4e..3a1972e 100644 --- a/src/google/protobuf/reflection_ops.cc +++ b/src/google/protobuf/reflection_ops.cc
@@ -170,8 +170,10 @@ } } - to_reflection->MutableUnknownFields(to)->MergeFrom( - from_reflection->GetUnknownFields(from)); + if (!from_reflection->GetUnknownFields(from).empty()) { + to_reflection->MutableUnknownFields(to)->MergeFrom( + from_reflection->GetUnknownFields(from)); + } } void ReflectionOps::Clear(Message* message) {
diff --git a/src/google/protobuf/reflection_ops_unittest.cc b/src/google/protobuf/reflection_ops_unittest.cc index 0ae6974..513ce47 100644 --- a/src/google/protobuf/reflection_ops_unittest.cc +++ b/src/google/protobuf/reflection_ops_unittest.cc
@@ -33,14 +33,14 @@ // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/reflection_ops.h> -#include <google/protobuf/test_util.h> -#include <google/protobuf/unittest.pb.h> -#include <google/protobuf/descriptor.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> +#include <google/protobuf/unittest.pb.h> +#include <google/protobuf/descriptor.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> +#include <google/protobuf/test_util.h> #include <google/protobuf/stubs/strutil.h>
diff --git a/src/google/protobuf/reflection_tester.cc b/src/google/protobuf/reflection_tester.cc index 77601a7..4c6db03 100644 --- a/src/google/protobuf/reflection_tester.cc +++ b/src/google/protobuf/reflection_tester.cc
@@ -30,9 +30,9 @@ #include <google/protobuf/reflection_tester.h> +#include <gtest/gtest.h> #include <google/protobuf/map_field.h> #include <google/protobuf/message.h> -#include <gtest/gtest.h> // Must include last. #include <google/protobuf/port_def.inc>
diff --git a/src/google/protobuf/repeated_field_reflection_unittest.cc b/src/google/protobuf/repeated_field_reflection_unittest.cc index e472fa4..25e8200 100644 --- a/src/google/protobuf/repeated_field_reflection_unittest.cc +++ b/src/google/protobuf/repeated_field_reflection_unittest.cc
@@ -34,11 +34,11 @@ // This test proto2 methods on a proto2 layout. #include <google/protobuf/stubs/casts.h> -#include <google/protobuf/test_util.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/dynamic_message.h> #include <google/protobuf/reflection.h> #include <gtest/gtest.h> +#include <google/protobuf/test_util.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/repeated_field_unittest.cc b/src/google/protobuf/repeated_field_unittest.cc index ddfafb5..d8a82bf 100644 --- a/src/google/protobuf/repeated_field_unittest.cc +++ b/src/google/protobuf/repeated_field_unittest.cc
@@ -1311,12 +1311,12 @@ } field.RemoveLast(); index = field.size(); - std::string* qux = new std::string("qux"); - field.AddAllocated(qux); + std::string* moo = new std::string("moo"); + field.AddAllocated(moo); EXPECT_EQ(index + 1, field.size()); // We should have discarded the cleared object. EXPECT_EQ(0, field.ClearedCount()); - EXPECT_EQ(qux, &field.Get(index)); + EXPECT_EQ(moo, &field.Get(index)); } TEST(RepeatedPtrField, AddAllocatedDifferentArena) { @@ -1906,8 +1906,8 @@ TEST_F(RepeatedPtrFieldIteratorTest, Mutation) { RepeatedPtrField<std::string>::iterator iter = proto_array_.begin(); - *iter = "qux"; - EXPECT_EQ("qux", proto_array_.Get(0)); + *iter = "moo"; + EXPECT_EQ("moo", proto_array_.Get(0)); } // ------------------------------------------------------------------- @@ -2107,8 +2107,8 @@ TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrMutation) { RepeatedPtrField<std::string>::pointer_iterator iter = proto_array_.pointer_begin(); - **iter = "qux"; - EXPECT_EQ("qux", proto_array_.Get(0)); + **iter = "moo"; + EXPECT_EQ("moo", proto_array_.Get(0)); EXPECT_EQ("bar", proto_array_.Get(1)); EXPECT_EQ("baz", proto_array_.Get(2));
diff --git a/src/google/protobuf/repeated_ptr_field.h b/src/google/protobuf/repeated_ptr_field.h index e81b2c7..aa278e6 100644 --- a/src/google/protobuf/repeated_ptr_field.h +++ b/src/google/protobuf/repeated_ptr_field.h
@@ -749,7 +749,7 @@ static inline GenericType* New(Arena* arena, GenericType&& value) { return Arena::Create<GenericType>(arena, std::move(value)); } - static inline GenericType* NewFromPrototype(const GenericType* prototype, + static inline GenericType* NewFromPrototype(const GenericType* /*prototype*/, Arena* arena = nullptr) { return New(arena); } @@ -872,8 +872,28 @@ const Element& Get(int index) const; Element* Mutable(int index); + + // Unlike std::vector, adding an element to a RepeatedPtrField doesn't always + // make a new element; it might re-use an element left over from when the + // field was Clear()'d or reize()'d smaller. For this reason, Add() is the + // fastest API for adding a new element. Element* Add(); + + // `Add(std::move(value));` is equivalent to `*Add() = std::move(value);` + // It will either move-construct to the end of this field, or swap value + // with the new-or-recycled element at the end of this field. Note that + // this operation is very slow if this RepeatedPtrField is not on the + // same Arena, if any, as `value`. void Add(Element&& value); + + // Copying to the end of this RepeatedPtrField is slowest of all; it can't + // reliably copy-construct to the last element of this RepeatedPtrField, for + // example (unlike std::vector). + // We currently block this API. The right way to add to the end is to call + // Add() and modify the element it points to. + // If you must add an existing value, call `*Add() = value;` + void Add(const Element& value) = delete; + // Append elements in the range [begin, end) after reserving // the appropriate number of elements. template <typename Iter>
diff --git a/src/google/protobuf/source_context.pb.cc b/src/google/protobuf/source_context.pb.cc index 2f865f6..eb7acfa 100644 --- a/src/google/protobuf/source_context.pb.cc +++ b/src/google/protobuf/source_context.pb.cc
@@ -22,8 +22,9 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR SourceContext::SourceContext( - ::_pbi::ConstantInitialized) - : file_name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.file_name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_._cached_size_)*/{}} {} struct SourceContextDefaultTypeInternal { PROTOBUF_CONSTEXPR SourceContextDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -45,7 +46,7 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceContext, file_name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::SourceContext, _impl_.file_name_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::SourceContext)}, @@ -89,28 +90,39 @@ SourceContext::SourceContext(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.SourceContext) } SourceContext::SourceContext(const SourceContext& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.file_name_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - file_name_.InitDefault(); + _impl_.file_name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - file_name_.Set("", GetArenaForAllocation()); + _impl_.file_name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_file_name().empty()) { - file_name_.Set(from._internal_file_name(), + _impl_.file_name_.Set(from._internal_file_name(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:google.protobuf.SourceContext) } -inline void SourceContext::SharedCtor() { -file_name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - file_name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING +inline void SourceContext::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.file_name_){} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.file_name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.file_name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } SourceContext::~SourceContext() { @@ -124,11 +136,11 @@ inline void SourceContext::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - file_name_.Destroy(); + _impl_.file_name_.Destroy(); } void SourceContext::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void SourceContext::Clear() { @@ -137,7 +149,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - file_name_.ClearToEmpty(); + _impl_.file_name_.ClearToEmpty(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -219,11 +231,11 @@ this->_internal_file_name()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData SourceContext::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, SourceContext::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*SourceContext::GetClassData() const { return &_class_data_; } @@ -264,8 +276,8 @@ auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &file_name_, lhs_arena, - &other->file_name_, rhs_arena + &_impl_.file_name_, lhs_arena, + &other->_impl_.file_name_, rhs_arena ); }
diff --git a/src/google/protobuf/source_context.pb.h b/src/google/protobuf/source_context.pb.h index aa73870..275df17 100644 --- a/src/google/protobuf/source_context.pb.h +++ b/src/google/protobuf/source_context.pb.h
@@ -147,10 +147,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(SourceContext* other); @@ -198,8 +198,11 @@ 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_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr file_name_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fsource_5fcontext_2eproto; }; // =================================================================== @@ -215,7 +218,7 @@ // string file_name = 1; inline void SourceContext::clear_file_name() { - file_name_.ClearToEmpty(); + _impl_.file_name_.ClearToEmpty(); } inline const std::string& SourceContext::file_name() const { // @@protoc_insertion_point(field_get:google.protobuf.SourceContext.file_name) @@ -225,7 +228,7 @@ inline PROTOBUF_ALWAYS_INLINE void SourceContext::set_file_name(ArgT0&& arg0, ArgT... args) { - file_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.file_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.SourceContext.file_name) } inline std::string* SourceContext::mutable_file_name() { @@ -234,19 +237,19 @@ return _s; } inline const std::string& SourceContext::_internal_file_name() const { - return file_name_.Get(); + return _impl_.file_name_.Get(); } inline void SourceContext::_internal_set_file_name(const std::string& value) { - file_name_.Set(value, GetArenaForAllocation()); + _impl_.file_name_.Set(value, GetArenaForAllocation()); } inline std::string* SourceContext::_internal_mutable_file_name() { - return file_name_.Mutable(GetArenaForAllocation()); + return _impl_.file_name_.Mutable(GetArenaForAllocation()); } inline std::string* SourceContext::release_file_name() { // @@protoc_insertion_point(field_release:google.protobuf.SourceContext.file_name) - return file_name_.Release(); + return _impl_.file_name_.Release(); } inline void SourceContext::set_allocated_file_name(std::string* file_name) { if (file_name != nullptr) { @@ -254,10 +257,10 @@ } else { } - file_name_.SetAllocated(file_name, GetArenaForAllocation()); + _impl_.file_name_.SetAllocated(file_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (file_name_.IsDefault()) { - file_name_.Set("", GetArenaForAllocation()); + if (_impl_.file_name_.IsDefault()) { + _impl_.file_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.SourceContext.file_name)
diff --git a/src/google/protobuf/struct.pb.cc b/src/google/protobuf/struct.pb.cc index c15fb84..afd1f8f 100644 --- a/src/google/protobuf/struct.pb.cc +++ b/src/google/protobuf/struct.pb.cc
@@ -22,7 +22,7 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Struct_FieldsEntry_DoNotUse::Struct_FieldsEntry_DoNotUse( - ::_pbi::ConstantInitialized){} + ::_pbi::ConstantInitialized) {} struct Struct_FieldsEntry_DoNotUseDefaultTypeInternal { PROTOBUF_CONSTEXPR Struct_FieldsEntry_DoNotUseDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -33,8 +33,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Struct_FieldsEntry_DoNotUseDefaultTypeInternal _Struct_FieldsEntry_DoNotUse_default_instance_; PROTOBUF_CONSTEXPR Struct::Struct( - ::_pbi::ConstantInitialized) - : fields_(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.fields_)*/{::_pbi::ConstantInitialized()} + , /*decltype(_impl_._cached_size_)*/{}} {} struct StructDefaultTypeInternal { PROTOBUF_CONSTEXPR StructDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -45,8 +46,10 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 StructDefaultTypeInternal _Struct_default_instance_; PROTOBUF_CONSTEXPR Value::Value( - ::_pbi::ConstantInitialized) - : _oneof_case_{}{} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.kind_)*/{} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_._oneof_case_)*/{}} {} struct ValueDefaultTypeInternal { PROTOBUF_CONSTEXPR ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -57,8 +60,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 ValueDefaultTypeInternal _Value_default_instance_; PROTOBUF_CONSTEXPR ListValue::ListValue( - ::_pbi::ConstantInitialized) - : values_(){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.values_)*/{} + , /*decltype(_impl_._cached_size_)*/{}} {} struct ListValueDefaultTypeInternal { PROTOBUF_CONSTEXPR ListValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -90,11 +94,11 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct, fields_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Struct, _impl_.fields_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _internal_metadata_), ~0u, // no _extensions_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _oneof_case_[0]), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _impl_._oneof_case_[0]), ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ ::_pbi::kInvalidFieldOffsetTag, @@ -103,14 +107,14 @@ ::_pbi::kInvalidFieldOffsetTag, ::_pbi::kInvalidFieldOffsetTag, ::_pbi::kInvalidFieldOffsetTag, - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, kind_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Value, _impl_.kind_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ListValue, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ListValue, values_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::ListValue, _impl_.values_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 8, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Struct_FieldsEntry_DoNotUse)}, @@ -196,9 +200,8 @@ Struct::Struct(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - fields_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); if (arena != nullptr && !is_message_owned) { arena->OwnCustomDestructor(this, &Struct::ArenaDtor); } @@ -206,12 +209,23 @@ } Struct::Struct(const Struct& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + /*decltype(_impl_.fields_)*/{} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - fields_.MergeFrom(from.fields_); + _impl_.fields_.MergeFrom(from._impl_.fields_); // @@protoc_insertion_point(copy_constructor:google.protobuf.Struct) } -inline void Struct::SharedCtor() { +inline void Struct::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + /*decltype(_impl_.fields_)*/{::_pbi::ArenaInitialized(), arena} + , /*decltype(_impl_._cached_size_)*/{} + }; } Struct::~Struct() { @@ -226,15 +240,16 @@ inline void Struct::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - fields_.Destruct(); + _impl_.fields_.Destruct(); + _impl_.fields_.~MapField(); } void Struct::ArenaDtor(void* object) { Struct* _this = reinterpret_cast< Struct* >(object); - _this->fields_.Destruct(); + _this->_impl_.fields_.Destruct(); } void Struct::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Struct::Clear() { @@ -243,7 +258,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - fields_.Clear(); + _impl_.fields_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -259,7 +274,7 @@ ptr -= 1; do { ptr += 1; - ptr = ctx->ParseMessage(&fields_, ptr); + ptr = ctx->ParseMessage(&_impl_.fields_, ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<10>(ptr)); @@ -346,11 +361,11 @@ total_size += Struct_FieldsEntry_DoNotUse::Funcs::ByteSizeLong(it->first, it->second); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Struct::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Struct::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Struct::GetClassData() const { return &_class_data_; } @@ -368,7 +383,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - fields_.MergeFrom(from.fields_); + _impl_.fields_.MergeFrom(from._impl_.fields_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -386,7 +401,7 @@ void Struct::InternalSwap(Struct* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - fields_.InternalSwap(&other->fields_); + _impl_.fields_.InternalSwap(&other->_impl_.fields_); } ::PROTOBUF_NAMESPACE_ID::Metadata Struct::GetMetadata() const { @@ -405,11 +420,11 @@ const ::PROTOBUF_NAMESPACE_ID::Struct& Value::_Internal::struct_value(const Value* msg) { - return *msg->kind_.struct_value_; + return *msg->_impl_.kind_.struct_value_; } const ::PROTOBUF_NAMESPACE_ID::ListValue& Value::_Internal::list_value(const Value* msg) { - return *msg->kind_.list_value_; + return *msg->_impl_.kind_.list_value_; } void Value::set_allocated_struct_value(::PROTOBUF_NAMESPACE_ID::Struct* struct_value) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); @@ -422,7 +437,7 @@ message_arena, struct_value, submessage_arena); } set_has_struct_value(); - kind_.struct_value_ = struct_value; + _impl_.kind_.struct_value_ = struct_value; } // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.struct_value) } @@ -437,18 +452,23 @@ message_arena, list_value, submessage_arena); } set_has_list_value(); - kind_.list_value_ = list_value; + _impl_.kind_.list_value_ = list_value; } // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.list_value) } Value::Value(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Value) } Value::Value(const Value& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.kind_){} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_._oneof_case_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); clear_has_kind(); switch (from.kind_case()) { @@ -483,8 +503,16 @@ // @@protoc_insertion_point(copy_constructor:google.protobuf.Value) } -inline void Value::SharedCtor() { -clear_has_kind(); +inline void Value::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.kind_){} + , /*decltype(_impl_._cached_size_)*/{} + , /*decltype(_impl_._oneof_case_)*/{} + }; + clear_has_kind(); } Value::~Value() { @@ -504,7 +532,7 @@ } void Value::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Value::clear_kind() { @@ -519,7 +547,7 @@ break; } case kStringValue: { - kind_.string_value_.Destroy(); + _impl_.kind_.string_value_.Destroy(); break; } case kBoolValue: { @@ -528,13 +556,13 @@ } case kStructValue: { if (GetArenaForAllocation() == nullptr) { - delete kind_.struct_value_; + delete _impl_.kind_.struct_value_; } break; } case kListValue: { if (GetArenaForAllocation() == nullptr) { - delete kind_.list_value_; + delete _impl_.kind_.list_value_; } break; } @@ -542,7 +570,7 @@ break; } } - _oneof_case_[0] = KIND_NOT_SET; + _impl_._oneof_case_[0] = KIND_NOT_SET; } @@ -729,25 +757,25 @@ case kStructValue: { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *kind_.struct_value_); + *_impl_.kind_.struct_value_); break; } // .google.protobuf.ListValue list_value = 6; case kListValue: { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *kind_.list_value_); + *_impl_.kind_.list_value_); break; } case KIND_NOT_SET: { break; } } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Value::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Value::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Value::GetClassData() const { return &_class_data_; } @@ -811,8 +839,8 @@ void Value::InternalSwap(Value* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(kind_, other->kind_); - swap(_oneof_case_[0], other->_oneof_case_[0]); + swap(_impl_.kind_, other->_impl_.kind_); + swap(_impl_._oneof_case_[0], other->_impl_._oneof_case_[0]); } ::PROTOBUF_NAMESPACE_ID::Metadata Value::GetMetadata() const { @@ -829,19 +857,28 @@ ListValue::ListValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - values_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.ListValue) } ListValue::ListValue(const ListValue& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - values_(from.values_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.values_){from._impl_.values_} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.protobuf.ListValue) } -inline void ListValue::SharedCtor() { +inline void ListValue::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.values_){arena} + , /*decltype(_impl_._cached_size_)*/{} + }; } ListValue::~ListValue() { @@ -855,10 +892,11 @@ inline void ListValue::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); + _impl_.values_.~RepeatedPtrField(); } void ListValue::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void ListValue::Clear() { @@ -867,7 +905,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - values_.Clear(); + _impl_.values_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -945,16 +983,16 @@ // repeated .google.protobuf.Value values = 1; total_size += 1UL * this->_internal_values_size(); - for (const auto& msg : this->values_) { + for (const auto& msg : this->_impl_.values_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData ListValue::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, ListValue::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*ListValue::GetClassData() const { return &_class_data_; } @@ -972,7 +1010,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - values_.MergeFrom(from.values_); + _impl_.values_.MergeFrom(from._impl_.values_); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } @@ -990,7 +1028,7 @@ void ListValue::InternalSwap(ListValue* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - values_.InternalSwap(&other->values_); + _impl_.values_.InternalSwap(&other->_impl_.values_); } ::PROTOBUF_NAMESPACE_ID::Metadata ListValue::GetMetadata() const {
diff --git a/src/google/protobuf/struct.pb.h b/src/google/protobuf/struct.pb.h index 87003ba..08d23e5 100644 --- a/src/google/protobuf/struct.pb.h +++ b/src/google/protobuf/struct.pb.h
@@ -213,10 +213,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Struct* other); @@ -270,12 +270,15 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::internal::MapField< - Struct_FieldsEntry_DoNotUse, - std::string, ::PROTOBUF_NAMESPACE_ID::Value, - ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, - ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> fields_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::MapField< + Struct_FieldsEntry_DoNotUse, + std::string, ::PROTOBUF_NAMESPACE_ID::Value, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_STRING, + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_MESSAGE> fields_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; }; // ------------------------------------------------------------------- @@ -381,10 +384,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Value* other); @@ -527,19 +530,22 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - union KindUnion { - constexpr KindUnion() : _constinit_{} {} - ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; - int null_value_; - double number_value_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; - bool bool_value_; - ::PROTOBUF_NAMESPACE_ID::Struct* struct_value_; - ::PROTOBUF_NAMESPACE_ID::ListValue* list_value_; - } kind_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; - uint32_t _oneof_case_[1]; + struct Impl_ { + union KindUnion { + constexpr KindUnion() : _constinit_{} {} + ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized _constinit_; + int null_value_; + double number_value_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr string_value_; + bool bool_value_; + ::PROTOBUF_NAMESPACE_ID::Struct* struct_value_; + ::PROTOBUF_NAMESPACE_ID::ListValue* list_value_; + } kind_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + uint32_t _oneof_case_[1]; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; }; // ------------------------------------------------------------------- @@ -635,10 +641,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(ListValue* other); @@ -690,8 +696,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value > values_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value > values_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fstruct_2eproto; }; // =================================================================== @@ -709,17 +718,17 @@ // map<string, .google.protobuf.Value> fields = 1; inline int Struct::_internal_fields_size() const { - return fields_.size(); + return _impl_.fields_.size(); } inline int Struct::fields_size() const { return _internal_fields_size(); } inline void Struct::clear_fields() { - fields_.Clear(); + _impl_.fields_.Clear(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >& Struct::_internal_fields() const { - return fields_.GetMap(); + return _impl_.fields_.GetMap(); } inline const ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >& Struct::fields() const { @@ -728,7 +737,7 @@ } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >* Struct::_internal_mutable_fields() { - return fields_.MutableMap(); + return _impl_.fields_.MutableMap(); } inline ::PROTOBUF_NAMESPACE_ID::Map< std::string, ::PROTOBUF_NAMESPACE_ID::Value >* Struct::mutable_fields() { @@ -748,17 +757,17 @@ return _internal_has_null_value(); } inline void Value::set_has_null_value() { - _oneof_case_[0] = kNullValue; + _impl_._oneof_case_[0] = kNullValue; } inline void Value::clear_null_value() { if (_internal_has_null_value()) { - kind_.null_value_ = 0; + _impl_.kind_.null_value_ = 0; clear_has_kind(); } } inline ::PROTOBUF_NAMESPACE_ID::NullValue Value::_internal_null_value() const { if (_internal_has_null_value()) { - return static_cast< ::PROTOBUF_NAMESPACE_ID::NullValue >(kind_.null_value_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::NullValue >(_impl_.kind_.null_value_); } return static_cast< ::PROTOBUF_NAMESPACE_ID::NullValue >(0); } @@ -771,7 +780,7 @@ clear_kind(); set_has_null_value(); } - kind_.null_value_ = value; + _impl_.kind_.null_value_ = value; } inline void Value::set_null_value(::PROTOBUF_NAMESPACE_ID::NullValue value) { _internal_set_null_value(value); @@ -786,17 +795,17 @@ return _internal_has_number_value(); } inline void Value::set_has_number_value() { - _oneof_case_[0] = kNumberValue; + _impl_._oneof_case_[0] = kNumberValue; } inline void Value::clear_number_value() { if (_internal_has_number_value()) { - kind_.number_value_ = 0; + _impl_.kind_.number_value_ = 0; clear_has_kind(); } } inline double Value::_internal_number_value() const { if (_internal_has_number_value()) { - return kind_.number_value_; + return _impl_.kind_.number_value_; } return 0; } @@ -805,7 +814,7 @@ clear_kind(); set_has_number_value(); } - kind_.number_value_ = value; + _impl_.kind_.number_value_ = value; } inline double Value::number_value() const { // @@protoc_insertion_point(field_get:google.protobuf.Value.number_value) @@ -824,11 +833,11 @@ return _internal_has_string_value(); } inline void Value::set_has_string_value() { - _oneof_case_[0] = kStringValue; + _impl_._oneof_case_[0] = kStringValue; } inline void Value::clear_string_value() { if (_internal_has_string_value()) { - kind_.string_value_.Destroy(); + _impl_.kind_.string_value_.Destroy(); clear_has_kind(); } } @@ -841,9 +850,9 @@ if (!_internal_has_string_value()) { clear_kind(); set_has_string_value(); - kind_.string_value_.InitDefault(); + _impl_.kind_.string_value_.InitDefault(); } - kind_.string_value_.Set( static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.kind_.string_value_.Set( static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Value.string_value) } inline std::string* Value::mutable_string_value() { @@ -853,7 +862,7 @@ } inline const std::string& Value::_internal_string_value() const { if (_internal_has_string_value()) { - return kind_.string_value_.Get(); + return _impl_.kind_.string_value_.Get(); } return ::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(); } @@ -861,23 +870,23 @@ if (!_internal_has_string_value()) { clear_kind(); set_has_string_value(); - kind_.string_value_.InitDefault(); + _impl_.kind_.string_value_.InitDefault(); } - kind_.string_value_.Set(value, GetArenaForAllocation()); + _impl_.kind_.string_value_.Set(value, GetArenaForAllocation()); } inline std::string* Value::_internal_mutable_string_value() { if (!_internal_has_string_value()) { clear_kind(); set_has_string_value(); - kind_.string_value_.InitDefault(); + _impl_.kind_.string_value_.InitDefault(); } - return kind_.string_value_.Mutable( GetArenaForAllocation()); + return _impl_.kind_.string_value_.Mutable( GetArenaForAllocation()); } 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(); + return _impl_.kind_.string_value_.Release(); } else { return nullptr; } @@ -888,7 +897,7 @@ } if (string_value != nullptr) { set_has_string_value(); - kind_.string_value_.InitAllocated(string_value, GetArenaForAllocation()); + _impl_.kind_.string_value_.InitAllocated(string_value, GetArenaForAllocation()); } // @@protoc_insertion_point(field_set_allocated:google.protobuf.Value.string_value) } @@ -901,17 +910,17 @@ return _internal_has_bool_value(); } inline void Value::set_has_bool_value() { - _oneof_case_[0] = kBoolValue; + _impl_._oneof_case_[0] = kBoolValue; } inline void Value::clear_bool_value() { if (_internal_has_bool_value()) { - kind_.bool_value_ = false; + _impl_.kind_.bool_value_ = false; clear_has_kind(); } } inline bool Value::_internal_bool_value() const { if (_internal_has_bool_value()) { - return kind_.bool_value_; + return _impl_.kind_.bool_value_; } return false; } @@ -920,7 +929,7 @@ clear_kind(); set_has_bool_value(); } - kind_.bool_value_ = value; + _impl_.kind_.bool_value_ = value; } inline bool Value::bool_value() const { // @@protoc_insertion_point(field_get:google.protobuf.Value.bool_value) @@ -939,12 +948,12 @@ return _internal_has_struct_value(); } inline void Value::set_has_struct_value() { - _oneof_case_[0] = kStructValue; + _impl_._oneof_case_[0] = kStructValue; } inline void Value::clear_struct_value() { if (_internal_has_struct_value()) { if (GetArenaForAllocation() == nullptr) { - delete kind_.struct_value_; + delete _impl_.kind_.struct_value_; } clear_has_kind(); } @@ -953,11 +962,11 @@ // @@protoc_insertion_point(field_release:google.protobuf.Value.struct_value) if (_internal_has_struct_value()) { clear_has_kind(); - ::PROTOBUF_NAMESPACE_ID::Struct* temp = kind_.struct_value_; + ::PROTOBUF_NAMESPACE_ID::Struct* temp = _impl_.kind_.struct_value_; if (GetArenaForAllocation() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - kind_.struct_value_ = nullptr; + _impl_.kind_.struct_value_ = nullptr; return temp; } else { return nullptr; @@ -965,7 +974,7 @@ } inline const ::PROTOBUF_NAMESPACE_ID::Struct& Value::_internal_struct_value() const { return _internal_has_struct_value() - ? *kind_.struct_value_ + ? *_impl_.kind_.struct_value_ : reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::Struct&>(::PROTOBUF_NAMESPACE_ID::_Struct_default_instance_); } inline const ::PROTOBUF_NAMESPACE_ID::Struct& Value::struct_value() const { @@ -976,8 +985,8 @@ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.struct_value) if (_internal_has_struct_value()) { clear_has_kind(); - ::PROTOBUF_NAMESPACE_ID::Struct* temp = kind_.struct_value_; - kind_.struct_value_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::Struct* temp = _impl_.kind_.struct_value_; + _impl_.kind_.struct_value_ = nullptr; return temp; } else { return nullptr; @@ -987,7 +996,7 @@ clear_kind(); if (struct_value) { set_has_struct_value(); - kind_.struct_value_ = struct_value; + _impl_.kind_.struct_value_ = struct_value; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.struct_value) } @@ -995,9 +1004,9 @@ if (!_internal_has_struct_value()) { clear_kind(); set_has_struct_value(); - kind_.struct_value_ = CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Struct >(GetArenaForAllocation()); + _impl_.kind_.struct_value_ = CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::Struct >(GetArenaForAllocation()); } - return kind_.struct_value_; + return _impl_.kind_.struct_value_; } inline ::PROTOBUF_NAMESPACE_ID::Struct* Value::mutable_struct_value() { ::PROTOBUF_NAMESPACE_ID::Struct* _msg = _internal_mutable_struct_value(); @@ -1013,12 +1022,12 @@ return _internal_has_list_value(); } inline void Value::set_has_list_value() { - _oneof_case_[0] = kListValue; + _impl_._oneof_case_[0] = kListValue; } inline void Value::clear_list_value() { if (_internal_has_list_value()) { if (GetArenaForAllocation() == nullptr) { - delete kind_.list_value_; + delete _impl_.kind_.list_value_; } clear_has_kind(); } @@ -1027,11 +1036,11 @@ // @@protoc_insertion_point(field_release:google.protobuf.Value.list_value) if (_internal_has_list_value()) { clear_has_kind(); - ::PROTOBUF_NAMESPACE_ID::ListValue* temp = kind_.list_value_; + ::PROTOBUF_NAMESPACE_ID::ListValue* temp = _impl_.kind_.list_value_; if (GetArenaForAllocation() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } - kind_.list_value_ = nullptr; + _impl_.kind_.list_value_ = nullptr; return temp; } else { return nullptr; @@ -1039,7 +1048,7 @@ } inline const ::PROTOBUF_NAMESPACE_ID::ListValue& Value::_internal_list_value() const { return _internal_has_list_value() - ? *kind_.list_value_ + ? *_impl_.kind_.list_value_ : reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::ListValue&>(::PROTOBUF_NAMESPACE_ID::_ListValue_default_instance_); } inline const ::PROTOBUF_NAMESPACE_ID::ListValue& Value::list_value() const { @@ -1050,8 +1059,8 @@ // @@protoc_insertion_point(field_unsafe_arena_release:google.protobuf.Value.list_value) if (_internal_has_list_value()) { clear_has_kind(); - ::PROTOBUF_NAMESPACE_ID::ListValue* temp = kind_.list_value_; - kind_.list_value_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::ListValue* temp = _impl_.kind_.list_value_; + _impl_.kind_.list_value_ = nullptr; return temp; } else { return nullptr; @@ -1061,7 +1070,7 @@ clear_kind(); if (list_value) { set_has_list_value(); - kind_.list_value_ = list_value; + _impl_.kind_.list_value_ = list_value; } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:google.protobuf.Value.list_value) } @@ -1069,9 +1078,9 @@ if (!_internal_has_list_value()) { clear_kind(); set_has_list_value(); - kind_.list_value_ = CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::ListValue >(GetArenaForAllocation()); + _impl_.kind_.list_value_ = CreateMaybeMessage< ::PROTOBUF_NAMESPACE_ID::ListValue >(GetArenaForAllocation()); } - return kind_.list_value_; + return _impl_.kind_.list_value_; } inline ::PROTOBUF_NAMESPACE_ID::ListValue* Value::mutable_list_value() { ::PROTOBUF_NAMESPACE_ID::ListValue* _msg = _internal_mutable_list_value(); @@ -1083,10 +1092,10 @@ return kind_case() != KIND_NOT_SET; } inline void Value::clear_has_kind() { - _oneof_case_[0] = KIND_NOT_SET; + _impl_._oneof_case_[0] = KIND_NOT_SET; } inline Value::KindCase Value::kind_case() const { - return Value::KindCase(_oneof_case_[0]); + return Value::KindCase(_impl_._oneof_case_[0]); } // ------------------------------------------------------------------- @@ -1094,32 +1103,32 @@ // repeated .google.protobuf.Value values = 1; inline int ListValue::_internal_values_size() const { - return values_.size(); + return _impl_.values_.size(); } inline int ListValue::values_size() const { return _internal_values_size(); } inline void ListValue::clear_values() { - values_.Clear(); + _impl_.values_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::Value* ListValue::mutable_values(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.ListValue.values) - return values_.Mutable(index); + return _impl_.values_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value >* ListValue::mutable_values() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.ListValue.values) - return &values_; + return &_impl_.values_; } inline const ::PROTOBUF_NAMESPACE_ID::Value& ListValue::_internal_values(int index) const { - return values_.Get(index); + return _impl_.values_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Value& ListValue::values(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.ListValue.values) return _internal_values(index); } inline ::PROTOBUF_NAMESPACE_ID::Value* ListValue::_internal_add_values() { - return values_.Add(); + return _impl_.values_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Value* ListValue::add_values() { ::PROTOBUF_NAMESPACE_ID::Value* _add = _internal_add_values(); @@ -1129,7 +1138,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Value >& ListValue::values() const { // @@protoc_insertion_point(field_list:google.protobuf.ListValue.values) - return values_; + return _impl_.values_; } #ifdef __GNUC__
diff --git a/src/google/protobuf/stubs/common.h b/src/google/protobuf/stubs/common.h index 3f1b645..c54468c 100644 --- a/src/google/protobuf/stubs/common.h +++ b/src/google/protobuf/stubs/common.h
@@ -85,7 +85,7 @@ #define GOOGLE_PROTOBUF_VERSION 3020001 // A suffix string for alpha, beta or rc releases. Empty for stable releases. -#define GOOGLE_PROTOBUF_VERSION_SUFFIX "" +#define GOOGLE_PROTOBUF_VERSION_SUFFIX "-rc1" // The minimum header version which works with the current version of // the library. This constant should only be used by protoc's C++ code
diff --git a/src/google/protobuf/stubs/structurally_valid.cc b/src/google/protobuf/stubs/structurally_valid.cc index 9a476c3..3db7a80 100644 --- a/src/google/protobuf/stubs/structurally_valid.cc +++ b/src/google/protobuf/stubs/structurally_valid.cc
@@ -381,6 +381,8 @@ return (static_cast<uint32>(Tbl - Tbl0) < st->state0_size); } +namespace { + // Scan a UTF-8 string based on state table. // Always scan complete UTF-8 characters // Set number of bytes scanned. Return reason for exiting @@ -539,7 +541,6 @@ // UTF-8 strings. Since UTF-8 validation is only used for debugging // anyway, we simply always return success if initialization hasn't // occurred yet. -namespace { bool module_initialized_ = false;
diff --git a/src/google/protobuf/test_messages_proto3.proto b/src/google/protobuf/test_messages_proto3.proto index 278ee4f..1e1285e 100644 --- a/src/google/protobuf/test_messages_proto3.proto +++ b/src/google/protobuf/test_messages_proto3.proto
@@ -80,8 +80,8 @@ ALIAS_FOO = 0; ALIAS_BAR = 1; ALIAS_BAZ = 2; - QUX = 2; - qux = 2; + MOO = 2; + moo = 2; bAz = 2; } @@ -278,8 +278,7 @@ FOREIGN_BAZ = 2; } -message NullHypothesisProto3 { -} +message NullHypothesisProto3 {} message EnumOnlyProto3 { enum Bool {
diff --git a/src/google/protobuf/test_util.h b/src/google/protobuf/test_util.h index 738490e..b18d7b6 100644 --- a/src/google/protobuf/test_util.h +++ b/src/google/protobuf/test_util.h
@@ -238,6 +238,10 @@ sub_message = reflection->MutableMessage(message, F("optional_lazy_message")); sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 127); + sub_message = reflection->MutableMessage( + message, F("optional_unverified_lazy_message")); + sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 128); + // ----------------------------------------------------------------- reflection->AddInt32(message, F("repeated_int32"), 201); @@ -348,7 +352,7 @@ Message* sub_message = reflection->MutableMessage( message, descriptor->FindFieldByName("foo_lazy_message")); sub_message->GetReflection()->SetInt64( - sub_message, sub_message->GetDescriptor()->FindFieldByName("qux_int"), + sub_message, sub_message->GetDescriptor()->FindFieldByName("moo_int"), 100); reflection->SetString(message, descriptor->FindFieldByName("bar_cord"), @@ -376,7 +380,7 @@ message, descriptor->FindFieldByName("foo_lazy_message")); EXPECT_EQ(100, sub_message->GetReflection()->GetInt64( *sub_message, - sub_message->GetDescriptor()->FindFieldByName("qux_int"))); + sub_message->GetDescriptor()->FindFieldByName("moo_int"))); EXPECT_EQ("101", reflection->GetString( message, descriptor->FindFieldByName("bar_cord"))); @@ -468,6 +472,8 @@ EXPECT_TRUE( reflection->HasField(message, F("optional_public_import_message"))); EXPECT_TRUE(reflection->HasField(message, F("optional_lazy_message"))); + EXPECT_TRUE( + reflection->HasField(message, F("optional_unverified_lazy_message"))); sub_message = &reflection->GetMessage(message, F("optionalgroup")); EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); @@ -482,6 +488,9 @@ EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_e_)); sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + sub_message = + &reflection->GetMessage(message, F("optional_unverified_lazy_message")); + EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); EXPECT_TRUE(reflection->HasField(message, F("optional_nested_enum"))); EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_enum"))); @@ -530,6 +539,10 @@ sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); EXPECT_EQ(127, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = + &reflection->GetMessage(message, F("optional_unverified_lazy_message")); + EXPECT_EQ(128, + sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); EXPECT_EQ(nested_baz_, reflection->GetEnum(message, F("optional_nested_enum"))); @@ -897,6 +910,8 @@ EXPECT_FALSE( reflection->HasField(message, F("optional_public_import_message"))); EXPECT_FALSE(reflection->HasField(message, F("optional_lazy_message"))); + EXPECT_FALSE( + reflection->HasField(message, F("optional_unverified_lazy_message"))); EXPECT_FALSE(reflection->HasField(message, F("optional_nested_enum"))); EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_enum"))); @@ -949,6 +964,10 @@ sub_message = &reflection->GetMessage(message, F("optional_lazy_message")); EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); + sub_message = + &reflection->GetMessage(message, F("optional_unverified_lazy_message")); + EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); + EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); // Enums without defaults are set to the first value in the enum. EXPECT_EQ(nested_foo_,
diff --git a/src/google/protobuf/test_util.inc b/src/google/protobuf/test_util.inc index 0f1b147..8d44afa 100644 --- a/src/google/protobuf/test_util.inc +++ b/src/google/protobuf/test_util.inc
@@ -39,9 +39,9 @@ #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/common.h> +#include <gtest/gtest.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/message.h> -#include <gtest/gtest.h> namespace google { namespace protobuf { @@ -143,6 +143,7 @@ message->mutable_optional_import_message()->set_d(120); message->mutable_optional_public_import_message()->set_e(126); message->mutable_optional_lazy_message()->set_bb(127); + message->mutable_optional_unverified_lazy_message()->set_bb(128); message->set_optional_nested_enum(UNITTEST::TestAllTypes::BAZ); message->set_optional_foreign_enum(UNITTEST::FOREIGN_BAZ); @@ -347,6 +348,7 @@ EXPECT_TRUE(message.has_optional_import_message()); EXPECT_TRUE(message.has_optional_public_import_message()); EXPECT_TRUE(message.has_optional_lazy_message()); + EXPECT_TRUE(message.has_optional_unverified_lazy_message()); EXPECT_TRUE(message.optionalgroup().has_a()); EXPECT_TRUE(message.optional_nested_message().has_bb()); @@ -354,6 +356,7 @@ EXPECT_TRUE(message.optional_import_message().has_d()); EXPECT_TRUE(message.optional_public_import_message().has_e()); EXPECT_TRUE(message.optional_lazy_message().has_bb()); + EXPECT_TRUE(message.optional_unverified_lazy_message().has_bb()); EXPECT_TRUE(message.has_optional_nested_enum()); EXPECT_TRUE(message.has_optional_foreign_enum()); @@ -386,6 +389,7 @@ EXPECT_EQ(120, message.optional_import_message().d()); EXPECT_EQ(126, message.optional_public_import_message().e()); EXPECT_EQ(127, message.optional_lazy_message().bb()); + EXPECT_EQ(128, message.optional_unverified_lazy_message().bb()); EXPECT_EQ(UNITTEST::TestAllTypes::BAZ, message.optional_nested_enum()); EXPECT_EQ(UNITTEST::FOREIGN_BAZ, message.optional_foreign_enum()); @@ -556,6 +560,7 @@ EXPECT_FALSE(message.has_optional_import_message()); EXPECT_FALSE(message.has_optional_public_import_message()); EXPECT_FALSE(message.has_optional_lazy_message()); + EXPECT_FALSE(message.has_optional_unverified_lazy_message()); EXPECT_FALSE(message.has_optional_nested_enum()); EXPECT_FALSE(message.has_optional_foreign_enum()); @@ -588,6 +593,7 @@ EXPECT_FALSE(message.optional_import_message().has_d()); EXPECT_FALSE(message.optional_public_import_message().has_e()); EXPECT_FALSE(message.optional_lazy_message().has_bb()); + EXPECT_FALSE(message.optional_unverified_lazy_message().has_bb()); EXPECT_EQ(0, message.optionalgroup().a()); EXPECT_EQ(0, message.optional_nested_message().bb()); @@ -595,6 +601,7 @@ EXPECT_EQ(0, message.optional_import_message().d()); EXPECT_EQ(0, message.optional_public_import_message().e()); EXPECT_EQ(0, message.optional_lazy_message().bb()); + EXPECT_EQ(0, message.optional_unverified_lazy_message().bb()); // Enums without defaults are set to the first value in the enum. EXPECT_EQ(UNITTEST::TestAllTypes::FOO, message.optional_nested_enum()); @@ -987,6 +994,9 @@ ->set_e(126); message->MutableExtension(UNITTEST::optional_lazy_message_extension) ->set_bb(127); + message + ->MutableExtension(UNITTEST::optional_unverified_lazy_message_extension) + ->set_bb(128); // ----------------------------------------------------------------- @@ -1183,6 +1193,8 @@ EXPECT_TRUE( message.HasExtension(UNITTEST::optional_public_import_message_extension)); EXPECT_TRUE(message.HasExtension(UNITTEST::optional_lazy_message_extension)); + EXPECT_TRUE(message.HasExtension( + UNITTEST::optional_unverified_lazy_message_extension)); EXPECT_TRUE(message.GetExtension(UNITTEST::optionalgroup_extension).has_a()); EXPECT_TRUE(message.GetExtension(UNITTEST::optional_nested_message_extension) @@ -1196,6 +1208,9 @@ .has_e()); EXPECT_TRUE( message.GetExtension(UNITTEST::optional_lazy_message_extension).has_bb()); + EXPECT_TRUE( + message.GetExtension(UNITTEST::optional_unverified_lazy_message_extension) + .has_bb()); EXPECT_TRUE(message.HasExtension(UNITTEST::optional_nested_enum_extension)); EXPECT_TRUE(message.HasExtension(UNITTEST::optional_foreign_enum_extension)); @@ -1248,6 +1263,10 @@ EXPECT_EQ( 127, message.GetExtension(UNITTEST::optional_lazy_message_extension).bb()); + EXPECT_EQ( + 128, + message.GetExtension(UNITTEST::optional_unverified_lazy_message_extension) + .bb()); // ----------------------------------------------------------------- @@ -1476,6 +1495,8 @@ EXPECT_FALSE( message.HasExtension(UNITTEST::optional_public_import_message_extension)); EXPECT_FALSE(message.HasExtension(UNITTEST::optional_lazy_message_extension)); + EXPECT_FALSE(message.HasExtension( + UNITTEST::optional_unverified_lazy_message_extension)); EXPECT_FALSE(message.HasExtension(UNITTEST::optional_nested_enum_extension)); EXPECT_FALSE(message.HasExtension(UNITTEST::optional_foreign_enum_extension)); @@ -1515,6 +1536,9 @@ .has_e()); EXPECT_FALSE( message.GetExtension(UNITTEST::optional_lazy_message_extension).has_bb()); + EXPECT_FALSE( + message.GetExtension(UNITTEST::optional_unverified_lazy_message_extension) + .has_bb()); EXPECT_EQ(0, message.GetExtension(UNITTEST::optionalgroup_extension).a()); EXPECT_EQ( @@ -1531,6 +1555,10 @@ .e()); EXPECT_EQ( 0, message.GetExtension(UNITTEST::optional_lazy_message_extension).bb()); + EXPECT_EQ( + 0, + message.GetExtension(UNITTEST::optional_unverified_lazy_message_extension) + .bb()); // Enums without defaults are set to the first value in the enum. EXPECT_EQ(UNITTEST::TestAllTypes::FOO, @@ -2315,7 +2343,7 @@ } inline void TestUtil::SetOneof1(UNITTEST::TestOneof2* message) { - message->mutable_foo_lazy_message()->set_qux_int(100); + message->mutable_foo_lazy_message()->set_moo_int(100); message->set_bar_string("101"); message->set_baz_int(102); message->set_baz_string("103"); @@ -2332,7 +2360,7 @@ ExpectAtMostOneFieldSetInOneof(message); EXPECT_TRUE(message.has_foo_lazy_message()); - EXPECT_TRUE(message.foo_lazy_message().has_qux_int()); + EXPECT_TRUE(message.foo_lazy_message().has_moo_int()); EXPECT_TRUE(message.has_bar_string()); EXPECT_TRUE(message.has_baz_int()); @@ -2340,7 +2368,7 @@ ASSERT_EQ(0, message.foo_lazy_message().corge_int_size()); - EXPECT_EQ(100, message.foo_lazy_message().qux_int()); + EXPECT_EQ(100, message.foo_lazy_message().moo_int()); EXPECT_EQ("101", message.bar_string()); EXPECT_EQ(102, message.baz_int()); EXPECT_EQ("103", message.baz_string());
diff --git a/src/google/protobuf/test_util2.h b/src/google/protobuf/test_util2.h index e3f53a9..540af63 100644 --- a/src/google/protobuf/test_util2.h +++ b/src/google/protobuf/test_util2.h
@@ -33,10 +33,10 @@ #include <google/protobuf/stubs/strutil.h> -#include <google/protobuf/util/message_differencer.h> #include <google/protobuf/testing/googletest.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> +#include <google/protobuf/util/message_differencer.h> namespace google { namespace protobuf {
diff --git a/src/google/protobuf/test_util_lite.cc b/src/google/protobuf/test_util_lite.cc index e7eb60a..628f1a0 100644 --- a/src/google/protobuf/test_util_lite.cc +++ b/src/google/protobuf/test_util_lite.cc
@@ -65,6 +65,7 @@ message->mutable_optional_import_message()->set_d(120); message->mutable_optional_public_import_message()->set_e(126); message->mutable_optional_lazy_message()->set_bb(127); + message->mutable_optional_unverified_lazy_message()->set_bb(128); message->set_optional_nested_enum(unittest::TestAllTypesLite::BAZ); message->set_optional_foreign_enum(unittest::FOREIGN_LITE_BAZ); @@ -214,6 +215,7 @@ EXPECT_TRUE(message.has_optional_import_message()); EXPECT_TRUE(message.has_optional_public_import_message()); EXPECT_TRUE(message.has_optional_lazy_message()); + EXPECT_TRUE(message.has_optional_unverified_lazy_message()); EXPECT_TRUE(message.optionalgroup().has_a()); EXPECT_TRUE(message.optional_nested_message().has_bb()); @@ -221,6 +223,7 @@ EXPECT_TRUE(message.optional_import_message().has_d()); EXPECT_TRUE(message.optional_public_import_message().has_e()); EXPECT_TRUE(message.optional_lazy_message().has_bb()); + EXPECT_TRUE(message.optional_unverified_lazy_message().has_bb()); EXPECT_TRUE(message.has_optional_nested_enum()); EXPECT_TRUE(message.has_optional_foreign_enum()); @@ -249,6 +252,7 @@ EXPECT_EQ(120, message.optional_import_message().d()); EXPECT_EQ(126, message.optional_public_import_message().e()); EXPECT_EQ(127, message.optional_lazy_message().bb()); + EXPECT_EQ(128, message.optional_unverified_lazy_message().bb()); EXPECT_EQ(unittest::TestAllTypesLite::BAZ, message.optional_nested_enum()); EXPECT_EQ(unittest::FOREIGN_LITE_BAZ, message.optional_foreign_enum()); @@ -415,6 +419,7 @@ EXPECT_FALSE(message.has_optional_import_message()); EXPECT_FALSE(message.has_optional_public_import_message()); EXPECT_FALSE(message.has_optional_lazy_message()); + EXPECT_FALSE(message.has_optional_unverified_lazy_message()); EXPECT_FALSE(message.has_optional_nested_enum()); EXPECT_FALSE(message.has_optional_foreign_enum()); @@ -445,6 +450,7 @@ EXPECT_FALSE(message.optional_import_message().has_d()); EXPECT_FALSE(message.optional_public_import_message().has_e()); EXPECT_FALSE(message.optional_lazy_message().has_bb()); + EXPECT_FALSE(message.optional_unverified_lazy_message().has_bb()); EXPECT_EQ(0, message.optionalgroup().a()); EXPECT_EQ(0, message.optional_nested_message().bb()); @@ -836,6 +842,10 @@ ->set_e(126); message->MutableExtension(unittest::optional_lazy_message_extension_lite) ->set_bb(127); + message + ->MutableExtension( + unittest::optional_unverified_lazy_message_extension_lite) + ->set_bb(128); message->SetExtension(unittest::optional_nested_enum_extension_lite, unittest::TestAllTypesLite::BAZ); @@ -1022,6 +1032,8 @@ unittest::optional_public_import_message_extension_lite)); EXPECT_TRUE( message.HasExtension(unittest::optional_lazy_message_extension_lite)); + EXPECT_TRUE(message.HasExtension( + unittest::optional_unverified_lazy_message_extension_lite)); EXPECT_TRUE( message.GetExtension(unittest::optionalgroup_extension_lite).has_a()); @@ -1041,6 +1053,10 @@ EXPECT_TRUE( message.GetExtension(unittest::optional_lazy_message_extension_lite) .has_bb()); + EXPECT_TRUE(message + .GetExtension( + unittest::optional_unverified_lazy_message_extension_lite) + .has_bb()); EXPECT_TRUE( message.HasExtension(unittest::optional_nested_enum_extension_lite)); @@ -1099,6 +1115,11 @@ EXPECT_EQ(127, message.GetExtension(unittest::optional_lazy_message_extension_lite) .bb()); + EXPECT_EQ(128, + message + .GetExtension( + unittest::optional_unverified_lazy_message_extension_lite) + .bb()); EXPECT_EQ( unittest::TestAllTypesLite::BAZ,
diff --git a/src/google/protobuf/testdata/golden_message b/src/google/protobuf/testdata/golden_message index 0b7e655..5825975 100644 --- a/src/google/protobuf/testdata/golden_message +++ b/src/google/protobuf/testdata/golden_message Binary files differ
diff --git a/src/google/protobuf/testdata/golden_message_oneof_implemented b/src/google/protobuf/testdata/golden_message_oneof_implemented index b48c898..794ca5e 100644 --- a/src/google/protobuf/testdata/golden_message_oneof_implemented +++ b/src/google/protobuf/testdata/golden_message_oneof_implemented Binary files differ
diff --git a/src/google/protobuf/testdata/text_format_unittest_data_oneof_implemented.txt b/src/google/protobuf/testdata/text_format_unittest_data_oneof_implemented.txt index ec95e1e..86389c9 100644 --- a/src/google/protobuf/testdata/text_format_unittest_data_oneof_implemented.txt +++ b/src/google/protobuf/testdata/text_format_unittest_data_oneof_implemented.txt
@@ -36,6 +36,9 @@ optional_lazy_message { bb: 127 } +optional_unverified_lazy_message { + bb: 128 +} repeated_int32: 201 repeated_int32: 301 repeated_int64: 202
diff --git a/src/google/protobuf/testdata/text_format_unittest_data_pointy.txt b/src/google/protobuf/testdata/text_format_unittest_data_pointy.txt index e1011eb..788025c 100644 --- a/src/google/protobuf/testdata/text_format_unittest_data_pointy.txt +++ b/src/google/protobuf/testdata/text_format_unittest_data_pointy.txt
@@ -36,6 +36,9 @@ optional_lazy_message < bb: 127 > +optional_unverified_lazy_message < + bb: 128 +> repeated_int32: 201 repeated_int32: 301 repeated_int64: 202
diff --git a/src/google/protobuf/testdata/text_format_unittest_data_pointy_oneof.txt b/src/google/protobuf/testdata/text_format_unittest_data_pointy_oneof.txt index 95109f6..b2d3367 100644 --- a/src/google/protobuf/testdata/text_format_unittest_data_pointy_oneof.txt +++ b/src/google/protobuf/testdata/text_format_unittest_data_pointy_oneof.txt
@@ -36,6 +36,9 @@ optional_lazy_message < bb: 127 > +optional_unverified_lazy_message < + bb: 128 +> repeated_int32: 201 repeated_int32: 301 repeated_int64: 202
diff --git a/src/google/protobuf/testdata/text_format_unittest_extensions_data.txt b/src/google/protobuf/testdata/text_format_unittest_extensions_data.txt index 8c8b1eb..5c3a03a 100644 --- a/src/google/protobuf/testdata/text_format_unittest_extensions_data.txt +++ b/src/google/protobuf/testdata/text_format_unittest_extensions_data.txt
@@ -36,6 +36,9 @@ [protobuf_unittest.optional_lazy_message_extension] { bb: 127 } +[protobuf_unittest.optional_unverified_lazy_message_extension] { + bb: 128 +} [protobuf_unittest.repeated_int32_extension]: 201 [protobuf_unittest.repeated_int32_extension]: 301 [protobuf_unittest.repeated_int64_extension]: 202
diff --git a/src/google/protobuf/testdata/text_format_unittest_extensions_data_pointy.txt b/src/google/protobuf/testdata/text_format_unittest_extensions_data_pointy.txt index 132f744..4233ca7 100644 --- a/src/google/protobuf/testdata/text_format_unittest_extensions_data_pointy.txt +++ b/src/google/protobuf/testdata/text_format_unittest_extensions_data_pointy.txt
@@ -36,6 +36,9 @@ [protobuf_unittest.optional_lazy_message_extension] < bb: 127 > +[protobuf_unittest.optional_unverified_lazy_message_extension] < + bb: 128 +> [protobuf_unittest.repeated_int32_extension]: 201 [protobuf_unittest.repeated_int32_extension]: 301 [protobuf_unittest.repeated_int64_extension]: 202
diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc index 880b16d..5566eec 100644 --- a/src/google/protobuf/text_format.cc +++ b/src/google/protobuf/text_format.cc
@@ -42,6 +42,7 @@ #include <climits> #include <cmath> #include <limits> +#include <utility> #include <vector> #include <google/protobuf/io/coded_stream.h> @@ -244,8 +245,8 @@ public: // Determines if repeated values for non-repeated fields and // oneofs are permitted, e.g., the string "foo: 1 foo: 2" for a - // required/optional field named "foo", or "baz: 1 qux: 2" - // where "baz" and "qux" are members of the same oneof. + // required/optional field named "foo", or "baz: 1 bar: 2" + // where "baz" and "bar" are members of the same oneof. enum SingularOverwritePolicy { ALLOW_SINGULAR_OVERWRITES = 0, // the last value is retained FORBID_SINGULAR_OVERWRITES = 1, // an error is issued @@ -455,8 +456,9 @@ } } reflection->SetString(message, any_type_url_field, - prefix_and_full_type_name); - reflection->SetString(message, any_value_field, serialized_value); + std::move(prefix_and_full_type_name)); + reflection->SetString(message, any_value_field, + std::move(serialized_value)); return true; } if (TryConsume("[")) { @@ -803,7 +805,7 @@ case FieldDescriptor::CPPTYPE_STRING: { std::string value; DO(ConsumeString(&value)); - SET_FIELD(String, value); + SET_FIELD(String, std::move(value)); break; }
diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h index 8640493..c27ab3f 100644 --- a/src/google/protobuf/text_format.h +++ b/src/google/protobuf/text_format.h
@@ -456,16 +456,15 @@ }; // Parses a text-format protocol message from the given input stream to - // the given message object. This function parses the human-readable format - // written by Print(). Returns true on success. The message is cleared first, - // even if the function fails -- See Merge() to avoid this behavior. + // the given message object. This function parses the human-readable + // serialization format written by Print(). Returns true on success. The + // message is cleared first, even if the function fails -- See Merge() to + // avoid this behavior. // // Example input: "user {\n id: 123 extra { gender: MALE language: 'en' }\n}" // - // One use for this function is parsing handwritten strings in test code. - // Another use is to parse the output from google::protobuf::Message::DebugString() - // (or ShortDebugString()), because these functions output using - // google::protobuf::TextFormat::Print(). + // One common use for this function is parsing handwritten strings in test + // code. // // If you would like to read a protocol buffer serialized in the // (non-human-readable) binary wire format, see
diff --git a/src/google/protobuf/text_format_unittest.cc b/src/google/protobuf/text_format_unittest.cc index 32a33d8..9417b87 100644 --- a/src/google/protobuf/text_format_unittest.cc +++ b/src/google/protobuf/text_format_unittest.cc
@@ -47,8 +47,6 @@ #include <google/protobuf/testing/file.h> #include <google/protobuf/any.pb.h> #include <google/protobuf/map_unittest.pb.h> -#include <google/protobuf/test_util.h> -#include <google/protobuf/test_util2.h> #include <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_mset.pb.h> #include <google/protobuf/unittest_mset_wire_format.pb.h> @@ -61,6 +59,8 @@ #include <gtest/gtest.h> #include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/substitute.h> +#include <google/protobuf/test_util.h> +#include <google/protobuf/test_util2.h> // Must be included last.
diff --git a/src/google/protobuf/timestamp.pb.cc b/src/google/protobuf/timestamp.pb.cc index f2bf9b2..6c8f3b2 100644 --- a/src/google/protobuf/timestamp.pb.cc +++ b/src/google/protobuf/timestamp.pb.cc
@@ -22,9 +22,10 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Timestamp::Timestamp( - ::_pbi::ConstantInitialized) - : seconds_(int64_t{0}) - , nanos_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.seconds_)*/int64_t{0} + , /*decltype(_impl_.nanos_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct TimestampDefaultTypeInternal { PROTOBUF_CONSTEXPR TimestampDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -46,8 +47,8 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, seconds_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, nanos_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, _impl_.seconds_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Timestamp, _impl_.nanos_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Timestamp)}, @@ -91,23 +92,32 @@ Timestamp::Timestamp(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Timestamp) } Timestamp::Timestamp(const Timestamp& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.seconds_){} + , decltype(_impl_.nanos_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _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_)); + ::memcpy(&_impl_.seconds_, &from._impl_.seconds_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.nanos_) - + reinterpret_cast<char*>(&_impl_.seconds_)) + sizeof(_impl_.nanos_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.Timestamp) } -inline void Timestamp::SharedCtor() { -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&seconds_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&nanos_) - - reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_)); +inline void Timestamp::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.seconds_){int64_t{0}} + , decltype(_impl_.nanos_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; } Timestamp::~Timestamp() { @@ -124,7 +134,7 @@ } void Timestamp::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Timestamp::Clear() { @@ -133,9 +143,9 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - ::memset(&seconds_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&nanos_) - - reinterpret_cast<char*>(&seconds_)) + sizeof(nanos_)); + ::memset(&_impl_.seconds_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.nanos_) - + reinterpret_cast<char*>(&_impl_.seconds_)) + sizeof(_impl_.nanos_)); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -148,7 +158,7 @@ // int64 seconds = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { - seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.seconds_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -156,7 +166,7 @@ // int32 nanos = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { - nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.nanos_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -228,11 +238,11 @@ total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_nanos()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Timestamp::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Timestamp::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Timestamp::GetClassData() const { return &_class_data_; } @@ -274,11 +284,11 @@ using std::swap; _internal_metadata_.InternalSwap(&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_FIELD_OFFSET(Timestamp, _impl_.nanos_) + + sizeof(Timestamp::_impl_.nanos_) + - PROTOBUF_FIELD_OFFSET(Timestamp, _impl_.seconds_)>( + reinterpret_cast<char*>(&_impl_.seconds_), + reinterpret_cast<char*>(&other->_impl_.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 cc368ea..4561e68 100644 --- a/src/google/protobuf/timestamp.pb.h +++ b/src/google/protobuf/timestamp.pb.h
@@ -147,10 +147,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Timestamp* other); @@ -203,9 +203,12 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - int64_t seconds_; - int32_t nanos_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + int64_t seconds_; + int32_t nanos_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftimestamp_2eproto; }; // =================================================================== @@ -221,10 +224,10 @@ // int64 seconds = 1; inline void Timestamp::clear_seconds() { - seconds_ = int64_t{0}; + _impl_.seconds_ = int64_t{0}; } inline int64_t Timestamp::_internal_seconds() const { - return seconds_; + return _impl_.seconds_; } inline int64_t Timestamp::seconds() const { // @@protoc_insertion_point(field_get:google.protobuf.Timestamp.seconds) @@ -232,7 +235,7 @@ } inline void Timestamp::_internal_set_seconds(int64_t value) { - seconds_ = value; + _impl_.seconds_ = value; } inline void Timestamp::set_seconds(int64_t value) { _internal_set_seconds(value); @@ -241,10 +244,10 @@ // int32 nanos = 2; inline void Timestamp::clear_nanos() { - nanos_ = 0; + _impl_.nanos_ = 0; } inline int32_t Timestamp::_internal_nanos() const { - return nanos_; + return _impl_.nanos_; } inline int32_t Timestamp::nanos() const { // @@protoc_insertion_point(field_get:google.protobuf.Timestamp.nanos) @@ -252,7 +255,7 @@ } inline void Timestamp::_internal_set_nanos(int32_t value) { - nanos_ = value; + _impl_.nanos_ = value; } inline void Timestamp::set_nanos(int32_t value) { _internal_set_nanos(value);
diff --git a/src/google/protobuf/type.pb.cc b/src/google/protobuf/type.pb.cc index 3d37ee4..618159b 100644 --- a/src/google/protobuf/type.pb.cc +++ b/src/google/protobuf/type.pb.cc
@@ -22,14 +22,14 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR Type::Type( - ::_pbi::ConstantInitialized) - : fields_() - , oneofs_() - , options_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , source_context_(nullptr) - , syntax_(0) -{} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.fields_)*/{} + , /*decltype(_impl_.oneofs_)*/{} + , /*decltype(_impl_.options_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.source_context_)*/nullptr + , /*decltype(_impl_.syntax_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct TypeDefaultTypeInternal { PROTOBUF_CONSTEXPR TypeDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -40,19 +40,18 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 TypeDefaultTypeInternal _Type_default_instance_; PROTOBUF_CONSTEXPR Field::Field( - ::_pbi::ConstantInitialized) - : options_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , type_url_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , json_name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , default_value_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , kind_(0) - - , cardinality_(0) - - , number_(0) - , oneof_index_(0) - , packed_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.options_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.type_url_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.json_name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.default_value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.kind_)*/0 + , /*decltype(_impl_.cardinality_)*/0 + , /*decltype(_impl_.number_)*/0 + , /*decltype(_impl_.oneof_index_)*/0 + , /*decltype(_impl_.packed_)*/false + , /*decltype(_impl_._cached_size_)*/{}} {} struct FieldDefaultTypeInternal { PROTOBUF_CONSTEXPR FieldDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -63,13 +62,13 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FieldDefaultTypeInternal _Field_default_instance_; PROTOBUF_CONSTEXPR Enum::Enum( - ::_pbi::ConstantInitialized) - : enumvalue_() - , options_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , source_context_(nullptr) - , syntax_(0) -{} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.enumvalue_)*/{} + , /*decltype(_impl_.options_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.source_context_)*/nullptr + , /*decltype(_impl_.syntax_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct EnumDefaultTypeInternal { PROTOBUF_CONSTEXPR EnumDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -80,10 +79,11 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumDefaultTypeInternal _Enum_default_instance_; PROTOBUF_CONSTEXPR EnumValue::EnumValue( - ::_pbi::ConstantInitialized) - : options_() - , name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , number_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.options_)*/{} + , /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.number_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct EnumValueDefaultTypeInternal { PROTOBUF_CONSTEXPR EnumValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -94,9 +94,10 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 EnumValueDefaultTypeInternal _EnumValue_default_instance_; PROTOBUF_CONSTEXPR Option::Option( - ::_pbi::ConstantInitialized) - : name_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}) - , value_(nullptr){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.name_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_.value_)*/nullptr + , /*decltype(_impl_._cached_size_)*/{}} {} struct OptionDefaultTypeInternal { PROTOBUF_CONSTEXPR OptionDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -118,56 +119,56 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, fields_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, oneofs_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, source_context_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, syntax_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.fields_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.oneofs_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.source_context_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Type, _impl_.syntax_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, kind_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, cardinality_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, number_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, type_url_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, oneof_index_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, packed_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, json_name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, default_value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.kind_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.cardinality_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.number_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.type_url_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.oneof_index_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.packed_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.json_name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Field, _impl_.default_value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, enumvalue_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, options_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, source_context_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, syntax_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.enumvalue_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.source_context_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Enum, _impl_.syntax_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, number_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, options_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.number_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::EnumValue, _impl_.options_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, name_), - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _impl_.name_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Option, _impl_.value_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::Type)}, @@ -351,55 +352,64 @@ const ::PROTOBUF_NAMESPACE_ID::SourceContext& Type::_Internal::source_context(const Type* msg) { - return *msg->source_context_; + return *msg->_impl_.source_context_; } void Type::clear_source_context() { - if (GetArenaForAllocation() == nullptr && source_context_ != nullptr) { - delete source_context_; + if (GetArenaForAllocation() == nullptr && _impl_.source_context_ != nullptr) { + delete _impl_.source_context_; } - source_context_ = nullptr; + _impl_.source_context_ = nullptr; } Type::Type(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - fields_(arena), - oneofs_(arena), - options_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Type) } Type::Type(const Type& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - fields_(from.fields_), - oneofs_(from.oneofs_), - options_(from.options_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.fields_){from._impl_.fields_} + , decltype(_impl_.oneofs_){from._impl_.oneofs_} + , decltype(_impl_.options_){from._impl_.options_} + , decltype(_impl_.name_){} + , decltype(_impl_.source_context_){nullptr} + , decltype(_impl_.syntax_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_name().empty()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } if (from._internal_has_source_context()) { - source_context_ = new ::PROTOBUF_NAMESPACE_ID::SourceContext(*from.source_context_); - } else { - source_context_ = nullptr; + _impl_.source_context_ = new ::PROTOBUF_NAMESPACE_ID::SourceContext(*from._impl_.source_context_); } - syntax_ = from.syntax_; + _impl_.syntax_ = from._impl_.syntax_; // @@protoc_insertion_point(copy_constructor:google.protobuf.Type) } -inline void Type::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&source_context_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&syntax_) - - reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_)); +inline void Type::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.fields_){arena} + , decltype(_impl_.oneofs_){arena} + , decltype(_impl_.options_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.source_context_){nullptr} + , decltype(_impl_.syntax_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Type::~Type() { @@ -413,12 +423,15 @@ inline void Type::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - if (this != internal_default_instance()) delete source_context_; + _impl_.fields_.~RepeatedPtrField(); + _impl_.oneofs_.~RepeatedPtrField(); + _impl_.options_.~RepeatedPtrField(); + _impl_.name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.source_context_; } void Type::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Type::Clear() { @@ -427,15 +440,15 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - fields_.Clear(); - oneofs_.Clear(); - options_.Clear(); - name_.ClearToEmpty(); - if (GetArenaForAllocation() == nullptr && source_context_ != nullptr) { - delete source_context_; + _impl_.fields_.Clear(); + _impl_.oneofs_.Clear(); + _impl_.options_.Clear(); + _impl_.name_.ClearToEmpty(); + if (GetArenaForAllocation() == nullptr && _impl_.source_context_ != nullptr) { + delete _impl_.source_context_; } - source_context_ = nullptr; - syntax_ = 0; + _impl_.source_context_ = nullptr; + _impl_.syntax_ = 0; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -610,22 +623,22 @@ // repeated .google.protobuf.Field fields = 2; total_size += 1UL * this->_internal_fields_size(); - for (const auto& msg : this->fields_) { + for (const auto& msg : this->_impl_.fields_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated string oneofs = 3; total_size += 1 * - ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(oneofs_.size()); - for (int i = 0, n = oneofs_.size(); i < n; i++) { + ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(_impl_.oneofs_.size()); + for (int i = 0, n = _impl_.oneofs_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( - oneofs_.Get(i)); + _impl_.oneofs_.Get(i)); } // repeated .google.protobuf.Option options = 4; total_size += 1UL * this->_internal_options_size(); - for (const auto& msg : this->options_) { + for (const auto& msg : this->_impl_.options_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } @@ -641,7 +654,7 @@ if (this->_internal_has_source_context()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *source_context_); + *_impl_.source_context_); } // .google.protobuf.Syntax syntax = 6; @@ -650,11 +663,11 @@ ::_pbi::WireFormatLite::EnumSize(this->_internal_syntax()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Type::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Type::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Type::GetClassData() const { return &_class_data_; } @@ -672,9 +685,9 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - fields_.MergeFrom(from.fields_); - oneofs_.MergeFrom(from.oneofs_); - options_.MergeFrom(from.options_); + _impl_.fields_.MergeFrom(from._impl_.fields_); + _impl_.oneofs_.MergeFrom(from._impl_.oneofs_); + _impl_.options_.MergeFrom(from._impl_.options_); if (!from._internal_name().empty()) { _internal_set_name(from._internal_name()); } @@ -703,19 +716,19 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - fields_.InternalSwap(&other->fields_); - oneofs_.InternalSwap(&other->oneofs_); - options_.InternalSwap(&other->options_); + _impl_.fields_.InternalSwap(&other->_impl_.fields_); + _impl_.oneofs_.InternalSwap(&other->_impl_.oneofs_); + _impl_.options_.InternalSwap(&other->_impl_.options_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::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_FIELD_OFFSET(Type, _impl_.syntax_) + + sizeof(Type::_impl_.syntax_) + - PROTOBUF_FIELD_OFFSET(Type, _impl_.source_context_)>( + reinterpret_cast<char*>(&_impl_.source_context_), + reinterpret_cast<char*>(&other->_impl_.source_context_)); } ::PROTOBUF_NAMESPACE_ID::Metadata Type::GetMetadata() const { @@ -732,74 +745,97 @@ Field::Field(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - options_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Field) } Field::Field(const Field& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - options_(from.options_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.options_){from._impl_.options_} + , decltype(_impl_.name_){} + , decltype(_impl_.type_url_){} + , decltype(_impl_.json_name_){} + , decltype(_impl_.default_value_){} + , decltype(_impl_.kind_){} + , decltype(_impl_.cardinality_){} + , decltype(_impl_.number_){} + , decltype(_impl_.oneof_index_){} + , decltype(_impl_.packed_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_name().empty()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - type_url_.InitDefault(); + _impl_.type_url_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - type_url_.Set("", GetArenaForAllocation()); + _impl_.type_url_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_type_url().empty()) { - type_url_.Set(from._internal_type_url(), + _impl_.type_url_.Set(from._internal_type_url(), GetArenaForAllocation()); } - json_name_.InitDefault(); + _impl_.json_name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - json_name_.Set("", GetArenaForAllocation()); + _impl_.json_name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_json_name().empty()) { - json_name_.Set(from._internal_json_name(), + _impl_.json_name_.Set(from._internal_json_name(), GetArenaForAllocation()); } - default_value_.InitDefault(); + _impl_.default_value_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - default_value_.Set("", GetArenaForAllocation()); + _impl_.default_value_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_default_value().empty()) { - default_value_.Set(from._internal_default_value(), + _impl_.default_value_.Set(from._internal_default_value(), GetArenaForAllocation()); } - ::memcpy(&kind_, &from.kind_, - static_cast<size_t>(reinterpret_cast<char*>(&packed_) - - reinterpret_cast<char*>(&kind_)) + sizeof(packed_)); + ::memcpy(&_impl_.kind_, &from._impl_.kind_, + static_cast<size_t>(reinterpret_cast<char*>(&_impl_.packed_) - + reinterpret_cast<char*>(&_impl_.kind_)) + sizeof(_impl_.packed_)); // @@protoc_insertion_point(copy_constructor:google.protobuf.Field) } -inline void Field::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -type_url_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - type_url_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -json_name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - json_name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -default_value_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - default_value_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&kind_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&packed_) - - reinterpret_cast<char*>(&kind_)) + sizeof(packed_)); +inline void Field::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.options_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.type_url_){} + , decltype(_impl_.json_name_){} + , decltype(_impl_.default_value_){} + , decltype(_impl_.kind_){0} + , decltype(_impl_.cardinality_){0} + , decltype(_impl_.number_){0} + , decltype(_impl_.oneof_index_){0} + , decltype(_impl_.packed_){false} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.type_url_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.type_url_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.json_name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.json_name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.default_value_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.default_value_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Field::~Field() { @@ -813,14 +849,15 @@ inline void Field::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - type_url_.Destroy(); - json_name_.Destroy(); - default_value_.Destroy(); + _impl_.options_.~RepeatedPtrField(); + _impl_.name_.Destroy(); + _impl_.type_url_.Destroy(); + _impl_.json_name_.Destroy(); + _impl_.default_value_.Destroy(); } void Field::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Field::Clear() { @@ -829,14 +866,14 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - options_.Clear(); - name_.ClearToEmpty(); - type_url_.ClearToEmpty(); - json_name_.ClearToEmpty(); - default_value_.ClearToEmpty(); - ::memset(&kind_, 0, static_cast<size_t>( - reinterpret_cast<char*>(&packed_) - - reinterpret_cast<char*>(&kind_)) + sizeof(packed_)); + _impl_.options_.Clear(); + _impl_.name_.ClearToEmpty(); + _impl_.type_url_.ClearToEmpty(); + _impl_.json_name_.ClearToEmpty(); + _impl_.default_value_.ClearToEmpty(); + ::memset(&_impl_.kind_, 0, static_cast<size_t>( + reinterpret_cast<char*>(&_impl_.packed_) - + reinterpret_cast<char*>(&_impl_.kind_)) + sizeof(_impl_.packed_)); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -867,7 +904,7 @@ // int32 number = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 24)) { - number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -895,7 +932,7 @@ // int32 oneof_index = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 56)) { - oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.oneof_index_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -903,7 +940,7 @@ // bool packed = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 64)) { - packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.packed_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -1068,7 +1105,7 @@ // repeated .google.protobuf.Option options = 9; total_size += 1UL * this->_internal_options_size(); - for (const auto& msg : this->options_) { + for (const auto& msg : this->_impl_.options_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } @@ -1128,11 +1165,11 @@ total_size += 1 + 1; } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Field::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Field::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Field::GetClassData() const { return &_class_data_; } @@ -1150,7 +1187,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - options_.MergeFrom(from.options_); + _impl_.options_.MergeFrom(from._impl_.options_); if (!from._internal_name().empty()) { _internal_set_name(from._internal_name()); } @@ -1197,29 +1234,29 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - options_.InternalSwap(&other->options_); + _impl_.options_.InternalSwap(&other->_impl_.options_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &type_url_, lhs_arena, - &other->type_url_, rhs_arena + &_impl_.type_url_, lhs_arena, + &other->_impl_.type_url_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &json_name_, lhs_arena, - &other->json_name_, rhs_arena + &_impl_.json_name_, lhs_arena, + &other->_impl_.json_name_, rhs_arena ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &default_value_, lhs_arena, - &other->default_value_, rhs_arena + &_impl_.default_value_, lhs_arena, + &other->_impl_.default_value_, rhs_arena ); ::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_FIELD_OFFSET(Field, _impl_.packed_) + + sizeof(Field::_impl_.packed_) + - PROTOBUF_FIELD_OFFSET(Field, _impl_.kind_)>( + reinterpret_cast<char*>(&_impl_.kind_), + reinterpret_cast<char*>(&other->_impl_.kind_)); } ::PROTOBUF_NAMESPACE_ID::Metadata Field::GetMetadata() const { @@ -1237,53 +1274,62 @@ const ::PROTOBUF_NAMESPACE_ID::SourceContext& Enum::_Internal::source_context(const Enum* msg) { - return *msg->source_context_; + return *msg->_impl_.source_context_; } void Enum::clear_source_context() { - if (GetArenaForAllocation() == nullptr && source_context_ != nullptr) { - delete source_context_; + if (GetArenaForAllocation() == nullptr && _impl_.source_context_ != nullptr) { + delete _impl_.source_context_; } - source_context_ = nullptr; + _impl_.source_context_ = nullptr; } Enum::Enum(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - enumvalue_(arena), - options_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Enum) } Enum::Enum(const Enum& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - enumvalue_(from.enumvalue_), - options_(from.options_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.enumvalue_){from._impl_.enumvalue_} + , decltype(_impl_.options_){from._impl_.options_} + , decltype(_impl_.name_){} + , decltype(_impl_.source_context_){nullptr} + , decltype(_impl_.syntax_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_name().empty()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } if (from._internal_has_source_context()) { - source_context_ = new ::PROTOBUF_NAMESPACE_ID::SourceContext(*from.source_context_); - } else { - source_context_ = nullptr; + _impl_.source_context_ = new ::PROTOBUF_NAMESPACE_ID::SourceContext(*from._impl_.source_context_); } - syntax_ = from.syntax_; + _impl_.syntax_ = from._impl_.syntax_; // @@protoc_insertion_point(copy_constructor:google.protobuf.Enum) } -inline void Enum::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( - reinterpret_cast<char*>(&source_context_) - reinterpret_cast<char*>(this)), - 0, static_cast<size_t>(reinterpret_cast<char*>(&syntax_) - - reinterpret_cast<char*>(&source_context_)) + sizeof(syntax_)); +inline void Enum::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.enumvalue_){arena} + , decltype(_impl_.options_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.source_context_){nullptr} + , decltype(_impl_.syntax_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Enum::~Enum() { @@ -1297,12 +1343,14 @@ inline void Enum::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - if (this != internal_default_instance()) delete source_context_; + _impl_.enumvalue_.~RepeatedPtrField(); + _impl_.options_.~RepeatedPtrField(); + _impl_.name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.source_context_; } void Enum::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Enum::Clear() { @@ -1311,14 +1359,14 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - enumvalue_.Clear(); - options_.Clear(); - name_.ClearToEmpty(); - if (GetArenaForAllocation() == nullptr && source_context_ != nullptr) { - delete source_context_; + _impl_.enumvalue_.Clear(); + _impl_.options_.Clear(); + _impl_.name_.ClearToEmpty(); + if (GetArenaForAllocation() == nullptr && _impl_.source_context_ != nullptr) { + delete _impl_.source_context_; } - source_context_ = nullptr; - syntax_ = 0; + _impl_.source_context_ = nullptr; + _impl_.syntax_ = 0; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1468,14 +1516,14 @@ // repeated .google.protobuf.EnumValue enumvalue = 2; total_size += 1UL * this->_internal_enumvalue_size(); - for (const auto& msg : this->enumvalue_) { + for (const auto& msg : this->_impl_.enumvalue_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .google.protobuf.Option options = 3; total_size += 1UL * this->_internal_options_size(); - for (const auto& msg : this->options_) { + for (const auto& msg : this->_impl_.options_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } @@ -1491,7 +1539,7 @@ if (this->_internal_has_source_context()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *source_context_); + *_impl_.source_context_); } // .google.protobuf.Syntax syntax = 5; @@ -1500,11 +1548,11 @@ ::_pbi::WireFormatLite::EnumSize(this->_internal_syntax()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Enum::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Enum::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Enum::GetClassData() const { return &_class_data_; } @@ -1522,8 +1570,8 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - enumvalue_.MergeFrom(from.enumvalue_); - options_.MergeFrom(from.options_); + _impl_.enumvalue_.MergeFrom(from._impl_.enumvalue_); + _impl_.options_.MergeFrom(from._impl_.options_); if (!from._internal_name().empty()) { _internal_set_name(from._internal_name()); } @@ -1552,18 +1600,18 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - enumvalue_.InternalSwap(&other->enumvalue_); - options_.InternalSwap(&other->options_); + _impl_.enumvalue_.InternalSwap(&other->_impl_.enumvalue_); + _impl_.options_.InternalSwap(&other->_impl_.options_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); ::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_FIELD_OFFSET(Enum, _impl_.syntax_) + + sizeof(Enum::_impl_.syntax_) + - PROTOBUF_FIELD_OFFSET(Enum, _impl_.source_context_)>( + reinterpret_cast<char*>(&_impl_.source_context_), + reinterpret_cast<char*>(&other->_impl_.source_context_)); } ::PROTOBUF_NAMESPACE_ID::Metadata Enum::GetMetadata() const { @@ -1580,33 +1628,45 @@ EnumValue::EnumValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) - : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned), - options_(arena) { - SharedCtor(); + : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.EnumValue) } EnumValue::EnumValue(const EnumValue& from) - : ::PROTOBUF_NAMESPACE_ID::Message(), - options_(from.options_) { + : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.options_){from._impl_.options_} + , decltype(_impl_.name_){} + , decltype(_impl_.number_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_name().empty()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } - number_ = from.number_; + _impl_.number_ = from._impl_.number_; // @@protoc_insertion_point(copy_constructor:google.protobuf.EnumValue) } -inline void EnumValue::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -number_ = 0; +inline void EnumValue::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.options_){arena} + , decltype(_impl_.name_){} + , decltype(_impl_.number_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } EnumValue::~EnumValue() { @@ -1620,11 +1680,12 @@ inline void EnumValue::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); + _impl_.options_.~RepeatedPtrField(); + _impl_.name_.Destroy(); } void EnumValue::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void EnumValue::Clear() { @@ -1633,9 +1694,9 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - options_.Clear(); - name_.ClearToEmpty(); - number_ = 0; + _impl_.options_.Clear(); + _impl_.name_.ClearToEmpty(); + _impl_.number_ = 0; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1658,7 +1719,7 @@ // int32 number = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 16)) { - number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.number_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -1747,7 +1808,7 @@ // repeated .google.protobuf.Option options = 3; total_size += 1UL * this->_internal_options_size(); - for (const auto& msg : this->options_) { + for (const auto& msg : this->_impl_.options_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } @@ -1764,11 +1825,11 @@ total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_number()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData EnumValue::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, EnumValue::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*EnumValue::GetClassData() const { return &_class_data_; } @@ -1786,7 +1847,7 @@ uint32_t cached_has_bits = 0; (void) cached_has_bits; - options_.MergeFrom(from.options_); + _impl_.options_.MergeFrom(from._impl_.options_); if (!from._internal_name().empty()) { _internal_set_name(from._internal_name()); } @@ -1812,12 +1873,12 @@ auto* lhs_arena = GetArenaForAllocation(); auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); - options_.InternalSwap(&other->options_); + _impl_.options_.InternalSwap(&other->_impl_.options_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); - swap(number_, other->number_); + swap(_impl_.number_, other->_impl_.number_); } ::PROTOBUF_NAMESPACE_ID::Metadata EnumValue::GetMetadata() const { @@ -1835,45 +1896,55 @@ const ::PROTOBUF_NAMESPACE_ID::Any& Option::_Internal::value(const Option* msg) { - return *msg->value_; + return *msg->_impl_.value_; } void Option::clear_value() { - if (GetArenaForAllocation() == nullptr && value_ != nullptr) { - delete value_; + if (GetArenaForAllocation() == nullptr && _impl_.value_ != nullptr) { + delete _impl_.value_; } - value_ = nullptr; + _impl_.value_ = nullptr; } Option::Option(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Option) } Option::Option(const Option& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.name_){} + , decltype(_impl_.value_){nullptr} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - name_.InitDefault(); + _impl_.name_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); + _impl_.name_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_name().empty()) { - name_.Set(from._internal_name(), + _impl_.name_.Set(from._internal_name(), GetArenaForAllocation()); } if (from._internal_has_value()) { - value_ = new ::PROTOBUF_NAMESPACE_ID::Any(*from.value_); - } else { - value_ = nullptr; + _impl_.value_ = new ::PROTOBUF_NAMESPACE_ID::Any(*from._impl_.value_); } // @@protoc_insertion_point(copy_constructor:google.protobuf.Option) } -inline void Option::SharedCtor() { -name_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - name_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING -value_ = nullptr; +inline void Option::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.name_){} + , decltype(_impl_.value_){nullptr} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.name_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.name_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } Option::~Option() { @@ -1887,12 +1958,12 @@ inline void Option::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - name_.Destroy(); - if (this != internal_default_instance()) delete value_; + _impl_.name_.Destroy(); + if (this != internal_default_instance()) delete _impl_.value_; } void Option::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Option::Clear() { @@ -1901,11 +1972,11 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - name_.ClearToEmpty(); - if (GetArenaForAllocation() == nullptr && value_ != nullptr) { - delete value_; + _impl_.name_.ClearToEmpty(); + if (GetArenaForAllocation() == nullptr && _impl_.value_ != nullptr) { + delete _impl_.value_; } - value_ = nullptr; + _impl_.value_ = nullptr; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -2006,14 +2077,14 @@ if (this->_internal_has_value()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( - *value_); + *_impl_.value_); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Option::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Option::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Option::GetClassData() const { return &_class_data_; } @@ -2057,10 +2128,10 @@ auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &name_, lhs_arena, - &other->name_, rhs_arena + &_impl_.name_, lhs_arena, + &other->_impl_.name_, rhs_arena ); - swap(value_, other->value_); + swap(_impl_.value_, other->_impl_.value_); } ::PROTOBUF_NAMESPACE_ID::Metadata Option::GetMetadata() const {
diff --git a/src/google/protobuf/type.pb.h b/src/google/protobuf/type.pb.h index 69c2abc..57e98d1 100644 --- a/src/google/protobuf/type.pb.h +++ b/src/google/protobuf/type.pb.h
@@ -260,10 +260,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Type* other); @@ -403,13 +403,16 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Field > fields_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> oneofs_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; - ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; - int syntax_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Field > fields_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string> oneofs_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; + int syntax_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; }; // ------------------------------------------------------------------- @@ -505,10 +508,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Field* other); @@ -768,17 +771,20 @@ 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 type_url_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr json_name_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr default_value_; - int kind_; - int cardinality_; - int32_t number_; - int32_t oneof_index_; - bool packed_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr type_url_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr json_name_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr default_value_; + int kind_; + int cardinality_; + int32_t number_; + int32_t oneof_index_; + bool packed_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; }; // ------------------------------------------------------------------- @@ -874,10 +880,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Enum* other); @@ -992,12 +998,15 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValue > enumvalue_; - ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; - ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; - int syntax_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValue > enumvalue_; + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context_; + int syntax_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; }; // ------------------------------------------------------------------- @@ -1093,10 +1102,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(EnumValue* other); @@ -1173,10 +1182,13 @@ 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_; - int32_t number_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option > options_; + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + int32_t number_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; }; // ------------------------------------------------------------------- @@ -1272,10 +1284,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Option* other); @@ -1342,9 +1354,12 @@ 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::Any* value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr name_; + ::PROTOBUF_NAMESPACE_ID::Any* value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2ftype_2eproto; }; // =================================================================== @@ -1360,7 +1375,7 @@ // string name = 1; inline void Type::clear_name() { - name_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); } inline const std::string& Type::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Type.name) @@ -1370,7 +1385,7 @@ inline PROTOBUF_ALWAYS_INLINE void Type::set_name(ArgT0&& arg0, ArgT... args) { - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Type.name) } inline std::string* Type::mutable_name() { @@ -1379,19 +1394,19 @@ return _s; } inline const std::string& Type::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void Type::_internal_set_name(const std::string& value) { - name_.Set(value, GetArenaForAllocation()); + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* Type::_internal_mutable_name() { - return name_.Mutable(GetArenaForAllocation()); + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* Type::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Type.name) - return name_.Release(); + return _impl_.name_.Release(); } inline void Type::set_allocated_name(std::string* name) { if (name != nullptr) { @@ -1399,10 +1414,10 @@ } else { } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.name) @@ -1410,32 +1425,32 @@ // repeated .google.protobuf.Field fields = 2; inline int Type::_internal_fields_size() const { - return fields_.size(); + return _impl_.fields_.size(); } inline int Type::fields_size() const { return _internal_fields_size(); } inline void Type::clear_fields() { - fields_.Clear(); + _impl_.fields_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::Field* Type::mutable_fields(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Type.fields) - return fields_.Mutable(index); + return _impl_.fields_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Field >* Type::mutable_fields() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.fields) - return &fields_; + return &_impl_.fields_; } inline const ::PROTOBUF_NAMESPACE_ID::Field& Type::_internal_fields(int index) const { - return fields_.Get(index); + return _impl_.fields_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Field& Type::fields(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Type.fields) return _internal_fields(index); } inline ::PROTOBUF_NAMESPACE_ID::Field* Type::_internal_add_fields() { - return fields_.Add(); + return _impl_.fields_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Field* Type::add_fields() { ::PROTOBUF_NAMESPACE_ID::Field* _add = _internal_add_fields(); @@ -1445,18 +1460,18 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Field >& Type::fields() const { // @@protoc_insertion_point(field_list:google.protobuf.Type.fields) - return fields_; + return _impl_.fields_; } // repeated string oneofs = 3; inline int Type::_internal_oneofs_size() const { - return oneofs_.size(); + return _impl_.oneofs_.size(); } inline int Type::oneofs_size() const { return _internal_oneofs_size(); } inline void Type::clear_oneofs() { - oneofs_.Clear(); + _impl_.oneofs_.Clear(); } inline std::string* Type::add_oneofs() { std::string* _s = _internal_add_oneofs(); @@ -1464,7 +1479,7 @@ return _s; } inline const std::string& Type::_internal_oneofs(int index) const { - return oneofs_.Get(index); + return _impl_.oneofs_.Get(index); } inline const std::string& Type::oneofs(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Type.oneofs) @@ -1472,85 +1487,85 @@ } inline std::string* Type::mutable_oneofs(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Type.oneofs) - return oneofs_.Mutable(index); + return _impl_.oneofs_.Mutable(index); } inline void Type::set_oneofs(int index, const std::string& value) { - oneofs_.Mutable(index)->assign(value); + _impl_.oneofs_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set:google.protobuf.Type.oneofs) } inline void Type::set_oneofs(int index, std::string&& value) { - oneofs_.Mutable(index)->assign(std::move(value)); + _impl_.oneofs_.Mutable(index)->assign(std::move(value)); // @@protoc_insertion_point(field_set:google.protobuf.Type.oneofs) } inline void Type::set_oneofs(int index, const char* value) { GOOGLE_DCHECK(value != nullptr); - oneofs_.Mutable(index)->assign(value); + _impl_.oneofs_.Mutable(index)->assign(value); // @@protoc_insertion_point(field_set_char:google.protobuf.Type.oneofs) } inline void Type::set_oneofs(int index, const char* value, size_t size) { - oneofs_.Mutable(index)->assign( + _impl_.oneofs_.Mutable(index)->assign( reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_set_pointer:google.protobuf.Type.oneofs) } inline std::string* Type::_internal_add_oneofs() { - return oneofs_.Add(); + return _impl_.oneofs_.Add(); } inline void Type::add_oneofs(const std::string& value) { - oneofs_.Add()->assign(value); + _impl_.oneofs_.Add()->assign(value); // @@protoc_insertion_point(field_add:google.protobuf.Type.oneofs) } inline void Type::add_oneofs(std::string&& value) { - oneofs_.Add(std::move(value)); + _impl_.oneofs_.Add(std::move(value)); // @@protoc_insertion_point(field_add:google.protobuf.Type.oneofs) } inline void Type::add_oneofs(const char* value) { GOOGLE_DCHECK(value != nullptr); - oneofs_.Add()->assign(value); + _impl_.oneofs_.Add()->assign(value); // @@protoc_insertion_point(field_add_char:google.protobuf.Type.oneofs) } inline void Type::add_oneofs(const char* value, size_t size) { - oneofs_.Add()->assign(reinterpret_cast<const char*>(value), size); + _impl_.oneofs_.Add()->assign(reinterpret_cast<const char*>(value), size); // @@protoc_insertion_point(field_add_pointer:google.protobuf.Type.oneofs) } inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>& Type::oneofs() const { // @@protoc_insertion_point(field_list:google.protobuf.Type.oneofs) - return oneofs_; + return _impl_.oneofs_; } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField<std::string>* Type::mutable_oneofs() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.oneofs) - return &oneofs_; + return &_impl_.oneofs_; } // repeated .google.protobuf.Option options = 4; inline int Type::_internal_options_size() const { - return options_.size(); + return _impl_.options_.size(); } inline int Type::options_size() const { return _internal_options_size(); } inline void Type::clear_options() { - options_.Clear(); + _impl_.options_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Type::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Type.options) - return options_.Mutable(index); + return _impl_.options_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* Type::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Type.options) - return &options_; + return &_impl_.options_; } inline const ::PROTOBUF_NAMESPACE_ID::Option& Type::_internal_options(int index) const { - return options_.Get(index); + return _impl_.options_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Option& Type::options(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Type.options) return _internal_options(index); } inline ::PROTOBUF_NAMESPACE_ID::Option* Type::_internal_add_options() { - return options_.Add(); + return _impl_.options_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Type::add_options() { ::PROTOBUF_NAMESPACE_ID::Option* _add = _internal_add_options(); @@ -1560,18 +1575,18 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& Type::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Type.options) - return options_; + return _impl_.options_; } // .google.protobuf.SourceContext source_context = 5; inline bool Type::_internal_has_source_context() const { - return this != internal_default_instance() && source_context_ != nullptr; + return this != internal_default_instance() && _impl_.source_context_ != nullptr; } inline bool Type::has_source_context() const { return _internal_has_source_context(); } inline const ::PROTOBUF_NAMESPACE_ID::SourceContext& Type::_internal_source_context() const { - const ::PROTOBUF_NAMESPACE_ID::SourceContext* p = source_context_; + const ::PROTOBUF_NAMESPACE_ID::SourceContext* p = _impl_.source_context_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::SourceContext&>( ::PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_); } @@ -1582,9 +1597,9 @@ inline void Type::unsafe_arena_set_allocated_source_context( ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_context_); } - source_context_ = source_context; + _impl_.source_context_ = source_context; if (source_context) { } else { @@ -1594,8 +1609,8 @@ } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Type::release_source_context() { - ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_; - source_context_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = _impl_.source_context_; + _impl_.source_context_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -1610,17 +1625,17 @@ inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Type::unsafe_arena_release_source_context() { // @@protoc_insertion_point(field_release:google.protobuf.Type.source_context) - ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_; - source_context_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = _impl_.source_context_; + _impl_.source_context_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Type::_internal_mutable_source_context() { - if (source_context_ == nullptr) { + if (_impl_.source_context_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::SourceContext>(GetArenaForAllocation()); - source_context_ = p; + _impl_.source_context_ = p; } - return source_context_; + return _impl_.source_context_; } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Type::mutable_source_context() { ::PROTOBUF_NAMESPACE_ID::SourceContext* _msg = _internal_mutable_source_context(); @@ -1630,7 +1645,7 @@ inline void Type::set_allocated_source_context(::PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_context_); } if (source_context) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -1644,16 +1659,16 @@ } else { } - source_context_ = source_context; + _impl_.source_context_ = source_context; // @@protoc_insertion_point(field_set_allocated:google.protobuf.Type.source_context) } // .google.protobuf.Syntax syntax = 6; inline void Type::clear_syntax() { - syntax_ = 0; + _impl_.syntax_ = 0; } inline ::PROTOBUF_NAMESPACE_ID::Syntax Type::_internal_syntax() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(syntax_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(_impl_.syntax_); } inline ::PROTOBUF_NAMESPACE_ID::Syntax Type::syntax() const { // @@protoc_insertion_point(field_get:google.protobuf.Type.syntax) @@ -1661,7 +1676,7 @@ } inline void Type::_internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { - syntax_ = value; + _impl_.syntax_ = value; } inline void Type::set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { _internal_set_syntax(value); @@ -1674,10 +1689,10 @@ // .google.protobuf.Field.Kind kind = 1; inline void Field::clear_kind() { - kind_ = 0; + _impl_.kind_ = 0; } inline ::PROTOBUF_NAMESPACE_ID::Field_Kind Field::_internal_kind() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::Field_Kind >(kind_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::Field_Kind >(_impl_.kind_); } inline ::PROTOBUF_NAMESPACE_ID::Field_Kind Field::kind() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.kind) @@ -1685,7 +1700,7 @@ } inline void Field::_internal_set_kind(::PROTOBUF_NAMESPACE_ID::Field_Kind value) { - kind_ = value; + _impl_.kind_ = value; } inline void Field::set_kind(::PROTOBUF_NAMESPACE_ID::Field_Kind value) { _internal_set_kind(value); @@ -1694,10 +1709,10 @@ // .google.protobuf.Field.Cardinality cardinality = 2; inline void Field::clear_cardinality() { - cardinality_ = 0; + _impl_.cardinality_ = 0; } inline ::PROTOBUF_NAMESPACE_ID::Field_Cardinality Field::_internal_cardinality() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::Field_Cardinality >(cardinality_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::Field_Cardinality >(_impl_.cardinality_); } inline ::PROTOBUF_NAMESPACE_ID::Field_Cardinality Field::cardinality() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.cardinality) @@ -1705,7 +1720,7 @@ } inline void Field::_internal_set_cardinality(::PROTOBUF_NAMESPACE_ID::Field_Cardinality value) { - cardinality_ = value; + _impl_.cardinality_ = value; } inline void Field::set_cardinality(::PROTOBUF_NAMESPACE_ID::Field_Cardinality value) { _internal_set_cardinality(value); @@ -1714,10 +1729,10 @@ // int32 number = 3; inline void Field::clear_number() { - number_ = 0; + _impl_.number_ = 0; } inline int32_t Field::_internal_number() const { - return number_; + return _impl_.number_; } inline int32_t Field::number() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.number) @@ -1725,7 +1740,7 @@ } inline void Field::_internal_set_number(int32_t value) { - number_ = value; + _impl_.number_ = value; } inline void Field::set_number(int32_t value) { _internal_set_number(value); @@ -1734,7 +1749,7 @@ // string name = 4; inline void Field::clear_name() { - name_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); } inline const std::string& Field::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.name) @@ -1744,7 +1759,7 @@ inline PROTOBUF_ALWAYS_INLINE void Field::set_name(ArgT0&& arg0, ArgT... args) { - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Field.name) } inline std::string* Field::mutable_name() { @@ -1753,19 +1768,19 @@ return _s; } inline const std::string& Field::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void Field::_internal_set_name(const std::string& value) { - name_.Set(value, GetArenaForAllocation()); + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* Field::_internal_mutable_name() { - return name_.Mutable(GetArenaForAllocation()); + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* Field::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Field.name) - return name_.Release(); + return _impl_.name_.Release(); } inline void Field::set_allocated_name(std::string* name) { if (name != nullptr) { @@ -1773,10 +1788,10 @@ } else { } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.name) @@ -1784,7 +1799,7 @@ // string type_url = 6; inline void Field::clear_type_url() { - type_url_.ClearToEmpty(); + _impl_.type_url_.ClearToEmpty(); } inline const std::string& Field::type_url() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.type_url) @@ -1794,7 +1809,7 @@ inline PROTOBUF_ALWAYS_INLINE void Field::set_type_url(ArgT0&& arg0, ArgT... args) { - type_url_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.type_url_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Field.type_url) } inline std::string* Field::mutable_type_url() { @@ -1803,19 +1818,19 @@ return _s; } inline const std::string& Field::_internal_type_url() const { - return type_url_.Get(); + return _impl_.type_url_.Get(); } inline void Field::_internal_set_type_url(const std::string& value) { - type_url_.Set(value, GetArenaForAllocation()); + _impl_.type_url_.Set(value, GetArenaForAllocation()); } inline std::string* Field::_internal_mutable_type_url() { - return type_url_.Mutable(GetArenaForAllocation()); + return _impl_.type_url_.Mutable(GetArenaForAllocation()); } inline std::string* Field::release_type_url() { // @@protoc_insertion_point(field_release:google.protobuf.Field.type_url) - return type_url_.Release(); + return _impl_.type_url_.Release(); } inline void Field::set_allocated_type_url(std::string* type_url) { if (type_url != nullptr) { @@ -1823,10 +1838,10 @@ } else { } - type_url_.SetAllocated(type_url, GetArenaForAllocation()); + _impl_.type_url_.SetAllocated(type_url, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (type_url_.IsDefault()) { - type_url_.Set("", GetArenaForAllocation()); + if (_impl_.type_url_.IsDefault()) { + _impl_.type_url_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.type_url) @@ -1834,10 +1849,10 @@ // int32 oneof_index = 7; inline void Field::clear_oneof_index() { - oneof_index_ = 0; + _impl_.oneof_index_ = 0; } inline int32_t Field::_internal_oneof_index() const { - return oneof_index_; + return _impl_.oneof_index_; } inline int32_t Field::oneof_index() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.oneof_index) @@ -1845,7 +1860,7 @@ } inline void Field::_internal_set_oneof_index(int32_t value) { - oneof_index_ = value; + _impl_.oneof_index_ = value; } inline void Field::set_oneof_index(int32_t value) { _internal_set_oneof_index(value); @@ -1854,10 +1869,10 @@ // bool packed = 8; inline void Field::clear_packed() { - packed_ = false; + _impl_.packed_ = false; } inline bool Field::_internal_packed() const { - return packed_; + return _impl_.packed_; } inline bool Field::packed() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.packed) @@ -1865,7 +1880,7 @@ } inline void Field::_internal_set_packed(bool value) { - packed_ = value; + _impl_.packed_ = value; } inline void Field::set_packed(bool value) { _internal_set_packed(value); @@ -1874,32 +1889,32 @@ // repeated .google.protobuf.Option options = 9; inline int Field::_internal_options_size() const { - return options_.size(); + return _impl_.options_.size(); } inline int Field::options_size() const { return _internal_options_size(); } inline void Field::clear_options() { - options_.Clear(); + _impl_.options_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Field::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Field.options) - return options_.Mutable(index); + return _impl_.options_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* Field::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Field.options) - return &options_; + return &_impl_.options_; } inline const ::PROTOBUF_NAMESPACE_ID::Option& Field::_internal_options(int index) const { - return options_.Get(index); + return _impl_.options_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Option& Field::options(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Field.options) return _internal_options(index); } inline ::PROTOBUF_NAMESPACE_ID::Option* Field::_internal_add_options() { - return options_.Add(); + return _impl_.options_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Field::add_options() { ::PROTOBUF_NAMESPACE_ID::Option* _add = _internal_add_options(); @@ -1909,12 +1924,12 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& Field::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Field.options) - return options_; + return _impl_.options_; } // string json_name = 10; inline void Field::clear_json_name() { - json_name_.ClearToEmpty(); + _impl_.json_name_.ClearToEmpty(); } inline const std::string& Field::json_name() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.json_name) @@ -1924,7 +1939,7 @@ inline PROTOBUF_ALWAYS_INLINE void Field::set_json_name(ArgT0&& arg0, ArgT... args) { - json_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.json_name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Field.json_name) } inline std::string* Field::mutable_json_name() { @@ -1933,19 +1948,19 @@ return _s; } inline const std::string& Field::_internal_json_name() const { - return json_name_.Get(); + return _impl_.json_name_.Get(); } inline void Field::_internal_set_json_name(const std::string& value) { - json_name_.Set(value, GetArenaForAllocation()); + _impl_.json_name_.Set(value, GetArenaForAllocation()); } inline std::string* Field::_internal_mutable_json_name() { - return json_name_.Mutable(GetArenaForAllocation()); + return _impl_.json_name_.Mutable(GetArenaForAllocation()); } inline std::string* Field::release_json_name() { // @@protoc_insertion_point(field_release:google.protobuf.Field.json_name) - return json_name_.Release(); + return _impl_.json_name_.Release(); } inline void Field::set_allocated_json_name(std::string* json_name) { if (json_name != nullptr) { @@ -1953,10 +1968,10 @@ } else { } - json_name_.SetAllocated(json_name, GetArenaForAllocation()); + _impl_.json_name_.SetAllocated(json_name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (json_name_.IsDefault()) { - json_name_.Set("", GetArenaForAllocation()); + if (_impl_.json_name_.IsDefault()) { + _impl_.json_name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.json_name) @@ -1964,7 +1979,7 @@ // string default_value = 11; inline void Field::clear_default_value() { - default_value_.ClearToEmpty(); + _impl_.default_value_.ClearToEmpty(); } inline const std::string& Field::default_value() const { // @@protoc_insertion_point(field_get:google.protobuf.Field.default_value) @@ -1974,7 +1989,7 @@ inline PROTOBUF_ALWAYS_INLINE void Field::set_default_value(ArgT0&& arg0, ArgT... args) { - default_value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.default_value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Field.default_value) } inline std::string* Field::mutable_default_value() { @@ -1983,19 +1998,19 @@ return _s; } inline const std::string& Field::_internal_default_value() const { - return default_value_.Get(); + return _impl_.default_value_.Get(); } inline void Field::_internal_set_default_value(const std::string& value) { - default_value_.Set(value, GetArenaForAllocation()); + _impl_.default_value_.Set(value, GetArenaForAllocation()); } inline std::string* Field::_internal_mutable_default_value() { - return default_value_.Mutable(GetArenaForAllocation()); + return _impl_.default_value_.Mutable(GetArenaForAllocation()); } inline std::string* Field::release_default_value() { // @@protoc_insertion_point(field_release:google.protobuf.Field.default_value) - return default_value_.Release(); + return _impl_.default_value_.Release(); } inline void Field::set_allocated_default_value(std::string* default_value) { if (default_value != nullptr) { @@ -2003,10 +2018,10 @@ } else { } - default_value_.SetAllocated(default_value, GetArenaForAllocation()); + _impl_.default_value_.SetAllocated(default_value, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (default_value_.IsDefault()) { - default_value_.Set("", GetArenaForAllocation()); + if (_impl_.default_value_.IsDefault()) { + _impl_.default_value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Field.default_value) @@ -2018,7 +2033,7 @@ // string name = 1; inline void Enum::clear_name() { - name_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); } inline const std::string& Enum::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Enum.name) @@ -2028,7 +2043,7 @@ inline PROTOBUF_ALWAYS_INLINE void Enum::set_name(ArgT0&& arg0, ArgT... args) { - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Enum.name) } inline std::string* Enum::mutable_name() { @@ -2037,19 +2052,19 @@ return _s; } inline const std::string& Enum::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void Enum::_internal_set_name(const std::string& value) { - name_.Set(value, GetArenaForAllocation()); + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* Enum::_internal_mutable_name() { - return name_.Mutable(GetArenaForAllocation()); + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* Enum::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Enum.name) - return name_.Release(); + return _impl_.name_.Release(); } inline void Enum::set_allocated_name(std::string* name) { if (name != nullptr) { @@ -2057,10 +2072,10 @@ } else { } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.name) @@ -2068,32 +2083,32 @@ // repeated .google.protobuf.EnumValue enumvalue = 2; inline int Enum::_internal_enumvalue_size() const { - return enumvalue_.size(); + return _impl_.enumvalue_.size(); } inline int Enum::enumvalue_size() const { return _internal_enumvalue_size(); } inline void Enum::clear_enumvalue() { - enumvalue_.Clear(); + _impl_.enumvalue_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::EnumValue* Enum::mutable_enumvalue(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Enum.enumvalue) - return enumvalue_.Mutable(index); + return _impl_.enumvalue_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValue >* Enum::mutable_enumvalue() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Enum.enumvalue) - return &enumvalue_; + return &_impl_.enumvalue_; } inline const ::PROTOBUF_NAMESPACE_ID::EnumValue& Enum::_internal_enumvalue(int index) const { - return enumvalue_.Get(index); + return _impl_.enumvalue_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::EnumValue& Enum::enumvalue(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Enum.enumvalue) return _internal_enumvalue(index); } inline ::PROTOBUF_NAMESPACE_ID::EnumValue* Enum::_internal_add_enumvalue() { - return enumvalue_.Add(); + return _impl_.enumvalue_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::EnumValue* Enum::add_enumvalue() { ::PROTOBUF_NAMESPACE_ID::EnumValue* _add = _internal_add_enumvalue(); @@ -2103,37 +2118,37 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::EnumValue >& Enum::enumvalue() const { // @@protoc_insertion_point(field_list:google.protobuf.Enum.enumvalue) - return enumvalue_; + return _impl_.enumvalue_; } // repeated .google.protobuf.Option options = 3; inline int Enum::_internal_options_size() const { - return options_.size(); + return _impl_.options_.size(); } inline int Enum::options_size() const { return _internal_options_size(); } inline void Enum::clear_options() { - options_.Clear(); + _impl_.options_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Enum::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.Enum.options) - return options_.Mutable(index); + return _impl_.options_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* Enum::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.Enum.options) - return &options_; + return &_impl_.options_; } inline const ::PROTOBUF_NAMESPACE_ID::Option& Enum::_internal_options(int index) const { - return options_.Get(index); + return _impl_.options_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Option& Enum::options(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.Enum.options) return _internal_options(index); } inline ::PROTOBUF_NAMESPACE_ID::Option* Enum::_internal_add_options() { - return options_.Add(); + return _impl_.options_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Option* Enum::add_options() { ::PROTOBUF_NAMESPACE_ID::Option* _add = _internal_add_options(); @@ -2143,18 +2158,18 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& Enum::options() const { // @@protoc_insertion_point(field_list:google.protobuf.Enum.options) - return options_; + return _impl_.options_; } // .google.protobuf.SourceContext source_context = 4; inline bool Enum::_internal_has_source_context() const { - return this != internal_default_instance() && source_context_ != nullptr; + return this != internal_default_instance() && _impl_.source_context_ != nullptr; } inline bool Enum::has_source_context() const { return _internal_has_source_context(); } inline const ::PROTOBUF_NAMESPACE_ID::SourceContext& Enum::_internal_source_context() const { - const ::PROTOBUF_NAMESPACE_ID::SourceContext* p = source_context_; + const ::PROTOBUF_NAMESPACE_ID::SourceContext* p = _impl_.source_context_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::SourceContext&>( ::PROTOBUF_NAMESPACE_ID::_SourceContext_default_instance_); } @@ -2165,9 +2180,9 @@ inline void Enum::unsafe_arena_set_allocated_source_context( ::PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_context_); } - source_context_ = source_context; + _impl_.source_context_ = source_context; if (source_context) { } else { @@ -2177,8 +2192,8 @@ } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Enum::release_source_context() { - ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_; - source_context_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = _impl_.source_context_; + _impl_.source_context_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -2193,17 +2208,17 @@ inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Enum::unsafe_arena_release_source_context() { // @@protoc_insertion_point(field_release:google.protobuf.Enum.source_context) - ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = source_context_; - source_context_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::SourceContext* temp = _impl_.source_context_; + _impl_.source_context_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Enum::_internal_mutable_source_context() { - if (source_context_ == nullptr) { + if (_impl_.source_context_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::SourceContext>(GetArenaForAllocation()); - source_context_ = p; + _impl_.source_context_ = p; } - return source_context_; + return _impl_.source_context_; } inline ::PROTOBUF_NAMESPACE_ID::SourceContext* Enum::mutable_source_context() { ::PROTOBUF_NAMESPACE_ID::SourceContext* _msg = _internal_mutable_source_context(); @@ -2213,7 +2228,7 @@ inline void Enum::set_allocated_source_context(::PROTOBUF_NAMESPACE_ID::SourceContext* source_context) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(source_context_); + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.source_context_); } if (source_context) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -2227,16 +2242,16 @@ } else { } - source_context_ = source_context; + _impl_.source_context_ = source_context; // @@protoc_insertion_point(field_set_allocated:google.protobuf.Enum.source_context) } // .google.protobuf.Syntax syntax = 5; inline void Enum::clear_syntax() { - syntax_ = 0; + _impl_.syntax_ = 0; } inline ::PROTOBUF_NAMESPACE_ID::Syntax Enum::_internal_syntax() const { - return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(syntax_); + return static_cast< ::PROTOBUF_NAMESPACE_ID::Syntax >(_impl_.syntax_); } inline ::PROTOBUF_NAMESPACE_ID::Syntax Enum::syntax() const { // @@protoc_insertion_point(field_get:google.protobuf.Enum.syntax) @@ -2244,7 +2259,7 @@ } inline void Enum::_internal_set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { - syntax_ = value; + _impl_.syntax_ = value; } inline void Enum::set_syntax(::PROTOBUF_NAMESPACE_ID::Syntax value) { _internal_set_syntax(value); @@ -2257,7 +2272,7 @@ // string name = 1; inline void EnumValue::clear_name() { - name_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); } inline const std::string& EnumValue::name() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValue.name) @@ -2267,7 +2282,7 @@ inline PROTOBUF_ALWAYS_INLINE void EnumValue::set_name(ArgT0&& arg0, ArgT... args) { - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.EnumValue.name) } inline std::string* EnumValue::mutable_name() { @@ -2276,19 +2291,19 @@ return _s; } inline const std::string& EnumValue::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void EnumValue::_internal_set_name(const std::string& value) { - name_.Set(value, GetArenaForAllocation()); + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* EnumValue::_internal_mutable_name() { - return name_.Mutable(GetArenaForAllocation()); + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* EnumValue::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.EnumValue.name) - return name_.Release(); + return _impl_.name_.Release(); } inline void EnumValue::set_allocated_name(std::string* name) { if (name != nullptr) { @@ -2296,10 +2311,10 @@ } else { } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.EnumValue.name) @@ -2307,10 +2322,10 @@ // int32 number = 2; inline void EnumValue::clear_number() { - number_ = 0; + _impl_.number_ = 0; } inline int32_t EnumValue::_internal_number() const { - return number_; + return _impl_.number_; } inline int32_t EnumValue::number() const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValue.number) @@ -2318,7 +2333,7 @@ } inline void EnumValue::_internal_set_number(int32_t value) { - number_ = value; + _impl_.number_ = value; } inline void EnumValue::set_number(int32_t value) { _internal_set_number(value); @@ -2327,32 +2342,32 @@ // repeated .google.protobuf.Option options = 3; inline int EnumValue::_internal_options_size() const { - return options_.size(); + return _impl_.options_.size(); } inline int EnumValue::options_size() const { return _internal_options_size(); } inline void EnumValue::clear_options() { - options_.Clear(); + _impl_.options_.Clear(); } inline ::PROTOBUF_NAMESPACE_ID::Option* EnumValue::mutable_options(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.EnumValue.options) - return options_.Mutable(index); + return _impl_.options_.Mutable(index); } inline ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >* EnumValue::mutable_options() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.EnumValue.options) - return &options_; + return &_impl_.options_; } inline const ::PROTOBUF_NAMESPACE_ID::Option& EnumValue::_internal_options(int index) const { - return options_.Get(index); + return _impl_.options_.Get(index); } inline const ::PROTOBUF_NAMESPACE_ID::Option& EnumValue::options(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.EnumValue.options) return _internal_options(index); } inline ::PROTOBUF_NAMESPACE_ID::Option* EnumValue::_internal_add_options() { - return options_.Add(); + return _impl_.options_.Add(); } inline ::PROTOBUF_NAMESPACE_ID::Option* EnumValue::add_options() { ::PROTOBUF_NAMESPACE_ID::Option* _add = _internal_add_options(); @@ -2362,7 +2377,7 @@ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedPtrField< ::PROTOBUF_NAMESPACE_ID::Option >& EnumValue::options() const { // @@protoc_insertion_point(field_list:google.protobuf.EnumValue.options) - return options_; + return _impl_.options_; } // ------------------------------------------------------------------- @@ -2371,7 +2386,7 @@ // string name = 1; inline void Option::clear_name() { - name_.ClearToEmpty(); + _impl_.name_.ClearToEmpty(); } inline const std::string& Option::name() const { // @@protoc_insertion_point(field_get:google.protobuf.Option.name) @@ -2381,7 +2396,7 @@ inline PROTOBUF_ALWAYS_INLINE void Option::set_name(ArgT0&& arg0, ArgT... args) { - name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.name_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.Option.name) } inline std::string* Option::mutable_name() { @@ -2390,19 +2405,19 @@ return _s; } inline const std::string& Option::_internal_name() const { - return name_.Get(); + return _impl_.name_.Get(); } inline void Option::_internal_set_name(const std::string& value) { - name_.Set(value, GetArenaForAllocation()); + _impl_.name_.Set(value, GetArenaForAllocation()); } inline std::string* Option::_internal_mutable_name() { - return name_.Mutable(GetArenaForAllocation()); + return _impl_.name_.Mutable(GetArenaForAllocation()); } inline std::string* Option::release_name() { // @@protoc_insertion_point(field_release:google.protobuf.Option.name) - return name_.Release(); + return _impl_.name_.Release(); } inline void Option::set_allocated_name(std::string* name) { if (name != nullptr) { @@ -2410,10 +2425,10 @@ } else { } - name_.SetAllocated(name, GetArenaForAllocation()); + _impl_.name_.SetAllocated(name, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (name_.IsDefault()) { - name_.Set("", GetArenaForAllocation()); + if (_impl_.name_.IsDefault()) { + _impl_.name_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.name) @@ -2421,13 +2436,13 @@ // .google.protobuf.Any value = 2; inline bool Option::_internal_has_value() const { - return this != internal_default_instance() && value_ != nullptr; + return this != internal_default_instance() && _impl_.value_ != nullptr; } inline bool Option::has_value() const { return _internal_has_value(); } inline const ::PROTOBUF_NAMESPACE_ID::Any& Option::_internal_value() const { - const ::PROTOBUF_NAMESPACE_ID::Any* p = value_; + const ::PROTOBUF_NAMESPACE_ID::Any* p = _impl_.value_; return p != nullptr ? *p : reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Any&>( ::PROTOBUF_NAMESPACE_ID::_Any_default_instance_); } @@ -2438,9 +2453,9 @@ inline void Option::unsafe_arena_set_allocated_value( ::PROTOBUF_NAMESPACE_ID::Any* value) { if (GetArenaForAllocation() == nullptr) { - delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(value_); + delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.value_); } - value_ = value; + _impl_.value_ = value; if (value) { } else { @@ -2450,8 +2465,8 @@ } inline ::PROTOBUF_NAMESPACE_ID::Any* Option::release_value() { - ::PROTOBUF_NAMESPACE_ID::Any* temp = value_; - value_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::Any* temp = _impl_.value_; + _impl_.value_ = nullptr; #ifdef PROTOBUF_FORCE_COPY_IN_RELEASE auto* old = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(temp); temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); @@ -2466,17 +2481,17 @@ inline ::PROTOBUF_NAMESPACE_ID::Any* Option::unsafe_arena_release_value() { // @@protoc_insertion_point(field_release:google.protobuf.Option.value) - ::PROTOBUF_NAMESPACE_ID::Any* temp = value_; - value_ = nullptr; + ::PROTOBUF_NAMESPACE_ID::Any* temp = _impl_.value_; + _impl_.value_ = nullptr; return temp; } inline ::PROTOBUF_NAMESPACE_ID::Any* Option::_internal_mutable_value() { - if (value_ == nullptr) { + if (_impl_.value_ == nullptr) { auto* p = CreateMaybeMessage<::PROTOBUF_NAMESPACE_ID::Any>(GetArenaForAllocation()); - value_ = p; + _impl_.value_ = p; } - return value_; + return _impl_.value_; } inline ::PROTOBUF_NAMESPACE_ID::Any* Option::mutable_value() { ::PROTOBUF_NAMESPACE_ID::Any* _msg = _internal_mutable_value(); @@ -2486,7 +2501,7 @@ inline void Option::set_allocated_value(::PROTOBUF_NAMESPACE_ID::Any* value) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArenaForAllocation(); if (message_arena == nullptr) { - delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(value_); + delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(_impl_.value_); } if (value) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = @@ -2500,7 +2515,7 @@ } else { } - value_ = value; + _impl_.value_ = value; // @@protoc_insertion_point(field_set_allocated:google.protobuf.Option.value) }
diff --git a/src/google/protobuf/unittest.proto b/src/google/protobuf/unittest.proto index 3a76195..44f8a48 100644 --- a/src/google/protobuf/unittest.proto +++ b/src/google/protobuf/unittest.proto
@@ -113,6 +113,7 @@ optional_public_import_message = 26; optional NestedMessage optional_lazy_message = 27 [lazy=true]; + optional NestedMessage optional_unverified_lazy_message = 28 [unverified_lazy=true]; // Repeated repeated int32 repeated_int32 = 31; @@ -264,6 +265,8 @@ optional TestAllTypes.NestedMessage optional_lazy_message_extension = 27 [lazy=true]; + optional TestAllTypes.NestedMessage + optional_unverified_lazy_message_extension = 28 [unverified_lazy=true]; // Repeated repeated int32 repeated_int32_extension = 31; @@ -842,7 +845,7 @@ optional string baz_string = 19 [default = "BAZ"]; message NestedMessage { - optional int64 qux_int = 1; + optional int64 moo_int = 1; repeated int32 corge_int = 2; } @@ -1034,6 +1037,17 @@ optional string a = 1 [default="*/ <- Neither should this."]; } +// Used to check that the c++ code generator re-orders messages to reduce +// padding. +message TestMessageSize { + optional bool m1 = 1; + optional int64 m2 = 2; + optional bool m3 = 3; + optional string m4 = 4; + optional int32 m5 = 5; + optional int64 m6 = 6; +} + // Test that RPC services work. message FooRequest {}
diff --git a/src/google/protobuf/unittest_custom_options.proto b/src/google/protobuf/unittest_custom_options.proto index 1812d71..d741661 100644 --- a/src/google/protobuf/unittest_custom_options.proto +++ b/src/google/protobuf/unittest_custom_options.proto
@@ -245,7 +245,7 @@ } message ComplexOptionType3 { - optional int32 qux = 1; + optional int32 moo = 1; optional group ComplexOptionType5 = 2 { optional int32 plugh = 3; @@ -253,7 +253,7 @@ } extend ComplexOptionType1 { - optional int32 quux = 7663707; + optional int32 mooo = 7663707; optional ComplexOptionType3 corge = 7663442; } @@ -274,18 +274,18 @@ // Note that we try various different ways of naming the same extension. message VariousComplexOptions { option (.protobuf_unittest.complex_opt1).foo = 42; - option (protobuf_unittest.complex_opt1).(.protobuf_unittest.quux) = 324; - option (.protobuf_unittest.complex_opt1).(protobuf_unittest.corge).qux = 876; + option (protobuf_unittest.complex_opt1).(.protobuf_unittest.mooo) = 324; + option (.protobuf_unittest.complex_opt1).(protobuf_unittest.corge).moo = 876; option (protobuf_unittest.complex_opt1).foo4 = 99; option (protobuf_unittest.complex_opt1).foo4 = 88; option (complex_opt2).baz = 987; option (complex_opt2).(grault) = 654; option (complex_opt2).bar.foo = 743; - option (complex_opt2).bar.(quux) = 1999; - option (complex_opt2).bar.(protobuf_unittest.corge).qux = 2008; + option (complex_opt2).bar.(mooo) = 1999; + option (complex_opt2).bar.(protobuf_unittest.corge).moo = 2008; option (complex_opt2).(garply).foo = 741; - option (complex_opt2).(garply).(.protobuf_unittest.quux) = 1998; - option (complex_opt2).(protobuf_unittest.garply).(corge).qux = 2121; + option (complex_opt2).(garply).(.protobuf_unittest.mooo) = 1998; + option (complex_opt2).(protobuf_unittest.garply).(corge).moo = 2121; option (ComplexOptionType2.ComplexOptionType4.complex_opt4).waldo = 1971; option (complex_opt2).fred.waldo = 321; option (complex_opt2).barney = { @@ -294,7 +294,7 @@ option (complex_opt2).barney = { waldo: 212 }; - option (protobuf_unittest.complex_opt3).qux = 9; + option (protobuf_unittest.complex_opt3).moo = 9; option (complex_opt3).complexoptiontype5.plugh = 22; option (complexopt6).xyzzy = 24; } @@ -439,7 +439,9 @@ // 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; }
diff --git a/src/google/protobuf/unittest_drop_unknown_fields.proto b/src/google/protobuf/unittest_drop_unknown_fields.proto index 8aa3a37..a8a98ad 100644 --- a/src/google/protobuf/unittest_drop_unknown_fields.proto +++ b/src/google/protobuf/unittest_drop_unknown_fields.proto
@@ -31,8 +31,8 @@ syntax = "proto3"; package unittest_drop_unknown_fields; -option objc_class_prefix = "DropUnknowns"; +option objc_class_prefix = "DropUnknowns"; option csharp_namespace = "Google.Protobuf.TestProtos"; message Foo { @@ -50,7 +50,7 @@ FOO = 0; BAR = 1; BAZ = 2; - QUX = 3; + MOO = 3; } int32 int32_value = 1; NestedEnum enum_value = 2;
diff --git a/src/google/protobuf/unittest_lite.proto b/src/google/protobuf/unittest_lite.proto index e2730ac..010d4a9 100644 --- a/src/google/protobuf/unittest_lite.proto +++ b/src/google/protobuf/unittest_lite.proto
@@ -97,6 +97,8 @@ optional_public_import_message = 26; optional NestedMessage optional_lazy_message = 27 [lazy = true]; + optional NestedMessage optional_unverified_lazy_message = 28 + [unverified_lazy = true]; // Repeated repeated int32 repeated_int32 = 31; @@ -247,6 +249,9 @@ optional TestAllTypesLite.NestedMessage optional_lazy_message_extension_lite = 27 [lazy = true]; + optional TestAllTypesLite.NestedMessage + optional_unverified_lazy_message_extension_lite = 28 + [unverified_lazy = true]; // Repeated repeated int32 repeated_int32_extension_lite = 31; @@ -406,7 +411,9 @@ extensions 1 to max; } -enum V1EnumLite { V1_FIRST = 1; } +enum V1EnumLite { + V1_FIRST = 1; +} enum V2EnumLite { V2_FIRST = 1;
diff --git a/src/google/protobuf/unittest_proto3.proto b/src/google/protobuf/unittest_proto3.proto index 8b78075..910f401 100644 --- a/src/google/protobuf/unittest_proto3.proto +++ b/src/google/protobuf/unittest_proto3.proto
@@ -96,6 +96,7 @@ 26; NestedMessage optional_lazy_message = 27 [lazy = true]; + NestedMessage optional_unverified_lazy_message = 28 [unverified_lazy = true]; protobuf_unittest_import.ImportMessage optional_lazy_import_message = 115 [lazy = true];
diff --git a/src/google/protobuf/unittest_proto3_arena.proto b/src/google/protobuf/unittest_proto3_arena.proto index 1752939..7dc6cd0 100644 --- a/src/google/protobuf/unittest_proto3_arena.proto +++ b/src/google/protobuf/unittest_proto3_arena.proto
@@ -96,6 +96,7 @@ optional_public_import_message = 26; NestedMessage optional_lazy_message = 27 [lazy=true]; + NestedMessage optional_unverified_lazy_message = 28 [unverified_lazy=true]; protobuf_unittest_import.ImportMessage optional_lazy_import_message = 115 [lazy = true];
diff --git a/src/google/protobuf/unknown_field_set.cc b/src/google/protobuf/unknown_field_set.cc index e592093..74c358e 100644 --- a/src/google/protobuf/unknown_field_set.cc +++ b/src/google/protobuf/unknown_field_set.cc
@@ -111,7 +111,7 @@ size_t UnknownFieldSet::SpaceUsedExcludingSelfLong() const { if (fields_.empty()) return 0; - size_t total_size = sizeof(fields_) + sizeof(UnknownField) * fields_.size(); + size_t total_size = sizeof(UnknownField) * fields_.capacity(); for (const UnknownField& field : fields_) { switch (field.type()) {
diff --git a/src/google/protobuf/unknown_field_set_unittest.cc b/src/google/protobuf/unknown_field_set_unittest.cc index de07d7c..f4d51ae 100644 --- a/src/google/protobuf/unknown_field_set_unittest.cc +++ b/src/google/protobuf/unknown_field_set_unittest.cc
@@ -37,12 +37,13 @@ #include <google/protobuf/unknown_field_set.h> +#include <string> #include <unordered_set> +#include <vector> #include <google/protobuf/stubs/callback.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_lite.pb.h> #include <google/protobuf/io/coded_stream.h> @@ -54,6 +55,7 @@ #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/time.h> +#include <google/protobuf/test_util.h> #include <google/protobuf/stubs/stl_util.h> namespace google { @@ -533,38 +535,61 @@ TEST_F(UnknownFieldSetTest, SpaceUsedExcludingSelf) { UnknownFieldSet empty; empty.AddVarint(1, 0); - EXPECT_EQ(sizeof(std::vector<UnknownField>) + sizeof(UnknownField), - empty.SpaceUsedExcludingSelf()); + EXPECT_EQ(sizeof(UnknownField), empty.SpaceUsedExcludingSelf()); } TEST_F(UnknownFieldSetTest, SpaceUsed) { + // Keep shadow vectors to avoid making assumptions about its capacity growth. + // We imitate the push back calls here to determine the expected capacity. + std::vector<UnknownField> shadow_vector, shadow_vector_group; unittest::TestEmptyMessage empty_message; // Make sure an unknown field set has zero space used until a field is // actually added. - size_t base_size = empty_message.SpaceUsedLong(); + const size_t base = empty_message.SpaceUsedLong(); + std::string* str = nullptr; + UnknownFieldSet* group = nullptr; + const auto total = [&] { + size_t result = base; + result += shadow_vector.capacity() * sizeof(UnknownField); + result += shadow_vector_group.capacity() * sizeof(UnknownField); + if (str != nullptr) { + result += sizeof(std::string); + static const size_t sso_capacity = std::string().capacity(); + if (str->capacity() > sso_capacity) result += str->capacity(); + } + if (group != nullptr) { + result += sizeof(UnknownFieldSet); + } + return result; + }; + UnknownFieldSet* unknown_fields = empty_message.mutable_unknown_fields(); - EXPECT_EQ(base_size, empty_message.SpaceUsedLong()); + EXPECT_EQ(total(), empty_message.SpaceUsedLong()); // Make sure each thing we add to the set increases the SpaceUsedLong(). unknown_fields->AddVarint(1, 0); - EXPECT_LT(base_size, empty_message.SpaceUsedLong()); - base_size = empty_message.SpaceUsedLong(); + shadow_vector.emplace_back(); + EXPECT_EQ(total(), empty_message.SpaceUsedLong()) << "Var"; - std::string* str = unknown_fields->AddLengthDelimited(1); - EXPECT_LT(base_size, empty_message.SpaceUsedLong()); - base_size = empty_message.SpaceUsedLong(); + str = unknown_fields->AddLengthDelimited(1); + shadow_vector.emplace_back(); + EXPECT_EQ(total(), empty_message.SpaceUsedLong()) << "Str"; str->assign(sizeof(std::string) + 1, 'x'); - EXPECT_LT(base_size, empty_message.SpaceUsedLong()); - base_size = empty_message.SpaceUsedLong(); + EXPECT_EQ(total(), empty_message.SpaceUsedLong()) << "Str2"; - UnknownFieldSet* group = unknown_fields->AddGroup(1); - EXPECT_LT(base_size, empty_message.SpaceUsedLong()); - base_size = empty_message.SpaceUsedLong(); + group = unknown_fields->AddGroup(1); + shadow_vector.emplace_back(); + EXPECT_EQ(total(), empty_message.SpaceUsedLong()) << "Group"; group->AddVarint(1, 0); - EXPECT_LT(base_size, empty_message.SpaceUsedLong()); + shadow_vector_group.emplace_back(); + EXPECT_EQ(total(), empty_message.SpaceUsedLong()) << "Group2"; + + unknown_fields->AddVarint(1, 0); + shadow_vector.emplace_back(); + EXPECT_EQ(total(), empty_message.SpaceUsedLong()) << "Var2"; }
diff --git a/src/google/protobuf/util/field_mask_util_test.cc b/src/google/protobuf/util/field_mask_util_test.cc index df5d087..bcad739 100644 --- a/src/google/protobuf/util/field_mask_util_test.cc +++ b/src/google/protobuf/util/field_mask_util_test.cc
@@ -227,7 +227,7 @@ EXPECT_TRUE(FieldMaskUtil::IsPathInFieldMask("bb", mask)); mask = FieldMaskUtil::GetFieldMaskForAllFields<TestAllTypes>(); - EXPECT_EQ(75, mask.paths_size()); + EXPECT_EQ(76, mask.paths_size()); EXPECT_TRUE(FieldMaskUtil::IsPathInFieldMask("optional_int32", mask)); EXPECT_TRUE(FieldMaskUtil::IsPathInFieldMask("optional_int64", mask)); EXPECT_TRUE(FieldMaskUtil::IsPathInFieldMask("optional_uint32", mask));
diff --git a/src/google/protobuf/util/internal/expecting_objectwriter.h b/src/google/protobuf/util/internal/expecting_objectwriter.h index cb0f2aa..76fe2b6 100644 --- a/src/google/protobuf/util/internal/expecting_objectwriter.h +++ b/src/google/protobuf/util/internal/expecting_objectwriter.h
@@ -28,8 +28,8 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_EXPECTING_OBJECTWRITER_H__ -#define GOOGLE_PROTOBUF_UTIL_CONVERTER_EXPECTING_OBJECTWRITER_H__ +#ifndef GOOGLE_PROTOBUF_UTIL_INTERNAL_EXPECTING_OBJECTWRITER_H__ +#define GOOGLE_PROTOBUF_UTIL_INTERNAL_EXPECTING_OBJECTWRITER_H__ // An implementation of ObjectWriter that automatically sets the // gmock expectations for the response to a method. Every method @@ -53,9 +53,9 @@ #include <cstdint> #include <google/protobuf/stubs/common.h> -#include <google/protobuf/util/internal/object_writer.h> #include <gmock/gmock.h> #include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/util/internal/object_writer.h> namespace google { namespace protobuf { @@ -247,4 +247,4 @@ } // namespace protobuf } // namespace google -#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_EXPECTING_OBJECTWRITER_H__ +#endif // GOOGLE_PROTOBUF_UTIL_INTERNAL_EXPECTING_OBJECTWRITER_H__
diff --git a/src/google/protobuf/util/internal/mock_error_listener.h b/src/google/protobuf/util/internal/mock_error_listener.h index a00fab0..3fbdd88 100644 --- a/src/google/protobuf/util/internal/mock_error_listener.h +++ b/src/google/protobuf/util/internal/mock_error_listener.h
@@ -28,13 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#ifndef GOOGLE_PROTOBUF_UTIL_CONVERTER_MOCK_ERROR_LISTENER_H__ -#define GOOGLE_PROTOBUF_UTIL_CONVERTER_MOCK_ERROR_LISTENER_H__ +#ifndef GOOGLE_PROTOBUF_UTIL_INTERNAL_MOCK_ERROR_LISTENER_H__ +#define GOOGLE_PROTOBUF_UTIL_INTERNAL_MOCK_ERROR_LISTENER_H__ -#include <google/protobuf/util/internal/error_listener.h> -#include <google/protobuf/util/internal/location_tracker.h> #include <gmock/gmock.h> #include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/util/internal/error_listener.h> +#include <google/protobuf/util/internal/location_tracker.h> namespace google { namespace protobuf { @@ -65,4 +65,4 @@ } // namespace protobuf } // namespace google -#endif // GOOGLE_PROTOBUF_UTIL_CONVERTER_MOCK_ERROR_LISTENER_H__ +#endif // GOOGLE_PROTOBUF_UTIL_INTERNAL_MOCK_ERROR_LISTENER_H__
diff --git a/src/google/protobuf/util/internal/protostream_objectwriter.cc b/src/google/protobuf/util/internal/protostream_objectwriter.cc index 3e54b1c..ecb219e 100644 --- a/src/google/protobuf/util/internal/protostream_objectwriter.cc +++ b/src/google/protobuf/util/internal/protostream_objectwriter.cc
@@ -503,7 +503,7 @@ // stream, we write those values. if (master_type_.name() == kStructType) { // Struct has a map<string, Value> field called "fields". - // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto + // https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/struct.proto // "fields": [ Push("fields", Item::MAP, true, true); return this; @@ -514,7 +514,7 @@ // object within that type is a struct type. So start a struct. // // The struct field in Value type is named "struct_value" - // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto + // https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/struct.proto // Also start the map field "fields" within the struct. // "struct_value": { // "fields": [ @@ -703,7 +703,7 @@ // we have to start the "list_value" within google.protobuf.Value. // // See - // https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/struct.proto + // https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/struct.proto // // Render // "<name>": {
diff --git a/src/google/protobuf/util/json_util.cc b/src/google/protobuf/util/json_util.cc index 5a84c7d..c39c10d 100644 --- a/src/google/protobuf/util/json_util.cc +++ b/src/google/protobuf/util/json_util.cc
@@ -31,9 +31,12 @@ #include <google/protobuf/util/json_util.h> #include <google/protobuf/stubs/common.h> +#include <google/protobuf/stubs/once.h> +#include <google/protobuf/stubs/status.h> +#include <google/protobuf/stubs/bytestream.h> +#include <google/protobuf/stubs/strutil.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/stubs/once.h> #include <google/protobuf/util/internal/default_value_objectwriter.h> #include <google/protobuf/util/internal/error_listener.h> #include <google/protobuf/util/internal/json_objectwriter.h> @@ -42,9 +45,6 @@ #include <google/protobuf/util/internal/protostream_objectwriter.h> #include <google/protobuf/util/type_resolver.h> #include <google/protobuf/util/type_resolver_util.h> -#include <google/protobuf/stubs/bytestream.h> -#include <google/protobuf/stubs/status.h> -#include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/status_macros.h> // clang-format off @@ -64,7 +64,7 @@ void ZeroCopyStreamByteSink::Append(const char* bytes, size_t len) { while (true) { - if (len <= buffer_size_) { + if (len <= buffer_size_) { // NOLINT memcpy(buffer_, bytes, len); buffer_ = static_cast<char*>(buffer_) + len; buffer_size_ -= len; @@ -226,7 +226,9 @@ message.GetDescriptor()->full_name(); } -void DeleteGeneratedTypeResolver() { delete generated_type_resolver_; } +void DeleteGeneratedTypeResolver() { // NOLINT + delete generated_type_resolver_; +} void InitGeneratedTypeResolver() { generated_type_resolver_ = NewTypeResolverForDescriptorPool(
diff --git a/src/google/protobuf/util/json_util.h b/src/google/protobuf/util/json_util.h index d95b8f7..0f1c4d8 100644 --- a/src/google/protobuf/util/json_util.h +++ b/src/google/protobuf/util/json_util.h
@@ -33,11 +33,11 @@ #ifndef GOOGLE_PROTOBUF_UTIL_JSON_UTIL_H__ #define GOOGLE_PROTOBUF_UTIL_JSON_UTIL_H__ -#include <google/protobuf/message.h> -#include <google/protobuf/util/type_resolver.h> #include <google/protobuf/stubs/bytestream.h> #include <google/protobuf/stubs/status.h> #include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/message.h> +#include <google/protobuf/util/type_resolver.h> // Must be included last. #include <google/protobuf/port_def.inc> @@ -62,8 +62,7 @@ bool case_insensitive_enum_parsing; JsonParseOptions() - : ignore_unknown_fields(false), - case_insensitive_enum_parsing(false) {} + : ignore_unknown_fields(false), case_insensitive_enum_parsing(false) {} }; struct JsonPrintOptions {
diff --git a/src/google/protobuf/util/json_util_test.cc b/src/google/protobuf/util/json_util_test.cc index a1f8264..0d2f6c7 100644 --- a/src/google/protobuf/util/json_util_test.cc +++ b/src/google/protobuf/util/json_util_test.cc
@@ -34,14 +34,14 @@ #include <list> #include <string> -#include <google/protobuf/io/zero_copy_stream.h> -#include <google/protobuf/io/zero_copy_stream_impl.h> -#include <google/protobuf/descriptor_database.h> -#include <google/protobuf/dynamic_message.h> #include <google/protobuf/util/internal/testdata/maps.pb.h> #include <google/protobuf/util/json_format.pb.h> #include <google/protobuf/util/json_format_proto3.pb.h> #include <gtest/gtest.h> +#include <google/protobuf/descriptor_database.h> +#include <google/protobuf/dynamic_message.h> +#include <google/protobuf/io/zero_copy_stream.h> +#include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/util/type_resolver.h> #include <google/protobuf/util/type_resolver_util.h>
diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h index 4bdf2cb..f63cd54 100644 --- a/src/google/protobuf/util/message_differencer.h +++ b/src/google/protobuf/util/message_differencer.h
@@ -223,16 +223,16 @@ // 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. + // For example, given following proto, if both baz and mooo are changed. // foo { // bar { // baz: 1 - // quux: 2 + // mooo: 2 // } // } // ReportModified will be invoked with following order: - // 1. foo.bar.baz or foo.bar.quux - // 2. foo.bar.quux or foo.bar.baz + // 1. foo.bar.baz or foo.bar.mooo + // 2. foo.bar.mooo or foo.bar.baz // 2. foo.bar // 3. foo class PROTOBUF_EXPORT Reporter {
diff --git a/src/google/protobuf/wire_format_unittest.inc b/src/google/protobuf/wire_format_unittest.inc index 4b7862c..d583ddd 100644 --- a/src/google/protobuf/wire_format_unittest.inc +++ b/src/google/protobuf/wire_format_unittest.inc
@@ -32,22 +32,22 @@ // Based on original Protocol Buffers design by // 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/test_util2.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/wire_format.h> #include <google/protobuf/wire_format_lite.h> -#include <google/protobuf/testing/googletest.h> -#include <google/protobuf/stubs/logging.h> #include <gmock/gmock.h> +#include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> #include <google/protobuf/stubs/casts.h> +#include <google/protobuf/stubs/logging.h> #include <google/protobuf/stubs/strutil.h> +#include <google/protobuf/dynamic_message.h> +#include <google/protobuf/test_util2.h> #include <google/protobuf/stubs/stl_util.h> // clang-format off
diff --git a/src/google/protobuf/wrappers.pb.cc b/src/google/protobuf/wrappers.pb.cc index 30ff129..f41ed67 100644 --- a/src/google/protobuf/wrappers.pb.cc +++ b/src/google/protobuf/wrappers.pb.cc
@@ -22,8 +22,9 @@ PROTOBUF_NAMESPACE_OPEN PROTOBUF_CONSTEXPR DoubleValue::DoubleValue( - ::_pbi::ConstantInitialized) - : value_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct DoubleValueDefaultTypeInternal { PROTOBUF_CONSTEXPR DoubleValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -34,8 +35,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 DoubleValueDefaultTypeInternal _DoubleValue_default_instance_; PROTOBUF_CONSTEXPR FloatValue::FloatValue( - ::_pbi::ConstantInitialized) - : value_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct FloatValueDefaultTypeInternal { PROTOBUF_CONSTEXPR FloatValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -46,8 +48,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 FloatValueDefaultTypeInternal _FloatValue_default_instance_; PROTOBUF_CONSTEXPR Int64Value::Int64Value( - ::_pbi::ConstantInitialized) - : value_(int64_t{0}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/int64_t{0} + , /*decltype(_impl_._cached_size_)*/{}} {} struct Int64ValueDefaultTypeInternal { PROTOBUF_CONSTEXPR Int64ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -58,8 +61,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Int64ValueDefaultTypeInternal _Int64Value_default_instance_; PROTOBUF_CONSTEXPR UInt64Value::UInt64Value( - ::_pbi::ConstantInitialized) - : value_(uint64_t{0u}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/uint64_t{0u} + , /*decltype(_impl_._cached_size_)*/{}} {} struct UInt64ValueDefaultTypeInternal { PROTOBUF_CONSTEXPR UInt64ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -70,8 +74,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 UInt64ValueDefaultTypeInternal _UInt64Value_default_instance_; PROTOBUF_CONSTEXPR Int32Value::Int32Value( - ::_pbi::ConstantInitialized) - : value_(0){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/0 + , /*decltype(_impl_._cached_size_)*/{}} {} struct Int32ValueDefaultTypeInternal { PROTOBUF_CONSTEXPR Int32ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -82,8 +87,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 Int32ValueDefaultTypeInternal _Int32Value_default_instance_; PROTOBUF_CONSTEXPR UInt32Value::UInt32Value( - ::_pbi::ConstantInitialized) - : value_(0u){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/0u + , /*decltype(_impl_._cached_size_)*/{}} {} struct UInt32ValueDefaultTypeInternal { PROTOBUF_CONSTEXPR UInt32ValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -94,8 +100,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 UInt32ValueDefaultTypeInternal _UInt32Value_default_instance_; PROTOBUF_CONSTEXPR BoolValue::BoolValue( - ::_pbi::ConstantInitialized) - : value_(false){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/false + , /*decltype(_impl_._cached_size_)*/{}} {} struct BoolValueDefaultTypeInternal { PROTOBUF_CONSTEXPR BoolValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -106,8 +113,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 BoolValueDefaultTypeInternal _BoolValue_default_instance_; PROTOBUF_CONSTEXPR StringValue::StringValue( - ::_pbi::ConstantInitialized) - : value_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_._cached_size_)*/{}} {} struct StringValueDefaultTypeInternal { PROTOBUF_CONSTEXPR StringValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -118,8 +126,9 @@ }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT PROTOBUF_ATTRIBUTE_INIT_PRIORITY1 StringValueDefaultTypeInternal _StringValue_default_instance_; PROTOBUF_CONSTEXPR BytesValue::BytesValue( - ::_pbi::ConstantInitialized) - : value_(&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}){} + ::_pbi::ConstantInitialized): _impl_{ + /*decltype(_impl_.value_)*/{&::_pbi::fixed_address_empty_string, ::_pbi::ConstantInitialized{}} + , /*decltype(_impl_._cached_size_)*/{}} {} struct BytesValueDefaultTypeInternal { PROTOBUF_CONSTEXPR BytesValueDefaultTypeInternal() : _instance(::_pbi::ConstantInitialized{}) {} @@ -141,63 +150,63 @@ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DoubleValue, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::DoubleValue, _impl_.value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FloatValue, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FloatValue, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::FloatValue, _impl_.value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int64Value, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int64Value, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int64Value, _impl_.value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt64Value, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt64Value, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt64Value, _impl_.value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int32Value, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int32Value, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::Int32Value, _impl_.value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt32Value, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt32Value, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::UInt32Value, _impl_.value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BoolValue, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BoolValue, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BoolValue, _impl_.value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::StringValue, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::StringValue, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::StringValue, _impl_.value_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BytesValue, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _inlined_string_donated_ - PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BytesValue, value_), + PROTOBUF_FIELD_OFFSET(::PROTOBUF_NAMESPACE_ID::BytesValue, _impl_.value_), }; static const ::_pbi::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, -1, sizeof(::PROTOBUF_NAMESPACE_ID::DoubleValue)}, @@ -263,18 +272,28 @@ DoubleValue::DoubleValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.DoubleValue) } DoubleValue::DoubleValue(const DoubleValue& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_ = from.value_; + _impl_.value_ = from._impl_.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.DoubleValue) } -inline void DoubleValue::SharedCtor() { -value_ = 0; +inline void DoubleValue::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; } DoubleValue::~DoubleValue() { @@ -291,7 +310,7 @@ } void DoubleValue::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void DoubleValue::Clear() { @@ -300,7 +319,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_ = 0; + _impl_.value_ = 0; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -313,7 +332,7 @@ // double value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 9)) { - value_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); + _impl_.value_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; @@ -382,11 +401,11 @@ total_size += 1 + 8; } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData DoubleValue::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, DoubleValue::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*DoubleValue::GetClassData() const { return &_class_data_; } @@ -428,7 +447,7 @@ void DoubleValue::InternalSwap(DoubleValue* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(value_, other->value_); + swap(_impl_.value_, other->_impl_.value_); } ::PROTOBUF_NAMESPACE_ID::Metadata DoubleValue::GetMetadata() const { @@ -446,18 +465,28 @@ FloatValue::FloatValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.FloatValue) } FloatValue::FloatValue(const FloatValue& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_ = from.value_; + _impl_.value_ = from._impl_.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.FloatValue) } -inline void FloatValue::SharedCtor() { -value_ = 0; +inline void FloatValue::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; } FloatValue::~FloatValue() { @@ -474,7 +503,7 @@ } void FloatValue::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void FloatValue::Clear() { @@ -483,7 +512,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_ = 0; + _impl_.value_ = 0; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -496,7 +525,7 @@ // float value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 13)) { - value_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); + _impl_.value_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr); ptr += sizeof(float); } else goto handle_unusual; @@ -565,11 +594,11 @@ total_size += 1 + 4; } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData FloatValue::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, FloatValue::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*FloatValue::GetClassData() const { return &_class_data_; } @@ -611,7 +640,7 @@ void FloatValue::InternalSwap(FloatValue* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(value_, other->value_); + swap(_impl_.value_, other->_impl_.value_); } ::PROTOBUF_NAMESPACE_ID::Metadata FloatValue::GetMetadata() const { @@ -629,18 +658,28 @@ Int64Value::Int64Value(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Int64Value) } Int64Value::Int64Value(const Int64Value& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_ = from.value_; + _impl_.value_ = from._impl_.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.Int64Value) } -inline void Int64Value::SharedCtor() { -value_ = int64_t{0}; +inline void Int64Value::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){int64_t{0}} + , /*decltype(_impl_._cached_size_)*/{} + }; } Int64Value::~Int64Value() { @@ -657,7 +696,7 @@ } void Int64Value::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Int64Value::Clear() { @@ -666,7 +705,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_ = int64_t{0}; + _impl_.value_ = int64_t{0}; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -679,7 +718,7 @@ // int64 value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { - value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -740,11 +779,11 @@ total_size += ::_pbi::WireFormatLite::Int64SizePlusOne(this->_internal_value()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Int64Value::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Int64Value::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Int64Value::GetClassData() const { return &_class_data_; } @@ -782,7 +821,7 @@ void Int64Value::InternalSwap(Int64Value* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(value_, other->value_); + swap(_impl_.value_, other->_impl_.value_); } ::PROTOBUF_NAMESPACE_ID::Metadata Int64Value::GetMetadata() const { @@ -800,18 +839,28 @@ UInt64Value::UInt64Value(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.UInt64Value) } UInt64Value::UInt64Value(const UInt64Value& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_ = from.value_; + _impl_.value_ = from._impl_.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.UInt64Value) } -inline void UInt64Value::SharedCtor() { -value_ = uint64_t{0u}; +inline void UInt64Value::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){uint64_t{0u}} + , /*decltype(_impl_._cached_size_)*/{} + }; } UInt64Value::~UInt64Value() { @@ -828,7 +877,7 @@ } void UInt64Value::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void UInt64Value::Clear() { @@ -837,7 +886,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_ = uint64_t{0u}; + _impl_.value_ = uint64_t{0u}; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -850,7 +899,7 @@ // uint64 value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { - value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -911,11 +960,11 @@ total_size += ::_pbi::WireFormatLite::UInt64SizePlusOne(this->_internal_value()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData UInt64Value::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, UInt64Value::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*UInt64Value::GetClassData() const { return &_class_data_; } @@ -953,7 +1002,7 @@ void UInt64Value::InternalSwap(UInt64Value* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(value_, other->value_); + swap(_impl_.value_, other->_impl_.value_); } ::PROTOBUF_NAMESPACE_ID::Metadata UInt64Value::GetMetadata() const { @@ -971,18 +1020,28 @@ Int32Value::Int32Value(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.Int32Value) } Int32Value::Int32Value(const Int32Value& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_ = from.value_; + _impl_.value_ = from._impl_.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.Int32Value) } -inline void Int32Value::SharedCtor() { -value_ = 0; +inline void Int32Value::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){0} + , /*decltype(_impl_._cached_size_)*/{} + }; } Int32Value::~Int32Value() { @@ -999,7 +1058,7 @@ } void Int32Value::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void Int32Value::Clear() { @@ -1008,7 +1067,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_ = 0; + _impl_.value_ = 0; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1021,7 +1080,7 @@ // int32 value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { - value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -1082,11 +1141,11 @@ total_size += ::_pbi::WireFormatLite::Int32SizePlusOne(this->_internal_value()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData Int32Value::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, Int32Value::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*Int32Value::GetClassData() const { return &_class_data_; } @@ -1124,7 +1183,7 @@ void Int32Value::InternalSwap(Int32Value* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(value_, other->value_); + swap(_impl_.value_, other->_impl_.value_); } ::PROTOBUF_NAMESPACE_ID::Metadata Int32Value::GetMetadata() const { @@ -1142,18 +1201,28 @@ UInt32Value::UInt32Value(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.UInt32Value) } UInt32Value::UInt32Value(const UInt32Value& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_ = from.value_; + _impl_.value_ = from._impl_.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.UInt32Value) } -inline void UInt32Value::SharedCtor() { -value_ = 0u; +inline void UInt32Value::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){0u} + , /*decltype(_impl_._cached_size_)*/{} + }; } UInt32Value::~UInt32Value() { @@ -1170,7 +1239,7 @@ } void UInt32Value::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void UInt32Value::Clear() { @@ -1179,7 +1248,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_ = 0u; + _impl_.value_ = 0u; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1192,7 +1261,7 @@ // uint32 value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { - value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); + _impl_.value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint32(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -1253,11 +1322,11 @@ total_size += ::_pbi::WireFormatLite::UInt32SizePlusOne(this->_internal_value()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData UInt32Value::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, UInt32Value::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*UInt32Value::GetClassData() const { return &_class_data_; } @@ -1295,7 +1364,7 @@ void UInt32Value::InternalSwap(UInt32Value* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(value_, other->value_); + swap(_impl_.value_, other->_impl_.value_); } ::PROTOBUF_NAMESPACE_ID::Metadata UInt32Value::GetMetadata() const { @@ -1313,18 +1382,28 @@ BoolValue::BoolValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.BoolValue) } BoolValue::BoolValue(const BoolValue& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_ = from.value_; + _impl_.value_ = from._impl_.value_; // @@protoc_insertion_point(copy_constructor:google.protobuf.BoolValue) } -inline void BoolValue::SharedCtor() { -value_ = false; +inline void BoolValue::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){false} + , /*decltype(_impl_._cached_size_)*/{} + }; } BoolValue::~BoolValue() { @@ -1341,7 +1420,7 @@ } void BoolValue::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void BoolValue::Clear() { @@ -1350,7 +1429,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_ = false; + _impl_.value_ = false; _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1363,7 +1442,7 @@ // bool value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<uint8_t>(tag) == 8)) { - value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); + _impl_.value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; @@ -1424,11 +1503,11 @@ total_size += 1 + 1; } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData BoolValue::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, BoolValue::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*BoolValue::GetClassData() const { return &_class_data_; } @@ -1466,7 +1545,7 @@ void BoolValue::InternalSwap(BoolValue* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); - swap(value_, other->value_); + swap(_impl_.value_, other->_impl_.value_); } ::PROTOBUF_NAMESPACE_ID::Metadata BoolValue::GetMetadata() const { @@ -1484,28 +1563,39 @@ StringValue::StringValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.StringValue) } StringValue::StringValue(const StringValue& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_.InitDefault(); + _impl_.value_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - value_.Set("", GetArenaForAllocation()); + _impl_.value_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_value().empty()) { - value_.Set(from._internal_value(), + _impl_.value_.Set(from._internal_value(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:google.protobuf.StringValue) } -inline void StringValue::SharedCtor() { -value_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - value_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING +inline void StringValue::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.value_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.value_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } StringValue::~StringValue() { @@ -1519,11 +1609,11 @@ inline void StringValue::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - value_.Destroy(); + _impl_.value_.Destroy(); } void StringValue::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void StringValue::Clear() { @@ -1532,7 +1622,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_.ClearToEmpty(); + _impl_.value_.ClearToEmpty(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1614,11 +1704,11 @@ this->_internal_value()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData StringValue::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, StringValue::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*StringValue::GetClassData() const { return &_class_data_; } @@ -1659,8 +1749,8 @@ auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &value_, lhs_arena, - &other->value_, rhs_arena + &_impl_.value_, lhs_arena, + &other->_impl_.value_, rhs_arena ); } @@ -1679,28 +1769,39 @@ BytesValue::BytesValue(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { - SharedCtor(); + SharedCtor(arena, is_message_owned); // @@protoc_insertion_point(arena_constructor:google.protobuf.BytesValue) } BytesValue::BytesValue(const BytesValue& from) : ::PROTOBUF_NAMESPACE_ID::Message() { + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{}}; + _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); - value_.InitDefault(); + _impl_.value_.InitDefault(); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - value_.Set("", GetArenaForAllocation()); + _impl_.value_.Set("", GetArenaForAllocation()); #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING if (!from._internal_value().empty()) { - value_.Set(from._internal_value(), + _impl_.value_.Set(from._internal_value(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:google.protobuf.BytesValue) } -inline void BytesValue::SharedCtor() { -value_.InitDefault(); -#ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - value_.Set("", GetArenaForAllocation()); -#endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING +inline void BytesValue::SharedCtor( + ::_pb::Arena* arena, bool is_message_owned) { + (void)arena; + (void)is_message_owned; + new (&_impl_) Impl_{ + decltype(_impl_.value_){} + , /*decltype(_impl_._cached_size_)*/{} + }; + _impl_.value_.InitDefault(); + #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING + _impl_.value_.Set("", GetArenaForAllocation()); + #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING } BytesValue::~BytesValue() { @@ -1714,11 +1815,11 @@ inline void BytesValue::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); - value_.Destroy(); + _impl_.value_.Destroy(); } void BytesValue::SetCachedSize(int size) const { - _cached_size_.Set(size); + _impl_._cached_size_.Set(size); } void BytesValue::Clear() { @@ -1727,7 +1828,7 @@ // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; - value_.ClearToEmpty(); + _impl_.value_.ClearToEmpty(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } @@ -1804,11 +1905,11 @@ this->_internal_value()); } - return MaybeComputeUnknownFieldsSize(total_size, &_cached_size_); + return MaybeComputeUnknownFieldsSize(total_size, &_impl_._cached_size_); } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData BytesValue::_class_data_ = { - ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, + ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSourceCheck, BytesValue::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*BytesValue::GetClassData() const { return &_class_data_; } @@ -1849,8 +1950,8 @@ auto* rhs_arena = other->GetArenaForAllocation(); _internal_metadata_.InternalSwap(&other->_internal_metadata_); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( - &value_, lhs_arena, - &other->value_, rhs_arena + &_impl_.value_, lhs_arena, + &other->_impl_.value_, rhs_arena ); }
diff --git a/src/google/protobuf/wrappers.pb.h b/src/google/protobuf/wrappers.pb.h index 178d907..59a5ebd 100644 --- a/src/google/protobuf/wrappers.pb.h +++ b/src/google/protobuf/wrappers.pb.h
@@ -179,10 +179,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DoubleValue* other); @@ -225,8 +225,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - double value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + double value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // ------------------------------------------------------------------- @@ -322,10 +325,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(FloatValue* other); @@ -368,8 +371,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - float value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + float value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // ------------------------------------------------------------------- @@ -465,10 +471,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Int64Value* other); @@ -511,8 +517,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - int64_t value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + int64_t value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // ------------------------------------------------------------------- @@ -608,10 +617,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(UInt64Value* other); @@ -654,8 +663,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - uint64_t value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + uint64_t value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // ------------------------------------------------------------------- @@ -751,10 +763,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Int32Value* other); @@ -797,8 +809,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - int32_t value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + int32_t value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // ------------------------------------------------------------------- @@ -894,10 +909,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(UInt32Value* other); @@ -940,8 +955,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - uint32_t value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + uint32_t value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // ------------------------------------------------------------------- @@ -1037,10 +1055,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BoolValue* other); @@ -1083,8 +1101,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - bool value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + bool value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // ------------------------------------------------------------------- @@ -1180,10 +1201,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(StringValue* other); @@ -1231,8 +1252,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // ------------------------------------------------------------------- @@ -1328,10 +1352,10 @@ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; uint8_t* _InternalSerialize( uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; - int GetCachedSize() const final { return _cached_size_.Get(); } + int GetCachedSize() const final { return _impl_._cached_size_.Get(); } private: - void SharedCtor(); + void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned); void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(BytesValue* other); @@ -1379,8 +1403,11 @@ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; - ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_; - mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + struct Impl_ { + ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr value_; + mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; + }; + union { Impl_ _impl_; }; friend struct ::TableStruct_google_2fprotobuf_2fwrappers_2eproto; }; // =================================================================== @@ -1396,10 +1423,10 @@ // double value = 1; inline void DoubleValue::clear_value() { - value_ = 0; + _impl_.value_ = 0; } inline double DoubleValue::_internal_value() const { - return value_; + return _impl_.value_; } inline double DoubleValue::value() const { // @@protoc_insertion_point(field_get:google.protobuf.DoubleValue.value) @@ -1407,7 +1434,7 @@ } inline void DoubleValue::_internal_set_value(double value) { - value_ = value; + _impl_.value_ = value; } inline void DoubleValue::set_value(double value) { _internal_set_value(value); @@ -1420,10 +1447,10 @@ // float value = 1; inline void FloatValue::clear_value() { - value_ = 0; + _impl_.value_ = 0; } inline float FloatValue::_internal_value() const { - return value_; + return _impl_.value_; } inline float FloatValue::value() const { // @@protoc_insertion_point(field_get:google.protobuf.FloatValue.value) @@ -1431,7 +1458,7 @@ } inline void FloatValue::_internal_set_value(float value) { - value_ = value; + _impl_.value_ = value; } inline void FloatValue::set_value(float value) { _internal_set_value(value); @@ -1444,10 +1471,10 @@ // int64 value = 1; inline void Int64Value::clear_value() { - value_ = int64_t{0}; + _impl_.value_ = int64_t{0}; } inline int64_t Int64Value::_internal_value() const { - return value_; + return _impl_.value_; } inline int64_t Int64Value::value() const { // @@protoc_insertion_point(field_get:google.protobuf.Int64Value.value) @@ -1455,7 +1482,7 @@ } inline void Int64Value::_internal_set_value(int64_t value) { - value_ = value; + _impl_.value_ = value; } inline void Int64Value::set_value(int64_t value) { _internal_set_value(value); @@ -1468,10 +1495,10 @@ // uint64 value = 1; inline void UInt64Value::clear_value() { - value_ = uint64_t{0u}; + _impl_.value_ = uint64_t{0u}; } inline uint64_t UInt64Value::_internal_value() const { - return value_; + return _impl_.value_; } inline uint64_t UInt64Value::value() const { // @@protoc_insertion_point(field_get:google.protobuf.UInt64Value.value) @@ -1479,7 +1506,7 @@ } inline void UInt64Value::_internal_set_value(uint64_t value) { - value_ = value; + _impl_.value_ = value; } inline void UInt64Value::set_value(uint64_t value) { _internal_set_value(value); @@ -1492,10 +1519,10 @@ // int32 value = 1; inline void Int32Value::clear_value() { - value_ = 0; + _impl_.value_ = 0; } inline int32_t Int32Value::_internal_value() const { - return value_; + return _impl_.value_; } inline int32_t Int32Value::value() const { // @@protoc_insertion_point(field_get:google.protobuf.Int32Value.value) @@ -1503,7 +1530,7 @@ } inline void Int32Value::_internal_set_value(int32_t value) { - value_ = value; + _impl_.value_ = value; } inline void Int32Value::set_value(int32_t value) { _internal_set_value(value); @@ -1516,10 +1543,10 @@ // uint32 value = 1; inline void UInt32Value::clear_value() { - value_ = 0u; + _impl_.value_ = 0u; } inline uint32_t UInt32Value::_internal_value() const { - return value_; + return _impl_.value_; } inline uint32_t UInt32Value::value() const { // @@protoc_insertion_point(field_get:google.protobuf.UInt32Value.value) @@ -1527,7 +1554,7 @@ } inline void UInt32Value::_internal_set_value(uint32_t value) { - value_ = value; + _impl_.value_ = value; } inline void UInt32Value::set_value(uint32_t value) { _internal_set_value(value); @@ -1540,10 +1567,10 @@ // bool value = 1; inline void BoolValue::clear_value() { - value_ = false; + _impl_.value_ = false; } inline bool BoolValue::_internal_value() const { - return value_; + return _impl_.value_; } inline bool BoolValue::value() const { // @@protoc_insertion_point(field_get:google.protobuf.BoolValue.value) @@ -1551,7 +1578,7 @@ } inline void BoolValue::_internal_set_value(bool value) { - value_ = value; + _impl_.value_ = value; } inline void BoolValue::set_value(bool value) { _internal_set_value(value); @@ -1564,7 +1591,7 @@ // string value = 1; inline void StringValue::clear_value() { - value_.ClearToEmpty(); + _impl_.value_.ClearToEmpty(); } inline const std::string& StringValue::value() const { // @@protoc_insertion_point(field_get:google.protobuf.StringValue.value) @@ -1574,7 +1601,7 @@ inline PROTOBUF_ALWAYS_INLINE void StringValue::set_value(ArgT0&& arg0, ArgT... args) { - value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.value_.Set(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.StringValue.value) } inline std::string* StringValue::mutable_value() { @@ -1583,19 +1610,19 @@ return _s; } inline const std::string& StringValue::_internal_value() const { - return value_.Get(); + return _impl_.value_.Get(); } inline void StringValue::_internal_set_value(const std::string& value) { - value_.Set(value, GetArenaForAllocation()); + _impl_.value_.Set(value, GetArenaForAllocation()); } inline std::string* StringValue::_internal_mutable_value() { - return value_.Mutable(GetArenaForAllocation()); + return _impl_.value_.Mutable(GetArenaForAllocation()); } inline std::string* StringValue::release_value() { // @@protoc_insertion_point(field_release:google.protobuf.StringValue.value) - return value_.Release(); + return _impl_.value_.Release(); } inline void StringValue::set_allocated_value(std::string* value) { if (value != nullptr) { @@ -1603,10 +1630,10 @@ } else { } - value_.SetAllocated(value, GetArenaForAllocation()); + _impl_.value_.SetAllocated(value, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (value_.IsDefault()) { - value_.Set("", GetArenaForAllocation()); + if (_impl_.value_.IsDefault()) { + _impl_.value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.StringValue.value) @@ -1618,7 +1645,7 @@ // bytes value = 1; inline void BytesValue::clear_value() { - value_.ClearToEmpty(); + _impl_.value_.ClearToEmpty(); } inline const std::string& BytesValue::value() const { // @@protoc_insertion_point(field_get:google.protobuf.BytesValue.value) @@ -1628,7 +1655,7 @@ inline PROTOBUF_ALWAYS_INLINE void BytesValue::set_value(ArgT0&& arg0, ArgT... args) { - value_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); + _impl_.value_.SetBytes(static_cast<ArgT0 &&>(arg0), args..., GetArenaForAllocation()); // @@protoc_insertion_point(field_set:google.protobuf.BytesValue.value) } inline std::string* BytesValue::mutable_value() { @@ -1637,19 +1664,19 @@ return _s; } inline const std::string& BytesValue::_internal_value() const { - return value_.Get(); + return _impl_.value_.Get(); } inline void BytesValue::_internal_set_value(const std::string& value) { - value_.Set(value, GetArenaForAllocation()); + _impl_.value_.Set(value, GetArenaForAllocation()); } inline std::string* BytesValue::_internal_mutable_value() { - return value_.Mutable(GetArenaForAllocation()); + return _impl_.value_.Mutable(GetArenaForAllocation()); } inline std::string* BytesValue::release_value() { // @@protoc_insertion_point(field_release:google.protobuf.BytesValue.value) - return value_.Release(); + return _impl_.value_.Release(); } inline void BytesValue::set_allocated_value(std::string* value) { if (value != nullptr) { @@ -1657,10 +1684,10 @@ } else { } - value_.SetAllocated(value, GetArenaForAllocation()); + _impl_.value_.SetAllocated(value, GetArenaForAllocation()); #ifdef PROTOBUF_FORCE_COPY_DEFAULT_STRING - if (value_.IsDefault()) { - value_.Set("", GetArenaForAllocation()); + if (_impl_.value_.IsDefault()) { + _impl_.value_.Set("", GetArenaForAllocation()); } #endif // PROTOBUF_FORCE_COPY_DEFAULT_STRING // @@protoc_insertion_point(field_set_allocated:google.protobuf.BytesValue.value)
diff --git a/tests.sh b/tests.sh index 73460fd..8e896e8 100755 --- a/tests.sh +++ b/tests.sh
@@ -4,10 +4,6 @@ # tests on kokoro (Ubuntu and MacOS). It can run locally as well but you # will need to make sure the required compilers/tools are available. -# For when some other test needs the C++ main build, including protoc and -# libprotobuf. -LAST_RELEASED=3.9.0 - internal_build_cpp() { if [ -f src/protoc ]; then # Already built. @@ -162,9 +158,14 @@ # Run csharp compatibility test between 3.0.0 and the current version. csharp/compatibility_tests/v3.0.0/test.sh 3.0.0 - - # Run csharp compatibility test between last released and the current version. - csharp/compatibility_tests/v3.0.0/test.sh $LAST_RELEASED + + # Regression test for https://github.com/protocolbuffers/protobuf/issues/9526 + # - all line endings in .proto and .cs (and .csproj) files should be LF. + if git ls-files --eol csharp | grep -E '\.cs|\.proto' | grep -v w/lf + then + echo "The files listed above have mixed or CRLF line endings; please change to LF." + exit 1 + fi } build_golang() { @@ -189,6 +190,10 @@ use_java() { version=$1 case "$version" in + jdk17) + export PATH=/usr/lib/jvm/java-17-openjdk-amd64/bin:$PATH + export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 + ;; jdk11) export PATH=/usr/lib/jvm/java-11-openjdk-amd64/bin:$PATH export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 @@ -264,10 +269,22 @@ use_java jdk7 build_java_with_conformance_tests } + build_java_oracle7() { use_java oracle7 build_java oracle7 } + +build_java_jdk8() { + use_java jdk8 + build_java_with_conformance_tests +} + +build_java_jdk17() { + use_java jdk17 + build_java_with_conformance_tests +} + build_java_linkage_monitor() { # Linkage Monitor checks compatibility with other Google libraries # https://github.com/GoogleCloudPlatform/cloud-opensource-java/tree/master/linkage-monitor @@ -397,7 +414,6 @@ build_python_cpp_version py310-cpp } - build_ruby23() { internal_build_cpp # For conformance tests. cd ruby && bash travis-test.sh ruby-2.3.8 && cd .. @@ -436,7 +452,7 @@ build_jruby93() { internal_build_cpp # For conformance tests. internal_build_java jdk8 && cd .. # For Maven protobuf jar with local changes - cd ruby && bash travis-test.sh jruby-9.3.3.0 && cd .. + cd ruby && bash travis-test.sh jruby-9.3.4.0 && cd .. } build_javascript() { @@ -532,7 +548,6 @@ build_php_compatibility() { internal_build_cpp - php/tests/compatibility_test.sh $LAST_RELEASED } build_php_multirequest() { @@ -579,6 +594,8 @@ csharp | java_jdk7 | java_oracle7 | + java_jdk8 | + java_jdk17 | java_linkage_monitor | objectivec_ios | objectivec_ios_debug |
diff --git a/third_party/abseil-cpp b/third_party/abseil-cpp new file mode 160000 index 0000000..8c6e53e --- /dev/null +++ b/third_party/abseil-cpp
@@ -0,0 +1 @@ +Subproject commit 8c6e53ef3adb1227fffa442c50349dab134a54bc
diff --git a/third_party/utf8_range/utf8_range.h b/third_party/utf8_range/utf8_range.h index 3695587..23b32a1 100644 --- a/third_party/utf8_range/utf8_range.h +++ b/third_party/utf8_range/utf8_range.h
@@ -1,5 +1,5 @@ -#if (defined(__ARM_NEON) && defined(__aarch64__)) || defined(__SSE4_1__) +#if ((defined(__ARM_NEON) && defined(__aarch64__)) || defined(__SSE4_1__)) && !defined(TRUFFLERUBY) int utf8_range2(const unsigned char* data, int len); #else int utf8_naive(const unsigned char* data, int len);
diff --git a/toolchain/BUILD b/toolchain/BUILD index ff2b515..b171c22 100644 --- a/toolchain/BUILD +++ b/toolchain/BUILD
@@ -14,6 +14,7 @@ "linux-x86_64": "cc-compiler-linux-x86_64", "win32": "cc-compiler-windows-x86_32", "win64": "cc-compiler-windows-x86_64", + "k8": "cc-compiler-k8", } cc_toolchain_suite( @@ -40,137 +41,97 @@ ] cc_toolchain_config( + name = "k8-config", + linker_path = "/usr/bin/ld", + sysroot = "/opt/manylinux/2014/x86_64", + target_cpu = "x86_64", + target_full_name = "x86_64-linux-gnu", +) + +cc_toolchain_config( name = "linux-aarch_64-config", - bit_flag = "-m64", - cpp_flag = "-lstdc++", - extra_compiler_flags = [ - "-I/opt/manylinux/2014/aarch64/usr/include/c++/10/aarch64-redhat-linux", - "-I/opt/manylinux/2014/aarch64/usr/include/c++/10" - ], sysroot = "/opt/manylinux/2014/aarch64", linker_path = "/usr/bin/ld", target_cpu = "aarch64", target_full_name = "aarch64-linux-gnu", - toolchain_name = "linux_aarch_64", - # Don't really need this, setting it because it's required. - toolchain_dir = "/opt/manylinux/2014/aarch64/usr/include", ) cc_toolchain_config( name = "linux-ppcle_64-config", - bit_flag = "-m64", - cpp_flag = "-lstdc++", - extra_compiler_flags = [ - "-I/usr/powerpc64le-linux-gnu/include/c++/8/powerpc64le-linux-gnu/", - "-I/usr/powerpc64le-linux-gnu/include/c++/8/" - ], - extra_include = "/usr/include", linker_path = "/usr/bin/ld", + sysroot = "/opt/manylinux/2014/ppc64le", target_cpu = "ppc64", target_full_name = "powerpc64le-linux-gnu", - toolchain_dir = "/usr/powerpc64le-linux-gnu/include", - toolchain_name = "linux_ppcle_64", ) cc_toolchain_config( name = "linux-s390_64-config", - bit_flag = "-m64", - cpp_flag = "-lstdc++", - extra_compiler_flags = [ - "-I/usr/s390x-linux-gnu/include/c++/8/s390x-linux-gnu/", - "-I/usr/s390x-linux-gnu/include/c++/8/" - ], - extra_include = "/usr/include", linker_path = "/usr/bin/ld", + sysroot = "/opt/manylinux/2014/s390x", target_cpu = "systemz", target_full_name = "s390x-linux-gnu", - toolchain_dir = "/usr/s390x-linux-gnu/include", - toolchain_name = "linux_s390_64", ) cc_toolchain_config( name = "linux-x86_32-config", - bit_flag = "-m32", - cpp_flag = "-lstdc++", - extra_include = "/usr/include", linker_path = "/usr/bin/ld", + sysroot = "/opt/manylinux/2014/i686", target_cpu = "x86_32", target_full_name = "i386-linux-gnu", - toolchain_dir = "/usr/include/i386-linux-gnu", - toolchain_name = "linux_x86_32", ) cc_toolchain_config( name = "linux-x86_64-config", - bit_flag = "-m64", - cpp_flag = "-lstdc++", - extra_include = "/usr/include", linker_path = "/usr/bin/ld", + sysroot = "/opt/manylinux/2014/x86_64", target_cpu = "x86_64", target_full_name = "x86_64-linux-gnu", - toolchain_dir = "/usr/include/x86_64-linux-gnu", - toolchain_name = "linux_x86_64", ) cc_toolchain_config( name = "osx-aarch_64-config", - bit_flag = "-m64", - cpp_flag = "-lc++", extra_compiler_flags = [ "-I/usr/tools/apple_sdks/xcode_13_0/macosx/usr/include/c++/v1", "-I/usr/tools/apple_sdks/xcode_13_0/macosx/usr/include" ], - extra_include = "/usr/include", linker_path = "/usr/tools", sysroot = "/usr/tools/apple_sdks/xcode_13_0/macosx", target_cpu = "aarch64", target_full_name = "aarch64-apple-macosx11.3", - toolchain_dir = "/usr/tools/apple_sdks/xcode_13_0/macosx", - toolchain_name = "osx_aarch_64", ) cc_toolchain_config( name = "osx-x86_64-config", - bit_flag = "-m64", - cpp_flag = "-lc++", extra_compiler_flags = [ "-I/usr/tools/apple_sdks/xcode_13_0/macosx/usr/include/c++/v1", "-I/usr/tools/apple_sdks/xcode_13_0/macosx/usr/include" ], - extra_include = "/usr/include", linker_path = "/usr/tools", sysroot = "/usr/tools/apple_sdks/xcode_13_0/macosx", target_cpu = "x86_64", target_full_name = "x86_64-apple-macosx11.3", - toolchain_dir = "/usr/tools/apple_sdks/xcode_13_0/macosx", - toolchain_name = "osx_x86_64", ) cc_toolchain_config( name = "win32-config", - bit_flag = "-m32", - cpp_flag = "-lstdc++", extra_compiler_flags = [ "-isystem/usr/lib/gcc/i686-w64-mingw32/8.3-posix/include/c++", "-isystem/usr/lib/gcc/i686-w64-mingw32/8.3-posix/include/c++/i686-w64-mingw32", "-fsjlj-exceptions", ], - extra_include = "/usr/lib/gcc/i686-w64-mingw32/8.3-posix/include", + extra_include = "/usr/lib/gcc/i686-w64-mingw32", extra_linker_flags = [ "-L/usr/lib/gcc/i686-w64-mingw32/8.3-posix", "-pthread", ], linker_path = "/usr/bin/ld", + sysroot = "/usr/i686-w64-mingw32", target_cpu = "x86_32", target_full_name = "i686-w64-mingw32", - toolchain_dir = "/usr/i686-w64-mingw32/include", - toolchain_name = "i686-w64-mingw32", ) cc_toolchain_config( name = "win64-config", - bit_flag = "-m64", - cpp_flag = "-lstdc++", extra_compiler_flags = [ "-isystem/usr/lib/gcc/x86_64-w64-mingw32/8.3-posix/include/c++/", "-isystem/usr/lib/gcc/x86_64-w64-mingw32/8.3-posix/include/c++/x86_64-w64-mingw32", @@ -180,8 +141,7 @@ "-L/usr/lib/gcc/x86_64-w64-mingw32/8.3-posix", ], linker_path = "/usr/bin/ld", + sysroot = "/usr/x86_64-w64-mingw32", target_cpu = "x86_64", target_full_name = "x86_64-w64-mingw32", - toolchain_dir = "/usr/x86_64-w64-mingw32/include", - toolchain_name = "x86_64-w64-mingw32", )
diff --git a/toolchain/cc_toolchain_config.bzl b/toolchain/cc_toolchain_config.bzl index 81fe19e..777bb82 100644 --- a/toolchain/cc_toolchain_config.bzl +++ b/toolchain/cc_toolchain_config.bzl
@@ -28,7 +28,7 @@ ] def _impl(ctx): - if 'mingw' in ctx.attr.target_full_name: + if "mingw" in ctx.attr.target_full_name: artifact_name_patterns = [ artifact_name_pattern( category_name = "executable", @@ -96,7 +96,7 @@ flag_group( flags = [ "-B" + ctx.attr.linker_path, - ctx.attr.cpp_flag, + "-lstdc++", "--target=" + ctx.attr.target_full_name, ] + ctx.attr.extra_linker_flags, ), @@ -105,7 +105,7 @@ ], ) - if 'osx' in ctx.attr.target_full_name: + if "osx" in ctx.attr.target_full_name: sysroot_action_set = all_link_actions else: sysroot_action_set = all_link_actions + all_compile_actions @@ -129,6 +129,10 @@ ], ) + if ctx.attr.target_cpu == "x86_32": + bit_flag = "-m32" + else: + bit_flag = "-m64" compiler_flags = feature( name = "default_compile_flags", enabled = True, @@ -138,14 +142,14 @@ flag_groups = [ flag_group( flags = [ - ctx.attr.bit_flag, + bit_flag, "-Wall", "-no-canonical-prefixes", "--target=" + ctx.attr.target_full_name, "-fvisibility=hidden", ] + ctx.attr.extra_compiler_flags + [ "-isystem", - ctx.attr.toolchain_dir, + ctx.attr.sysroot, ], ), ], @@ -153,6 +157,23 @@ ], ) + features = [linker_flags, compiler_flags, sysroot_flags] + + if "mingw" in ctx.attr.target_full_name: + features.append( + feature( + name = "targets_windows", + enabled = True, + ) + ) + else: + features.append( + feature( + name = "supports_pic", + enabled = True + ) + ) + return cc_common.create_cc_toolchain_config_info( abi_libc_version = ctx.attr.abi_version, abi_version = ctx.attr.abi_version, @@ -160,17 +181,17 @@ ctx = ctx, compiler = "clang", cxx_builtin_include_directories = [ - ctx.attr.toolchain_dir, + ctx.attr.sysroot, ctx.attr.extra_include, "/usr/local/include", "/usr/local/lib/clang", ], - features = [linker_flags, compiler_flags, sysroot_flags], + features = features, host_system_name = "local", target_cpu = ctx.attr.target_cpu, target_libc = ctx.attr.target_cpu, target_system_name = ctx.attr.target_full_name, - toolchain_identifier = ctx.attr.toolchain_name, + toolchain_identifier = ctx.attr.target_full_name, tool_paths = tool_paths, ) @@ -178,8 +199,6 @@ implementation = _impl, attrs = { "abi_version": attr.string(default = "local"), - "bit_flag": attr.string(mandatory = True, values = ["-m32", "-m64"]), - "cpp_flag": attr.string(mandatory = True), "extra_compiler_flags": attr.string_list(), "extra_include": attr.string(mandatory = False), "extra_linker_flags": attr.string_list(), @@ -187,8 +206,6 @@ "sysroot": attr.string(mandatory = False), "target_cpu": attr.string(mandatory = True, values = ["aarch64", "ppc64", "systemz", "x86_32", "x86_64"]), "target_full_name": attr.string(mandatory = True), - "toolchain_dir": attr.string(mandatory = True), - "toolchain_name": attr.string(mandatory = True), }, provides = [CcToolchainConfigInfo], )
diff --git a/update_file_lists.sh b/update_file_lists.sh index 1ec1195..3ef366d 100755 --- a/update_file_lists.sh +++ b/update_file_lists.sh
@@ -27,10 +27,6 @@ get_variable_value $@ | grep "cc$\|inc$" } -get_proto_files_blacklisted() { - get_proto_files $@ | sed '/^google\/protobuf\/unittest_enormous_descriptor.proto$/d' -} - get_proto_files() { get_variable_value $@ | grep "pb.cc$" | sed "s/pb.cc/proto/" } @@ -58,7 +54,6 @@ LIBPROTOC_HEADERS=$(get_variable_value $MAKEFILE nobase_include_HEADERS | grep /compiler/) LITE_PROTOS=$(get_proto_files $MAKEFILE protoc_lite_outputs) PROTOS=$(get_proto_files $MAKEFILE protoc_outputs) -PROTOS_BLACKLISTED=$(get_proto_files_blacklisted $MAKEFILE protoc_outputs) WKT_PROTOS=$(get_variable_value $MAKEFILE nobase_dist_proto_DATA) COMMON_TEST_SOURCES=$(get_source_files $MAKEFILE COMMON_TEST_SOURCES) COMMON_LITE_TEST_SOURCES=$(get_source_files $MAKEFILE COMMON_LITE_TEST_SOURCES) @@ -118,13 +113,13 @@ # Replace file lists in cmake files. -CMAKE_PREFIX="\${protobuf_source_dir}/src/" +CMAKE_PREFIX="\${protobuf_SOURCE_DIR}/src/" set_cmake_value $CMAKE_DIR/libprotobuf-lite.cmake libprotobuf_lite_files $CMAKE_PREFIX $LIBPROTOBUF_LITE_SOURCES set_cmake_value $CMAKE_DIR/libprotobuf.cmake libprotobuf_files $CMAKE_PREFIX $LIBPROTOBUF_SOURCES set_cmake_value $CMAKE_DIR/libprotoc.cmake libprotoc_files $CMAKE_PREFIX $LIBPROTOC_SOURCES set_cmake_value $CMAKE_DIR/libprotoc.cmake libprotoc_headers $CMAKE_PREFIX $LIBPROTOC_HEADERS set_cmake_value $CMAKE_DIR/tests.cmake lite_test_protos "" $LITE_PROTOS -set_cmake_value $CMAKE_DIR/tests.cmake tests_protos "" $PROTOS_BLACKLISTED +set_cmake_value $CMAKE_DIR/tests.cmake tests_protos "" $PROTOS set_cmake_value $CMAKE_DIR/tests.cmake common_test_files $CMAKE_PREFIX '${common_lite_test_files}' $COMMON_TEST_SOURCES set_cmake_value $CMAKE_DIR/tests.cmake common_lite_test_files $CMAKE_PREFIX $COMMON_LITE_TEST_SOURCES set_cmake_value $CMAKE_DIR/tests.cmake tests_files $CMAKE_PREFIX $TEST_SOURCES