Sync from Piper @425656941

PROTOBUF_SYNC_PIPER
This commit is contained in:
Deanna Garcia 2022-02-01 18:24:53 +00:00
commit ab4585a695
644 changed files with 31898 additions and 25241 deletions

View File

@ -9,10 +9,10 @@ mergeable:
- and:
- must_include:
regex: 'release notes: yes'
message: 'Please include release notes: yes'
message: 'Include release notes: yes'
- must_include:
regex: '^(autotools|bazel|c#|c\+\+|cleanup|cmake|conformance tests|integration|go|java|javascript|objective-c|php|protoc|python|ruby|kotlin)'
message: 'Please include at least a language label (e.g., c++, java, python). Or apply one of the following labels: autotools, bazel, cmake, cleanup, conformance tests, integration, protoc.'
message: 'at least a language label (e.g., c++, java, python). Or apply one of the following labels: autotools, bazel, cmake, cleanup, conformance tests, integration, protoc.'
- must_include:
regex: 'release notes: no'
message: 'Please include release notes: no'
message: 'Include release notes: no'

265
BUILD
View File

@ -2,11 +2,13 @@
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"])
@ -26,7 +28,6 @@ ZLIB_DEPS = ["@zlib//:zlib"]
################################################################################
MSVC_COPTS = [
"/DHAVE_PTHREAD",
"/wd4018", # -Wno-sign-compare
"/wd4065", # switch statement contains 'default' but no 'case' labels
"/wd4146", # unary minus operator applied to unsigned type, result still unsigned
@ -46,7 +47,6 @@ MSVC_COPTS = [
COPTS = select({
":msvc": MSVC_COPTS,
"//conditions:default": [
"-DHAVE_PTHREAD",
"-DHAVE_ZLIB",
"-Wmissing-field-initializers",
"-Woverloaded-virtual",
@ -65,6 +65,13 @@ create_compiler_config_setting(
],
)
# Android NDK builds can specify different crosstool_top flags to choose which
# STL they use for C++. We need these multiple variants to catch all of those
# versions of crosstool_top and reliably detect Android.
#
# For more info on the various crosstool_tops used by NDK Bazel builds, see:
# https://docs.bazel.build/versions/master/android-ndk.html#configuring-the-stl
config_setting(
name = "android",
values = {
@ -76,6 +83,17 @@ config_setting(
],
)
config_setting(
name = "android-stlport",
values = {
"crosstool_top": "@androidndk//:toolchain-stlport",
},
visibility = [
# Public, but Protobuf only visibility.
"//:__subpackages__",
],
)
config_setting(
name = "android-libcpp",
values = {
@ -98,11 +116,24 @@ config_setting(
],
)
config_setting(
name = "android-default",
values = {
"crosstool_top": "@androidndk//:default_crosstool",
},
visibility = [
# Public, but Protobuf only visibility.
"//:__subpackages__",
],
)
# Android and MSVC builds do not need to link in a separate pthread library.
LINK_OPTS = select({
":android": [],
":android-stlport": [],
":android-libcpp": [],
":android-gnu-libstdcpp": [],
":android-default": [],
":msvc": [
# Suppress linker warnings about files with no symbols defined.
"-ignore:4221",
@ -147,6 +178,7 @@ cc_library(
"src/google/protobuf/message_lite.cc",
"src/google/protobuf/parse_context.cc",
"src/google/protobuf/repeated_field.cc",
"src/google/protobuf/repeated_ptr_field.cc",
"src/google/protobuf/stubs/bytestream.cc",
"src/google/protobuf/stubs/common.cc",
"src/google/protobuf/stubs/int128.cc",
@ -488,6 +520,70 @@ cc_binary(
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
################################################################################
@ -560,6 +656,8 @@ RELATIVE_TEST_PROTOS = [
TEST_PROTOS = ["src/" + s for s in RELATIVE_TEST_PROTOS]
GENERIC_RELATIVE_TEST_PROTOS = [
"google/protobuf/map_proto2_unittest.proto",
"google/protobuf/map_unittest.proto",
"google/protobuf/unittest.proto",
"google/protobuf/unittest_arena.proto",
"google/protobuf/unittest_custom_options.proto",
@ -953,7 +1051,6 @@ py_proto_library(
protoc = ":protoc",
py_libs = [
":python_srcs",
"@six//:six",
],
srcs_version = "PY2AND3",
visibility = ["//visibility:public"],
@ -1087,7 +1184,7 @@ proto_library(
name = "generated_protos_proto",
srcs = [
"src/google/protobuf/unittest_import_public.proto",
"unittest_gen.proto",
"unittest_gen_import.proto",
],
)
@ -1095,7 +1192,7 @@ py_proto_library(
name = "generated_protos_py",
srcs = [
"src/google/protobuf/unittest_import_public.proto",
"unittest_gen.proto",
"unittest_gen_import.proto",
],
default_runtime = "",
protoc = ":protoc",
@ -1225,6 +1322,19 @@ cc_binary(
# ],
# )
java_proto_library(
name = "java_test_protos",
deps = [":generic_test_protos"],
visibility = ["//java:__subpackages__"],
)
java_lite_proto_library(
name = "java_lite_test_protos",
deps = [":generic_test_protos"],
visibility = ["//java:__subpackages__"],
)
java_proto_library(
name = "test_messages_proto2_java_proto",
visibility = [
@ -1318,3 +1428,146 @@ filegroup(
srcs = glob(["**/*.bzl"]),
visibility = ["//visibility:public"],
)
# Kotlin proto rules
genrule(
name = "gen_kotlin_unittest_lite",
srcs = [
"src/google/protobuf/unittest_lite.proto",
"src/google/protobuf/unittest_import_lite.proto",
"src/google/protobuf/unittest_import_public_lite.proto",
"src/google/protobuf/map_lite_unittest.proto",
],
outs = [
"TestAllTypesLiteKt.kt",
"ForeignMessageLiteKt.kt",
"TestAllExtensionsLiteKt.kt",
"TestEmptyMessageLiteKt.kt",
"TestEmptyMessageWithExtensionsLiteKt.kt",
"TestMapLiteKt.kt",
"OptionalGroup_extension_liteKt.kt",
"RepeatedGroup_extension_liteKt.kt",
],
visibility = ["//java:__subpackages__"],
cmd = "$(location //:protoc) " +
"--kotlin_out=lite:$(@D) -Isrc/ " +
"$(locations src/google/protobuf/unittest_lite.proto) && " +
"$(location //:protoc) " +
"--kotlin_out=lite:$(@D) -Isrc/ " +
"$(locations src/google/protobuf/map_lite_unittest.proto) && " +
"cp $(@D)/com/google/protobuf/TestAllTypesLiteKt.kt " +
"$(location TestAllTypesLiteKt.kt) && " +
"cp $(@D)/com/google/protobuf/ForeignMessageLiteKt.kt " +
"$(location ForeignMessageLiteKt.kt) && " +
"cp $(@D)/com/google/protobuf/TestAllExtensionsLiteKt.kt " +
"$(location TestAllExtensionsLiteKt.kt) && " +
"cp $(@D)/com/google/protobuf/TestAllTypesLiteKt.kt " +
"$(location TestAllTypesLiteKt.kt) && " +
"cp $(@D)/com/google/protobuf/TestEmptyMessageLiteKt.kt " +
"$(location TestEmptyMessageLiteKt.kt) && " +
"cp $(@D)/com/google/protobuf/TestEmptyMessageWithExtensionsLiteKt.kt " +
"$(location TestEmptyMessageWithExtensionsLiteKt.kt) && " +
"cp $(@D)/protobuf_unittest/TestMapLiteKt.kt " +
"$(location TestMapLiteKt.kt) && " +
"cp $(@D)/com/google/protobuf/OptionalGroup_extension_liteKt.kt " +
"$(location OptionalGroup_extension_liteKt.kt) && " +
"cp $(@D)/com/google/protobuf/RepeatedGroup_extension_liteKt.kt " +
"$(location RepeatedGroup_extension_liteKt.kt)",
tools = [":protoc"],
)
genrule(
name = "gen_kotlin_unittest",
srcs = [
"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",
],
outs = [
"TestAllTypesKt.kt",
"ForeignMessageKt.kt",
"TestAllExtensionsKt.kt",
"TestEmptyMessageKt.kt",
"TestEmptyMessageWithExtensionsKt.kt",
"TestIntIntMapKt.kt",
"TestEnumMapKt.kt",
"TestMapsKt.kt",
"OptionalGroup_extensionKt.kt",
"RepeatedGroup_extensionKt.kt",
],
visibility = ["//java:__subpackages__"],
cmd = "$(location //:protoc) " +
"--kotlin_out=shared,immutable:$(@D) -Isrc/ " +
"$(location src/google/protobuf/unittest.proto) && " +
"$(location //:protoc) " +
"--kotlin_out=shared,immutable:$(@D) -Isrc/ " +
"$(location src/google/protobuf/map_proto2_unittest.proto) && " +
"cp $(@D)/protobuf_unittest/TestAllTypesKt.kt " +
"$(location TestAllTypesKt.kt) && " +
"cp $(@D)/protobuf_unittest/ForeignMessageKt.kt " +
"$(location ForeignMessageKt.kt) && " +
"cp $(@D)/protobuf_unittest/TestAllExtensionsKt.kt " +
"$(location TestAllExtensionsKt.kt) && " +
"cp $(@D)/protobuf_unittest/TestEmptyMessageKt.kt " +
"$(location TestEmptyMessageKt.kt) && " +
"cp $(@D)/protobuf_unittest/TestEmptyMessageWithExtensionsKt.kt " +
"$(location TestEmptyMessageWithExtensionsKt.kt) && " +
"cp $(@D)/protobuf_unittest/TestIntIntMapKt.kt " +
"$(location TestIntIntMapKt.kt) && " +
"cp $(@D)/protobuf_unittest/TestEnumMapKt.kt " +
"$(location TestEnumMapKt.kt) && " +
"cp $(@D)/protobuf_unittest/TestMapsKt.kt " +
"$(location TestMapsKt.kt) && " +
"cp $(@D)/protobuf_unittest/OptionalGroup_extensionKt.kt " +
"$(location OptionalGroup_extensionKt.kt) && " +
"cp $(@D)/protobuf_unittest/RepeatedGroup_extensionKt.kt " +
"$(location RepeatedGroup_extensionKt.kt)",
tools = ["//:protoc"],
)
genrule(
name = "gen_kotlin_proto3_unittest_lite",
srcs = [
"src/google/protobuf/unittest_proto3_lite.proto",
"src/google/protobuf/unittest_import.proto",
"src/google/protobuf/unittest_import_public.proto",
],
outs = [
"TestAllTypesProto3LiteKt.kt",
"TestEmptyMessageProto3LiteKt.kt",
],
visibility = ["//java:__subpackages__"],
cmd = "$(location //:protoc) " +
"--kotlin_out=lite:$(@D) -Isrc/ " +
"$(location src/google/protobuf/unittest_proto3_lite.proto) && " +
"cp $(@D)/proto3_lite_unittest/TestAllTypesKt.kt " +
"$(location TestAllTypesProto3LiteKt.kt) && " +
"cp $(@D)/proto3_lite_unittest/TestEmptyMessageKt.kt " +
"$(location TestEmptyMessageProto3LiteKt.kt)",
tools = ["//:protoc"],
)
genrule(
name = "gen_kotlin_proto3_unittest",
srcs = [
"src/google/protobuf/unittest_proto3.proto",
"src/google/protobuf/unittest_import.proto",
"src/google/protobuf/unittest_import_public.proto",
],
outs = [
"TestAllTypesProto3Kt.kt",
"TestEmptyMessageProto3Kt.kt",
],
visibility = ["//java:__subpackages__"],
cmd = "$(location //:protoc) " +
"--kotlin_out=shared,immutable:$(@D) -Isrc/ " +
"$(location src/google/protobuf/unittest_proto3.proto) && " +
"cp $(@D)/proto3_unittest/TestAllTypesKt.kt " +
"$(location TestAllTypesProto3Kt.kt) && " +
"cp $(@D)/proto3_unittest/TestEmptyMessageKt.kt " +
"$(location TestEmptyMessageProto3Kt.kt)",
tools = ["//:protoc"],
)

View File

@ -1,6 +1,110 @@
Unreleased Changes (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
Protocol Compiler
Ruby
* JSON will now output shorter strings for double and float fields when possible
without losing precision.
* Encoding and decoding of binary format will now work properly on big-endian
systems.
* UTF-8 verification was fixed to properly reject surrogate code points.
* Unknown enums for proto2 protos now properly implement proto2's behavior of
putting such values in unknown fields.
2022-01-28 version 3.19.4 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
Python
* Make libprotobuf symbols local on OSX to fix issue #9395 (#9435)
Ruby
* Fixed a data loss bug that could occur when the number of `optional`
fields in a message is an exact multiple of 32. (#9440).
PHP
* Fixed a data loss bug that could occur when the number of `optional`
fields in a message is an exact multiple of 32. (#9440).
2022-01-10 version 3.19.3 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
Python
* Fix missing Windows wheel for Python 3.10 on PyPI
2022-01-05 version 3.19.2 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
Java
* Improve performance characteristics of UnknownFieldSet parsing (#9371)
* This release addresses a Security Advisory for Java users
(https://github.com/protocolbuffers/protobuf/security/advisories/GHSA-wrvw-hg22-4m67)
2022-01-05 version 3.18.2 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
Java
* Improve performance characteristics of UnknownFieldSet parsing (#9371)
* This release addresses a Security Advisory for Java users
(https://github.com/protocolbuffers/protobuf/security/advisories/GHSA-wrvw-hg22-4m67)
2022-01-05 version 3.16.1 (Java)
Java
* Improve performance characteristics of UnknownFieldSet parsing (#9371)
* This release addresses a Security Advisory for Java users
(https://github.com/protocolbuffers/protobuf/security/advisories/GHSA-wrvw-hg22-4m67)
2021-10-28 version 3.19.1 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
Bazel
* Ensure that release archives contain everything needed for Bazel (#9131)
* Align dependency handling with Bazel best practices (#9165)
JavaScript
* Fix `ReferenceError: window is not defined` when getting the global object (#9156)
Ruby
* Fix memory leak in MessageClass.encode (#9150)
2021-10-15 version 3.19.0 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)
C++
* Make proto2::Message::DiscardUnknownFields() non-virtual
* Separate RepeatedPtrField into its own header file
* For default floating point values of 0, consider all bits significant
* cmake: support `MSVC_RUNTIME_LIBRARY` property (#8851)
* Fix shadowing warnings (#8926)
* Fix for issue #8484, constant initialization doesn't compile in msvc clang-cl environment (#8993)
* Fix build on AIX and SunOS (#8373) (#9065)
* Add Android stlport and default toolchains to BUILD. (#8290)
Java
* For default floating point values of 0, consider all bits significant
* Annotate `//java/com/google/protobuf/util/...` with nullness annotations
* Use ArrayList copy constructor (#7853)
Kotlin
* Switch Kotlin proto DSLs to be implemented with inline value classes
* Fix inlining and deprecation for repeated string fields in kotlin (#9120)
Python
* Proto2 DecodeError now includes message name in error message
* Make MessageToDict convert map keys to strings (#8122)
* Add python-requires in setup.py (#8989)
* Add python 3.10 (#9034)
JavaScript
* Skip exports if not available by CommonJS (#8856)
* JS: Comply with CSP no-unsafe-eval. (#8864)
PHP
* Added "object" as a reserved name for PHP (#8962)
Ruby
* Override Map.clone to use Map's dup method (#7938)
* Ruby: build extensions for arm64-darwin (#8232)
* Add class method Timestamp.from_time to ruby well known types (#8562)
* Adopt pure ruby DSL implementation for JRuby (#9047)
* Add size to Map class (#8068)
* Fix for descriptor_pb.rb: google/protobuf should be required first (#9121)
C#
* Correctly set ExtensionRegistry when parsing with MessageParser, but using an already existing CodedInputStream (#7246)
* [C#] Make FieldDescriptor propertyName public (#7642)
2021-10-04 version 3.18.1 (C++/Java/Python/PHP/Objective-C/C#/Ruby/JavaScript)

View File

@ -1,9 +1,31 @@
# Contributing to Protocol Buffers
We welcome your contributions to protocol buffers. This doc describes the
We welcome some types of contributions to protocol buffers. This doc describes the
process to contribute patches to protobuf and the general guidelines we
expect contributors to follow.
## What We Accept
* Bug fixes with unit tests demonstrating the problem are very welcome.
We also appreciate bug reports, even when they don't come with a patch.
Bug fixes without tests are usually not accepted.
* New APIs and features with adequate test coverage and documentation
may be accepted if they do not compromise backwards
compatibility. However there's a fairly high bar of usefulness a new public
method must clear before it will be accepted. Features that are fine in
isolation are often rejected because they don't have enough impact to justify the
conceptual burden and ongoing maintenance cost. It's best to file an issue
and get agreement from maintainers on the value of a new feature before
working on a PR.
* Performance optimizations may be accepted if they have convincing benchmarks that demonstrate
an improvement and they do not significantly increase complexity.
* Changes to existing APIs are almost never accepted. Stability and
backwards compatibility are paramount. In the unlikely event a breaking change
is required, it must usually be implemented in google3 first.
* Changes to the wire and text formats are never accepted. Any breaking change
to these formats would have to be implemented as a completely new format.
We cannot begin generating protos that cannot be parsed by existing code.
## Before You Start
We accept patches in the form of github pull requests. If you are new to
@ -58,7 +80,7 @@ the final release.
* Create small PRs that are narrowly focused on addressing a single concern.
We often receive PRs that are trying to fix several things at a time, but if
only one fix is considered acceptable, nothing gets merged and both author's
& review's time is wasted. Create more PRs to address different concerns and
& reviewer's time is wasted. Create more PRs to address different concerns and
everyone will be happy.
* For speculative changes, consider opening an issue and discussing it first.
If you are suggesting a behavioral or API change, make sure you get explicit

View File

@ -1011,6 +1011,7 @@ python_EXTRA_DIST= \
python/google/protobuf/internal/any_test.proto \
python/google/protobuf/internal/api_implementation.cc \
python/google/protobuf/internal/api_implementation.py \
python/google/protobuf/internal/builder.py \
python/google/protobuf/internal/containers.py \
python/google/protobuf/internal/decoder.py \
python/google/protobuf/internal/descriptor_database_test.py \
@ -1426,7 +1427,6 @@ EXTRA_DIST = $(@DIST_LANG@_EXTRA_DIST) \
examples/pubspec.yaml \
protobuf.bzl \
protobuf_deps.bzl \
third_party/six.BUILD \
third_party/zlib.BUILD \
util/python/BUILD \
internal.bzl

View File

@ -35,9 +35,6 @@ Pod::Spec.new do |s|
# Do not let src/google/protobuf/stubs/time.h override system API
'USE_HEADERMAP' => 'NO',
'ALWAYS_SEARCH_USER_PATHS' => 'NO',
# Configure tool is not being used for Xcode. When building, assume pthread is supported.
'GCC_PREPROCESSOR_DEFINITIONS' => '"$(inherited)" "HAVE_PTHREAD=1"',
}
end

View File

@ -5,10 +5,10 @@
# dependent projects use the :git notation to refer to the library.
Pod::Spec.new do |s|
s.name = 'Protobuf'
s.version = '3.18.1'
s.version = '3.19.4'
s.summary = 'Protocol Buffers v.3 runtime library for Objective-C.'
s.homepage = 'https://github.com/protocolbuffers/protobuf'
s.license = '3-Clause BSD License'
s.license = 'BSD-3-Clause'
s.authors = { 'The Protocol Buffers contributors' => 'protobuf@googlegroups.com' }
s.cocoapods_version = '>= 1.0'

View File

@ -27,7 +27,7 @@ http_archive(
)
# Load common dependencies.
load("//:protobuf_deps.bzl", "protobuf_deps")
load("//:protobuf_deps.bzl", "PROTOBUF_MAVEN_ARTIFACTS", "protobuf_deps")
protobuf_deps()
bind(
@ -36,68 +36,33 @@ bind(
)
load("@rules_jvm_external//:defs.bzl", "maven_install")
maven_install(
artifacts = [
"com.google.code.gson:gson:2.8.6",
"com.google.errorprone:error_prone_annotations:2.3.2",
"com.google.j2objc:j2obj_annotations:1.3",
"com.google.guava:guava:30.1.1-jre",
"com.google.truth:truth:1.1.2",
"junit:junit:4.12",
"org.easymock:easymock:3.2",
],
artifacts = PROTOBUF_MAVEN_ARTIFACTS,
# For updating instructions, see:
# https://github.com/bazelbuild/rules_jvm_external#updating-maven_installjson
maven_install_json = "//:maven_install.json",
repositories = [
"https://repo1.maven.org/maven2",
"https://repo.maven.apache.org/maven2",
],
# For updating instructions, see:
# https://github.com/bazelbuild/rules_jvm_external#updating-maven_installjson
maven_install_json = "//:maven_install.json",
)
load("@maven//:defs.bzl", "pinned_maven_install")
pinned_maven_install()
bind(
name = "guava",
actual = "@maven//:com_google_guava_guava",
)
bind(
name = "gson",
actual = "@maven//:com_google_code_gson_gson",
)
bind(
name = "error_prone_annotations",
actual = "@maven//:com_google_errorprone_error_prone_annotations",
)
bind(
name = "j2objc_annotations",
actual = "@maven//:com_google_j2objc_j2objc_annotations",
)
bind(
name = "junit",
actual = "@maven//:junit_junit",
)
bind(
name = "easymock",
actual = "@maven//:org_easymock_easymock",
)
bind(
name = "easymock_classextension",
actual = "@maven//:org_easymock_easymockclassextension",
)
bind(
name = "truth",
actual = "@maven//:com_google_truth_truth",
)
# For `cc_proto_blacklist_test` and `build_test`.
load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")
bazel_skylib_workspace()
load("@rules_pkg//:deps.bzl", "rules_pkg_dependencies")
rules_pkg_dependencies()
# For `kt_jvm_library`
load("@io_bazel_rules_kotlin//kotlin:repositories.bzl", "kotlin_repositories")
kotlin_repositories()
load("@io_bazel_rules_kotlin//kotlin:core.bzl", "kt_register_toolchains")
kt_register_toolchains()

View File

@ -38,7 +38,7 @@ dotnet restore
dotnet build -c %configuration% || goto error
echo Testing C#
dotnet test -c %configuration% -f netcoreapp2.1 Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
dotnet test -c %configuration% -f netcoreapp3.1 Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
dotnet test -c %configuration% -f net451 Google.Protobuf.Test\Google.Protobuf.Test.csproj || goto error
goto :EOF

View File

@ -4,8 +4,8 @@
This directory contains benchmarking schemas and data sets that you
can use to test a variety of performance scenarios against your
protobuf language runtime. If you are looking for performance
numbers of officially support languages, see [here](
https://github.com/protocolbuffers/protobuf/blob/master/docs/performance.md)
numbers of officially supported languages, see [Protobuf Performance](
https://github.com/protocolbuffers/protobuf/blob/master/docs/performance.md).
## Prerequisite

View File

@ -127,9 +127,6 @@ if (protobuf_DISABLE_RTTI)
endif()
find_package(Threads REQUIRED)
if (CMAKE_USE_PTHREADS_INIT)
add_definitions(-DHAVE_PTHREAD)
endif (CMAKE_USE_PTHREADS_INIT)
set(_protobuf_FIND_ZLIB)
if (protobuf_WITH_ZLIB)
@ -209,6 +206,8 @@ if (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(
/wd4018 # 'expression' : signed/unsigned mismatch

View File

@ -41,6 +41,8 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\php\php_gene
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\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
@ -48,6 +50,7 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\descriptor_database.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\duration.pb.h" include\google\protobuf\duration.pb.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\dynamic_message.h" include\google\protobuf\dynamic_message.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\empty.pb.h" include\google\protobuf\empty.pb.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\explicitly_constructed.h" include\google\protobuf\explicitly_constructed.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\extension_set.h" include\google\protobuf\extension_set.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\extension_set_inl.h" include\google\protobuf\extension_set_inl.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\field_access_listener.h" include\google\protobuf\field_access_listener.h
@ -92,6 +95,7 @@ copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\port_undef.inc" inclu
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\reflection.h" include\google\protobuf\reflection.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\reflection_ops.h" include\google\protobuf\reflection_ops.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\repeated_field.h" include\google\protobuf\repeated_field.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\repeated_ptr_field.h" include\google\protobuf\repeated_ptr_field.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\service.h" include\google\protobuf\service.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\source_context.pb.h" include\google\protobuf\source_context.pb.h
copy "${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\struct.pb.h" include\google\protobuf\struct.pb.h

View File

@ -2,9 +2,9 @@ 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_table_driven_lite.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
@ -38,15 +38,13 @@ set(libprotobuf_lite_includes
${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_table_driven.h
${protobuf_source_dir}/src/google/protobuf/generated_message_table_driven_lite.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_tctable_impl.inc
${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

View File

@ -14,7 +14,6 @@ set(libprotobuf_files
${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_table_driven.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

View File

@ -91,6 +91,8 @@ set(libprotoc_files
${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
@ -117,6 +119,7 @@ set(libprotoc_headers
${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
)

View File

@ -110,16 +110,6 @@ function(_protobuf_find_libraries name filename)
endif()
endfunction()
# Internal function: find threads library
function(_protobuf_find_threads)
set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
find_package(Threads)
if(Threads_FOUND)
list(APPEND PROTOBUF_LIBRARIES ${CMAKE_THREAD_LIBS_INIT})
set(PROTOBUF_LIBRARIES "${PROTOBUF_LIBRARIES}" PARENT_SCOPE)
endif()
endfunction()
#
# Main.
#
@ -139,10 +129,6 @@ _protobuf_find_libraries(Protobuf_LITE protobuf-lite)
# The Protobuf Protoc Library
_protobuf_find_libraries(Protobuf_PROTOC protoc)
if(UNIX)
_protobuf_find_threads()
endif()
# Set the include directory
get_target_property(Protobuf_INCLUDE_DIRS protobuf::libprotobuf
INTERFACE_INCLUDE_DIRECTORIES)

View File

@ -131,6 +131,7 @@ 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
@ -155,6 +156,7 @@ set(tests_files
${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

View File

@ -361,7 +361,7 @@ class ConformanceJava {
case TEXT_FORMAT:
return Conformance.ConformanceResponse.newBuilder()
.setTextPayload(TextFormat.printToString(testMessage))
.setTextPayload(TextFormat.printer().printToString(testMessage))
.build();
default:

View File

@ -39,8 +39,8 @@ import sys
import os
from google.protobuf import json_format
from google.protobuf import message
from google.protobuf import test_messages_proto3_pb2
from google.protobuf import test_messages_proto2_pb2
from google3.third_party.protobuf import test_messages_proto3_pb2
from google3.third_party.protobuf import test_messages_proto2_pb2
from google.protobuf import text_format
import conformance_pb2

View File

@ -162,7 +162,7 @@ void ForkPipeRunner::RunTest(
// We failed to read from the child, assume a crash and try to reap.
GOOGLE_LOG(INFO) << "Trying to reap child, pid=" << child_pid_;
int status;
int status = 0;
waitpid(child_pid_, &status, WEXITED);
string error_msg;

View File

@ -5,7 +5,7 @@
<title>Google Protocol Buffers tools</title>
<summary>Tools for Protocol Buffers - Google's data interchange format.</summary>
<description>See project site for more info.</description>
<version>3.18.1</version>
<version>3.19.4</version>
<authors>Google Inc.</authors>
<owners>protobuf-packages</owners>
<licenseUrl>https://github.com/protocolbuffers/protobuf/blob/master/LICENSE</licenseUrl>

8
csharp/NuGet.Config Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<!--To inherit the global NuGet package sources remove the <clear/> line below -->
<clear />
<add key="NuGet.org (v3)" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>

View File

@ -1,7 +1,7 @@
@rem Builds Google.Protobuf NuGet packages
dotnet restore src/Google.Protobuf.sln
dotnet pack -c Release src/Google.Protobuf.sln || goto :error
dotnet pack -c Release src/Google.Protobuf.sln -p:ContinuousIntegrationBuild=true || goto :error
goto :EOF

View File

@ -10,8 +10,8 @@ dotnet restore $SRC/Google.Protobuf.sln
dotnet build -c $CONFIG $SRC/Google.Protobuf.sln
echo Running tests.
# Only test netcoreapp2.1, which uses the .NET Core runtime.
# Only test netcoreapp3.1, which uses the .NET Core runtime.
# If we want to test the .NET 4.5 version separately, we could
# run Mono explicitly. However, we don't have any differences between
# the .NET 4.5 and netstandard2.1 assemblies.
dotnet test -c $CONFIG -f netcoreapp2.1 $SRC/Google.Protobuf.Test/Google.Protobuf.Test.csproj
dotnet test -c $CONFIG -f netcoreapp3.1 $SRC/Google.Protobuf.Test/Google.Protobuf.Test.csproj

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net451;netcoreapp2.1</TargetFrameworks>
<TargetFrameworks>net451;netcoreapp3.1</TargetFrameworks>
<AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<IsPackable>False</IsPackable>

View File

@ -22,7 +22,7 @@ function run_test() {
dotnet restore src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
dotnet build -c Release src/Google.Protobuf/Google.Protobuf.csproj
dotnet build -c Release src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
dotnet run -c Release -f netcoreapp2.1 -p src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
dotnet run -c Release -f netcoreapp3.1 -p src/Google.Protobuf.Test/Google.Protobuf.Test.csproj
}
set -ex

View File

@ -16,5 +16,5 @@ Invoke-WebRequest -Uri $InstallScriptUrl -OutFile $InstallScriptPath
# The SDK versions to install should be kept in sync with versions
# installed by kokoro/linux/dockerfile/test/csharp/Dockerfile
&$InstallScriptPath -Version 2.1.802
&$InstallScriptPath -Version 5.0.102
&$InstallScriptPath -Version 3.1.415
&$InstallScriptPath -Version 6.0.100

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<OutputType>Exe</OutputType>
<StartupObject>Google.Protobuf.Examples.AddressBook.Program</StartupObject>
<IsPackable>False</IsPackable>

View File

@ -32,9 +32,10 @@ namespace Google.Protobuf.Examples.AddressBook {
"Eg4KBm51bWJlchgBIAEoCRIoCgR0eXBlGAIgASgOMhoudHV0b3JpYWwuUGVy",
"c29uLlBob25lVHlwZSIrCglQaG9uZVR5cGUSCgoGTU9CSUxFEAASCAoESE9N",
"RRABEggKBFdPUksQAiIvCgtBZGRyZXNzQm9vaxIgCgZwZW9wbGUYASADKAsy",
"EC50dXRvcmlhbC5QZXJzb25CZgobY29tLmV4YW1wbGUudHV0b3JpYWwucHJv",
"dG9zQhFBZGRyZXNzQm9va1Byb3Rvc1ABWgsuLi90dXRvcmlhbKoCJEdvb2ds",
"ZS5Qcm90b2J1Zi5FeGFtcGxlcy5BZGRyZXNzQm9va2IGcHJvdG8z"));
"EC50dXRvcmlhbC5QZXJzb25ClQEKG2NvbS5leGFtcGxlLnR1dG9yaWFsLnBy",
"b3Rvc0IRQWRkcmVzc0Jvb2tQcm90b3NQAVo6Z2l0aHViLmNvbS9wcm90b2Nv",
"bGJ1ZmZlcnMvcHJvdG9idWYvZXhhbXBsZXMvZ28vdHV0b3JpYWxwYqoCJEdv",
"b2dsZS5Qcm90b2J1Zi5FeGFtcGxlcy5BZGRyZXNzQm9va2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {

View File

@ -36,7 +36,7 @@ namespace Google.Protobuf.Benchmarks
{
class Program
{
// typical usage: dotnet run -c Release -f netcoreapp2.1
// typical usage: dotnet run -c Release -f netcoreapp3.1
// (this can profile both .net core and .net framework; for some reason
// if you start from "-f net461", it goes horribly wrong)
public static void Main(string[] args)

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<OutputType>Exe</OutputType>
<IsPackable>False</IsPackable>
</PropertyGroup>

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>netcoreapp3.1</TargetFramework>
<OutputType>Exe</OutputType>
<IsPackable>False</IsPackable>
</PropertyGroup>

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<!--
This TestProtos project is kept separate from the original test project for many reasons.
@ -15,7 +15,7 @@
<!-- 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-preview.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>

View File

@ -25,7 +25,7 @@ namespace ProtobufTestMessages.Proto2 {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cipnb29nbGUvcHJvdG9idWYvdGVzdF9tZXNzYWdlc19wcm90bzIucHJvdG8S",
"HXByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8yIqQ+ChJUZXN0QWxsVHlw",
"HXByb3RvYnVmX3Rlc3RfbWVzc2FnZXMucHJvdG8yIsQ+ChJUZXN0QWxsVHlw",
"ZXNQcm90bzISFgoOb3B0aW9uYWxfaW50MzIYASABKAUSFgoOb3B0aW9uYWxf",
"aW50NjQYAiABKAMSFwoPb3B0aW9uYW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aGgoNT3B0aW9uYWxHcm91cBIJCgFhGAEgASgFIhYKFE51",
"bGxIeXBvdGhlc2lzUHJvdG8yIi8KDkVudW1Pbmx5UHJvdG8yIh0KBEJvb2wS",
"CgoGa0ZhbHNlEAASCQoFa1RydWUQASpGChFGb3JlaWduRW51bVByb3RvMhIP",
"CgtGT1JFSUdOX0ZPTxAAEg8KC0ZPUkVJR05fQkFSEAESDwoLRk9SRUlHTl9C",
"QVoQAjpKCg9leHRlbnNpb25faW50MzISMS5wcm90b2J1Zl90ZXN0X21lc3Nh",
"Z2VzLnByb3RvMi5UZXN0QWxsVHlwZXNQcm90bzIYeCABKAVCLwooY29tLmdv",
"b2dsZS5wcm90b2J1Zl90ZXN0X21lc3NhZ2VzLnByb3RvMkgB+AEB"));
"b3RvMhh4IAEoBUIvCihjb20uZ29vZ2xlLnByb3RvYnVmX3Rlc3RfbWVzc2Fn",
"ZXMucHJvdG8ySAH4AQE="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::ProtobufTestMessages.Proto2.ForeignEnumProto2), }, new pb::Extension[] { TestMessagesProto2Extensions.ExtensionInt32 }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2), global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Parser, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalNestedMessage", "OptionalForeignMessage", "OptionalNestedEnum", "OptionalForeignEnum", "OptionalStringPiece", "OptionalCord", "RecursiveMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedStringPiece", "RepeatedCord", "PackedInt32", "PackedInt64", "PackedUint32", "PackedUint64", "PackedSint32", "PackedSint64", "PackedFixed32", "PackedFixed64", "PackedSfixed32", "PackedSfixed64", "PackedFloat", "PackedDouble", "PackedBool", "PackedNestedEnum", "UnpackedInt32", "UnpackedInt64", "UnpackedUint32", "UnpackedUint64", "UnpackedSint32", "UnpackedSint64", "UnpackedFixed32", "UnpackedFixed64", "UnpackedSfixed32", "UnpackedSfixed64", "UnpackedFloat", "UnpackedDouble", "UnpackedBool", "UnpackedNestedEnum", "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapStringBytes", "MapStringNestedMessage", "MapStringForeignMessage", "MapStringNestedEnum", "MapStringForeignEnum", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes", "OneofBool", "OneofUint64", "OneofFloat", "OneofDouble", "OneofEnum", "Data", "DefaultInt32", "DefaultInt64", "DefaultUint32", "DefaultUint64", "DefaultSint32", "DefaultSint64", "DefaultFixed32", "DefaultFixed64", "DefaultSfixed32", "DefaultSfixed64", "DefaultFloat", "DefaultDouble", "DefaultBool", "DefaultString", "Fieldname1", "FieldName2", "FieldName3", "FieldName4", "Field0Name5", "Field0Name6", "FieldName7", "FieldName8", "FieldName9", "FieldName10", "FIELDNAME11", "FIELDName12", "FieldName13", "FieldName14", "FieldName15", "FieldName16", "FieldName17", "FieldName18" }, new[]{ "OneofField" }, new[]{ typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedEnum) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage), global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage.Parser, new[]{ "A", "Corecursive" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2), global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Parser, new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalNestedMessage", "OptionalForeignMessage", "OptionalNestedEnum", "OptionalForeignEnum", "OptionalStringPiece", "OptionalCord", "RecursiveMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedStringPiece", "RepeatedCord", "PackedInt32", "PackedInt64", "PackedUint32", "PackedUint64", "PackedSint32", "PackedSint64", "PackedFixed32", "PackedFixed64", "PackedSfixed32", "PackedSfixed64", "PackedFloat", "PackedDouble", "PackedBool", "PackedNestedEnum", "UnpackedInt32", "UnpackedInt64", "UnpackedUint32", "UnpackedUint64", "UnpackedSint32", "UnpackedSint64", "UnpackedFixed32", "UnpackedFixed64", "UnpackedSfixed32", "UnpackedSfixed64", "UnpackedFloat", "UnpackedDouble", "UnpackedBool", "UnpackedNestedEnum", "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapStringBytes", "MapStringNestedMessage", "MapStringForeignMessage", "MapStringNestedEnum", "MapStringForeignEnum", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes", "OneofBool", "OneofUint64", "OneofFloat", "OneofDouble", "OneofEnum", "Data", "DefaultInt32", "DefaultInt64", "DefaultUint32", "DefaultUint64", "DefaultSint32", "DefaultSint64", "DefaultFixed32", "DefaultFixed64", "DefaultSfixed32", "DefaultSfixed64", "DefaultFloat", "DefaultDouble", "DefaultBool", "DefaultString", "DefaultBytes", "Fieldname1", "FieldName2", "FieldName3", "FieldName4", "Field0Name5", "Field0Name6", "FieldName7", "FieldName8", "FieldName9", "FieldName10", "FIELDNAME11", "FIELDName12", "FieldName13", "FieldName14", "FieldName15", "FieldName16", "FieldName17", "FieldName18" }, new[]{ "OneofField" }, new[]{ typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedEnum) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage), global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.NestedMessage.Parser, new[]{ "A", "Corecursive" }, null, null, null, null),
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.Data), global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.Data.Parser, new[]{ "GroupInt32", "GroupUint32" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.MessageSetCorrect), global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.MessageSetCorrect.Parser, null, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.MessageSetCorrectExtension1), global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.MessageSetCorrectExtension1.Parser, new[]{ "Str" }, null, null, new pb::Extension[] { global::ProtobufTestMessages.Proto2.TestAllTypesProto2.Types.MessageSetCorrectExtension1.Extensions.MessageSetExtension }, null),
@ -228,7 +230,8 @@ namespace ProtobufTestMessages.Proto2 {
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.ForeignMessageProto2), global::ProtobufTestMessages.Proto2.ForeignMessageProto2.Parser, new[]{ "C" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.UnknownToTestAllTypes), global::ProtobufTestMessages.Proto2.UnknownToTestAllTypes.Parser, new[]{ "OptionalInt32", "OptionalString", "NestedMessage", "OptionalGroup", "OptionalBool", "RepeatedInt32" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.UnknownToTestAllTypes.Types.OptionalGroup), global::ProtobufTestMessages.Proto2.UnknownToTestAllTypes.Types.OptionalGroup.Parser, new[]{ "A" }, null, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.NullHypothesisProto2), global::ProtobufTestMessages.Proto2.NullHypothesisProto2.Parser, null, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.EnumOnlyProto2), global::ProtobufTestMessages.Proto2.EnumOnlyProto2.Parser, null, null, new[]{ typeof(global::ProtobufTestMessages.Proto2.EnumOnlyProto2.Types.Bool) }, null, null)
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.EnumOnlyProto2), global::ProtobufTestMessages.Proto2.EnumOnlyProto2.Parser, null, null, new[]{ typeof(global::ProtobufTestMessages.Proto2.EnumOnlyProto2.Types.Bool) }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::ProtobufTestMessages.Proto2.OneStringProto2), global::ProtobufTestMessages.Proto2.OneStringProto2.Parser, new[]{ "Data" }, null, null, null, null)
}));
}
#endregion
@ -404,6 +407,7 @@ namespace ProtobufTestMessages.Proto2 {
defaultDouble_ = other.defaultDouble_;
defaultBool_ = other.defaultBool_;
defaultString_ = other.defaultString_;
defaultBytes_ = other.defaultBytes_;
fieldname1_ = other.fieldname1_;
fieldName2_ = other.fieldName2_;
FieldName3_ = other.FieldName3_;
@ -2394,6 +2398,32 @@ namespace ProtobufTestMessages.Proto2 {
defaultString_ = null;
}
/// <summary>Field number for the "default_bytes" field.</summary>
public const int DefaultBytesFieldNumber = 255;
private readonly static pb::ByteString DefaultBytesDefaultValue = pb::ByteString.FromBase64("am9zaHVh");
private pb::ByteString defaultBytes_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pb::ByteString DefaultBytes {
get { return defaultBytes_ ?? DefaultBytesDefaultValue; }
set {
defaultBytes_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Gets whether the "default_bytes" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool HasDefaultBytes {
get { return defaultBytes_ != null; }
}
/// <summary>Clears the value of the "default_bytes" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void ClearDefaultBytes() {
defaultBytes_ = null;
}
/// <summary>Field number for the "fieldname1" field.</summary>
public const int Fieldname1FieldNumber = 401;
private readonly static int Fieldname1DefaultValue = 0;
@ -3041,6 +3071,7 @@ namespace ProtobufTestMessages.Proto2 {
if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(DefaultDouble, other.DefaultDouble)) return false;
if (DefaultBool != other.DefaultBool) return false;
if (DefaultString != other.DefaultString) return false;
if (DefaultBytes != other.DefaultBytes) return false;
if (Fieldname1 != other.Fieldname1) return false;
if (FieldName2 != other.FieldName2) return false;
if (FieldName3 != other.FieldName3) return false;
@ -3184,6 +3215,7 @@ namespace ProtobufTestMessages.Proto2 {
if (HasDefaultDouble) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(DefaultDouble);
if (HasDefaultBool) hash ^= DefaultBool.GetHashCode();
if (HasDefaultString) hash ^= DefaultString.GetHashCode();
if (HasDefaultBytes) hash ^= DefaultBytes.GetHashCode();
if (HasFieldname1) hash ^= Fieldname1.GetHashCode();
if (HasFieldName2) hash ^= FieldName2.GetHashCode();
if (HasFieldName3) hash ^= FieldName3.GetHashCode();
@ -3477,6 +3509,10 @@ namespace ProtobufTestMessages.Proto2 {
output.WriteRawTag(242, 15);
output.WriteString(DefaultString);
}
if (HasDefaultBytes) {
output.WriteRawTag(250, 15);
output.WriteBytes(DefaultBytes);
}
if (HasFieldname1) {
output.WriteRawTag(136, 25);
output.WriteInt32(Fieldname1);
@ -3815,6 +3851,10 @@ namespace ProtobufTestMessages.Proto2 {
output.WriteRawTag(242, 15);
output.WriteString(DefaultString);
}
if (HasDefaultBytes) {
output.WriteRawTag(250, 15);
output.WriteBytes(DefaultBytes);
}
if (HasFieldname1) {
output.WriteRawTag(136, 25);
output.WriteInt32(Fieldname1);
@ -4106,6 +4146,9 @@ namespace ProtobufTestMessages.Proto2 {
if (HasDefaultString) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(DefaultString);
}
if (HasDefaultBytes) {
size += 2 + pb::CodedOutputStream.ComputeBytesSize(DefaultBytes);
}
if (HasFieldname1) {
size += 2 + pb::CodedOutputStream.ComputeInt32Size(Fieldname1);
}
@ -4366,6 +4409,9 @@ namespace ProtobufTestMessages.Proto2 {
if (other.HasDefaultString) {
DefaultString = other.DefaultString;
}
if (other.HasDefaultBytes) {
DefaultBytes = other.DefaultBytes;
}
if (other.HasFieldname1) {
Fieldname1 = other.Fieldname1;
}
@ -4988,6 +5034,10 @@ namespace ProtobufTestMessages.Proto2 {
DefaultString = input.ReadString();
break;
}
case 2042: {
DefaultBytes = input.ReadBytes();
break;
}
case 3208: {
Fieldname1 = input.ReadInt32();
break;
@ -5594,6 +5644,10 @@ namespace ProtobufTestMessages.Proto2 {
DefaultString = input.ReadString();
break;
}
case 2042: {
DefaultBytes = input.ReadBytes();
break;
}
case 3208: {
Fieldname1 = input.ReadInt32();
break;
@ -8043,6 +8097,209 @@ namespace ProtobufTestMessages.Proto2 {
}
public sealed partial class OneStringProto2 : pb::IMessage<OneStringProto2>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<OneStringProto2> _parser = new pb::MessageParser<OneStringProto2>(() => new OneStringProto2());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<OneStringProto2> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::ProtobufTestMessages.Proto2.TestMessagesProto2Reflection.Descriptor.MessageTypes[5]; }
}
[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 OneStringProto2() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public OneStringProto2(OneStringProto2 other) : this() {
data_ = other.data_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public OneStringProto2 Clone() {
return new OneStringProto2(this);
}
/// <summary>Field number for the "data" field.</summary>
public const int DataFieldNumber = 1;
private readonly static string DataDefaultValue = "";
private string data_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Data {
get { return data_ ?? DataDefaultValue; }
set {
data_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Gets whether the "data" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool HasData {
get { return data_ != null; }
}
/// <summary>Clears the value of the "data" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void ClearData() {
data_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as OneStringProto2);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(OneStringProto2 other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Data != other.Data) 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 (HasData) hash ^= Data.GetHashCode();
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 (HasData) {
output.WriteRawTag(10);
output.WriteString(Data);
}
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 (HasData) {
output.WriteRawTag(10);
output.WriteString(Data);
}
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 (HasData) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Data);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(OneStringProto2 other) {
if (other == null) {
return;
}
if (other.HasData) {
Data = other.Data;
}
_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: {
Data = 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: {
Data = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}

View File

@ -840,7 +840,7 @@ namespace Google.Protobuf.Collections
var list2 = new RepeatedField<double> { SampleNaNs.Regular, SampleNaNs.PayloadFlipped };
var list3 = new RepeatedField<double> { SampleNaNs.Regular, SampleNaNs.SignallingFlipped };
// All SampleNaNs have the same hashcode under certain targets (e.g. netcoreapp2.1)
// All SampleNaNs have the same hashcode under certain targets (e.g. netcoreapp3.1)
EqualityTester.AssertInequality(list1, list2, checkHashcode: false);
EqualityTester.AssertEquality(list1, list3);
Assert.True(list1.Contains(SampleNaNs.SignallingFlipped));

View File

@ -380,5 +380,18 @@ namespace Google.Protobuf
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);
}
}
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net451;netcoreapp2.1;net50</TargetFrameworks>
<TargetFrameworks>net451;netcoreapp3.1;net60</TargetFrameworks>
<AssemblyOriginatorKeyFile>../../keys/Google.Protobuf.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<IsPackable>False</IsPackable>
@ -21,7 +21,7 @@
<!-- 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-preview.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>

View File

@ -35,6 +35,7 @@ using Google.Protobuf.TestProtos;
using Google.Protobuf.WellKnownTypes;
using NUnit.Framework;
using ProtobufTestMessages.Proto2;
using ProtobufTestMessages.Proto3;
using System;
using UnitTest.Issues.TestProtos;
@ -551,13 +552,9 @@ namespace Google.Protobuf
}
[Test]
// Skip these test cases in .NET 5 because floating point parsing supports bigger values.
// These big values won't throw an error in the test.
#if !NET5_0
[TestCase("1.7977e308")]
[TestCase("-1.7977e308")]
[TestCase("1e309")]
#endif
[TestCase("1,0")]
[TestCase("1.0.0")]
[TestCase("+1")]
@ -922,10 +919,10 @@ namespace Google.Protobuf
}
[Test]
[TestCase("\"FOREIGN_BAR\"", ForeignEnum.ForeignBar)]
[TestCase("5", ForeignEnum.ForeignBar)]
[TestCase("100", (ForeignEnum)100)]
public void EnumValid(string value, ForeignEnum expectedValue)
[TestCase("\"FOREIGN_BAR\"", TestProtos.ForeignEnum.ForeignBar)]
[TestCase("5", TestProtos.ForeignEnum.ForeignBar)]
[TestCase("100", (TestProtos.ForeignEnum)100)]
public void EnumValid(string value, TestProtos.ForeignEnum expectedValue)
{
string json = "{ \"singleForeignEnum\": " + value + " }";
var parsed = TestAllTypes.Parser.ParseJson(json);
@ -1025,5 +1022,128 @@ namespace Google.Protobuf
{
return '"' + text + '"';
}
[Test]
public void ParseAllNullValues()
{
string json = @"{
""optionalInt32"": null,
""optionalInt64"": null,
""optionalUint32"": null,
""optionalUint64"": null,
""optionalSint32"": null,
""optionalSint64"": null,
""optionalFixed32"": null,
""optionalFixed64"": null,
""optionalSfixed32"": null,
""optionalSfixed64"": null,
""optionalFloat"": null,
""optionalDouble"": null,
""optionalBool"": null,
""optionalString"": null,
""optionalBytes"": null,
""optionalNestedEnum"": null,
""optionalNestedMessage"": null,
""repeatedInt32"": null,
""repeatedInt64"": null,
""repeatedUint32"": null,
""repeatedUint64"": null,
""repeatedSint32"": null,
""repeatedSint64"": null,
""repeatedFixed32"": null,
""repeatedFixed64"": null,
""repeatedSfixed32"": null,
""repeatedSfixed64"": null,
""repeatedFloat"": null,
""repeatedDouble"": null,
""repeatedBool"": null,
""repeatedString"": null,
""repeatedBytes"": null,
""repeatedNestedEnum"": null,
""repeatedNestedMessage"": null,
""mapInt32Int32"": null,
""mapBoolBool"": null,
""mapStringNestedMessage"": null
}";
TestAllTypesProto3 message = new TestAllTypesProto3();
message.OptionalInt32 = 1;
message.OptionalInt64 = 1;
message.OptionalUint32 = 1;
message.OptionalUint64 = 1;
message.OptionalSint32 = 1;
message.OptionalSint64 = 1;
message.OptionalFixed32 = 1;
message.OptionalFixed64 = 1;
message.OptionalSfixed32 = 1;
message.OptionalSfixed64 = 1;
message.OptionalFloat = 1;
message.OptionalDouble = 1;
message.OptionalBool = true;
message.OptionalString = "1";
message.OptionalBytes = ByteString.CopyFrom(new byte[] { 1 });
message.OptionalNestedEnum = TestAllTypesProto3.Types.NestedEnum.Bar;
message.OptionalNestedMessage = new TestAllTypesProto3.Types.NestedMessage();
message.RepeatedInt32.Add(1);
message.RepeatedInt64.Add(1);
message.RepeatedUint32.Add(1);
message.RepeatedUint64.Add(1);
message.RepeatedSint32.Add(1);
message.RepeatedSint64.Add(1);
message.RepeatedFixed32.Add(1);
message.RepeatedFixed64.Add(1);
message.RepeatedSfixed32.Add(1);
message.RepeatedSfixed64.Add(1);
message.RepeatedFloat.Add(1);
message.RepeatedDouble.Add(1);
message.RepeatedBool.Add(true);
message.RepeatedString.Add("1");
message.RepeatedBytes.Add(ByteString.CopyFrom(new byte[] { 1 }));
message.RepeatedNestedEnum.Add(TestAllTypesProto3.Types.NestedEnum.Bar);
message.RepeatedNestedMessage.Add(new TestAllTypesProto3.Types.NestedMessage());
message.MapInt32Int32.Add(1, 1);
message.MapBoolBool.Add(true, true);
message.MapStringNestedMessage.Add(" ", new TestAllTypesProto3.Types.NestedMessage());
JsonParser.Default.Merge(message, json);
Assert.AreEqual(0, message.OptionalInt32);
Assert.AreEqual(0, message.OptionalInt64);
Assert.AreEqual(0, message.OptionalUint32);
Assert.AreEqual(0, message.OptionalUint64);
Assert.AreEqual(0, message.OptionalSint32);
Assert.AreEqual(0, message.OptionalSint64);
Assert.AreEqual(0, message.OptionalFixed32);
Assert.AreEqual(0, message.OptionalFixed64);
Assert.AreEqual(0, message.OptionalSfixed32);
Assert.AreEqual(0, message.OptionalSfixed64);
Assert.AreEqual(0, message.OptionalFloat);
Assert.AreEqual(0, message.OptionalDouble);
Assert.AreEqual(false, message.OptionalBool);
Assert.AreEqual("", message.OptionalString);
Assert.AreEqual(ByteString.Empty, message.OptionalBytes);
Assert.AreEqual(TestAllTypesProto3.Types.NestedEnum.Foo, message.OptionalNestedEnum);
Assert.AreEqual(null, message.OptionalNestedMessage);
Assert.AreEqual(0, message.RepeatedInt32.Count);
Assert.AreEqual(0, message.RepeatedInt64.Count);
Assert.AreEqual(0, message.RepeatedUint32.Count);
Assert.AreEqual(0, message.RepeatedUint64.Count);
Assert.AreEqual(0, message.RepeatedSint32.Count);
Assert.AreEqual(0, message.RepeatedSint64.Count);
Assert.AreEqual(0, message.RepeatedFixed32.Count);
Assert.AreEqual(0, message.RepeatedFixed64.Count);
Assert.AreEqual(0, message.RepeatedSfixed32.Count);
Assert.AreEqual(0, message.RepeatedFloat.Count);
Assert.AreEqual(0, message.RepeatedDouble.Count);
Assert.AreEqual(0, message.RepeatedBool.Count);
Assert.AreEqual(0, message.RepeatedString.Count);
Assert.AreEqual(0, message.RepeatedBytes.Count);
Assert.AreEqual(0, message.RepeatedNestedEnum.Count);
Assert.AreEqual(0, message.RepeatedNestedMessage.Count);
Assert.AreEqual(0, message.MapInt32Int32.Count);
Assert.AreEqual(0, message.MapBoolBool.Count);
Assert.AreEqual(0, message.MapStringNestedMessage.Count);
}
}
}

View File

@ -199,12 +199,8 @@ namespace Google.Protobuf
[TestCase("1e-")]
[TestCase("--")]
[TestCase("--1")]
// Skip these test cases in .NET 5 because floating point parsing supports bigger values.
// These big values won't throw an error in the test.
#if !NET5_0
[TestCase("-1.7977e308")]
[TestCase("1.7977e308")]
#endif
public void InvalidNumberValue(string json)
{
AssertThrowsAfter(json);

View File

@ -124,6 +124,7 @@ namespace Google.Protobuf.Reflection
}
Assert.AreEqual(10, file.SerializedData[0]);
TestDescriptorToProto(file.ToProto, file.Proto);
}
[Test]
@ -231,6 +232,7 @@ namespace Google.Protobuf.Reflection
{
Assert.AreEqual(i, messageType.EnumTypes[i].Index);
}
TestDescriptorToProto(messageType.ToProto, messageType.Proto);
}
[Test]
@ -294,6 +296,11 @@ namespace Google.Protobuf.Reflection
// For a field in a regular onoef, ContainingOneof and RealContainingOneof should be the same.
Assert.AreEqual("oneof_field", fieldInOneof.ContainingOneof.Name);
Assert.AreSame(fieldInOneof.ContainingOneof, fieldInOneof.RealContainingOneof);
TestDescriptorToProto(primitiveField.ToProto, primitiveField.Proto);
TestDescriptorToProto(enumField.ToProto, enumField.Proto);
TestDescriptorToProto(foreignMessageField.ToProto, foreignMessageField.Proto);
TestDescriptorToProto(fieldInOneof.ToProto, fieldInOneof.Proto);
}
[Test]
@ -338,6 +345,8 @@ namespace Google.Protobuf.Reflection
{
Assert.AreEqual(i, enumType.Values[i].Index);
}
TestDescriptorToProto(enumType.ToProto, enumType.Proto);
TestDescriptorToProto(nestedType.ToProto, nestedType.Proto);
}
[Test]
@ -361,6 +370,7 @@ namespace Google.Protobuf.Reflection
}
CollectionAssert.AreEquivalent(expectedFields, descriptor.Fields);
TestDescriptorToProto(descriptor.ToProto, descriptor.Proto);
}
[Test]
@ -370,6 +380,7 @@ namespace Google.Protobuf.Reflection
Assert.IsNull(descriptor.Parser);
Assert.IsNull(descriptor.ClrType);
Assert.IsNull(descriptor.Fields[1].Accessor);
TestDescriptorToProto(descriptor.ToProto, descriptor.Proto);
}
// From TestFieldOrdering:
@ -391,6 +402,7 @@ namespace Google.Protobuf.Reflection
{
var descriptor = Google.Protobuf.Reflection.FileDescriptor.DescriptorProtoFileDescriptor;
Assert.AreEqual("google/protobuf/descriptor.proto", descriptor.Name);
TestDescriptorToProto(descriptor.ToProto, descriptor.Proto);
}
[Test]
@ -453,5 +465,17 @@ namespace Google.Protobuf.Reflection
}
}
}
private static void TestDescriptorToProto(Func<IMessage> toProtoFunction, IMessage expectedProto)
{
var clone1 = toProtoFunction();
var clone2 = toProtoFunction();
Assert.AreNotSame(clone1, clone2);
Assert.AreNotSame(clone1, expectedProto);
Assert.AreNotSame(clone2, expectedProto);
Assert.AreEqual(clone1, clone2);
Assert.AreEqual(clone1, expectedProto);
}
}
}

View File

@ -0,0 +1,127 @@
#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
#if !NET5_0_OR_GREATER
// Copied with permission from https://github.com/dotnet/runtime/tree/8fbf206d0e518b45ca855832e8bfb391afa85972/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Specifies the types of members that are dynamically accessed.
///
/// This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a
/// bitwise combination of its member values.
/// </summary>
[Flags]
internal enum DynamicallyAccessedMemberTypes
{
/// <summary>
/// Specifies no members.
/// </summary>
None = 0,
/// <summary>
/// Specifies the default, parameterless public constructor.
/// </summary>
PublicParameterlessConstructor = 0x0001,
/// <summary>
/// Specifies all public constructors.
/// </summary>
PublicConstructors = 0x0002 | PublicParameterlessConstructor,
/// <summary>
/// Specifies all non-public constructors.
/// </summary>
NonPublicConstructors = 0x0004,
/// <summary>
/// Specifies all public methods.
/// </summary>
PublicMethods = 0x0008,
/// <summary>
/// Specifies all non-public methods.
/// </summary>
NonPublicMethods = 0x0010,
/// <summary>
/// Specifies all public fields.
/// </summary>
PublicFields = 0x0020,
/// <summary>
/// Specifies all non-public fields.
/// </summary>
NonPublicFields = 0x0040,
/// <summary>
/// Specifies all public nested types.
/// </summary>
PublicNestedTypes = 0x0080,
/// <summary>
/// Specifies all non-public nested types.
/// </summary>
NonPublicNestedTypes = 0x0100,
/// <summary>
/// Specifies all public properties.
/// </summary>
PublicProperties = 0x0200,
/// <summary>
/// Specifies all non-public properties.
/// </summary>
NonPublicProperties = 0x0400,
/// <summary>
/// Specifies all public events.
/// </summary>
PublicEvents = 0x0800,
/// <summary>
/// Specifies all non-public events.
/// </summary>
NonPublicEvents = 0x1000,
/// <summary>
/// Specifies all interfaces implemented by the type.
/// </summary>
Interfaces = 0x2000,
/// <summary>
/// Specifies all members.
/// </summary>
All = ~None
}
}
#endif

View File

@ -0,0 +1,83 @@
#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
#if !NET5_0_OR_GREATER
// Copied with permission from https://github.com/dotnet/runtime/tree/8fbf206d0e518b45ca855832e8bfb391afa85972/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Indicates that certain members on a specified <see cref="Type"/> are accessed dynamically,
/// for example through <see cref="System.Reflection"/>.
/// </summary>
/// <remarks>
/// This allows tools to understand which members are being accessed during the execution
/// of a program.
///
/// This attribute is valid on members whose type is <see cref="Type"/> or <see cref="string"/>.
///
/// When this attribute is applied to a location of type <see cref="string"/>, the assumption is
/// that the string represents a fully qualified type name.
///
/// When this attribute is applied to a class, interface, or struct, the members specified
/// can be accessed dynamically on <see cref="Type"/> instances returned from calling
/// <see cref="object.GetType"/> on instances of that class, interface, or struct.
///
/// If the attribute is applied to a method it's treated as a special case and it implies
/// the attribute should be applied to the "this" parameter of the method. As such the attribute
/// should only be used on instance methods of types assignable to System.Type (or string, but no methods
/// will use it there).
/// </remarks>
[AttributeUsage(
AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter |
AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method |
AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct,
Inherited = false)]
internal sealed class DynamicallyAccessedMembersAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DynamicallyAccessedMembersAttribute"/> class
/// with the specified member types.
/// </summary>
/// <param name="memberTypes">The types of members dynamically accessed.</param>
public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
{
MemberTypes = memberTypes;
}
/// <summary>
/// Gets the <see cref="DynamicallyAccessedMemberTypes"/> which specifies the type
/// of members dynamically accessed.
/// </summary>
public DynamicallyAccessedMemberTypes MemberTypes { get; }
}
}
#endif

View File

@ -0,0 +1,72 @@
#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
#if !NET5_0_OR_GREATER
// Copied with permission from https://github.com/dotnet/runtime/tree/8fbf206d0e518b45ca855832e8bfb391afa85972/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Indicates that the specified method requires dynamic access to code that is not referenced
/// statically, for example through <see cref="System.Reflection"/>.
/// </summary>
/// <remarks>
/// This allows tools to understand which methods are unsafe to call when removing unreferenced
/// code from an application.
/// </remarks>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)]
internal sealed class RequiresUnreferencedCodeAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequiresUnreferencedCodeAttribute"/> class
/// with the specified message.
/// </summary>
/// <param name="message">
/// A message that contains information about the usage of unreferenced code.
/// </param>
public RequiresUnreferencedCodeAttribute(string message)
{
Message = message;
}
/// <summary>
/// Gets a message that contains information about the usage of unreferenced code.
/// </summary>
public string Message { get; }
/// <summary>
/// Gets or sets an optional URL that contains more information about the method,
/// why it requires unreferenced code, and what options a consumer has to deal with it.
/// </summary>
public string Url { get; set; }
}
}
#endif

View File

@ -31,6 +31,7 @@
#endregion
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
#if !NET35
@ -59,7 +60,11 @@ namespace Google.Protobuf.Compatibility
/// including inherited properties or null if there is no such public property.
/// Here, "public property" means a property where either the getter, or the setter, or both, is public.
/// </summary>
internal static PropertyInfo GetProperty(this Type target, string name)
[UnconditionalSuppressMessage("Trimming", "IL2072",
Justification = "The BaseType of the target will have all properties because of the annotation.")]
internal static PropertyInfo GetProperty(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
this Type target, string name)
{
// GetDeclaredProperty only returns properties declared in the given type, so we need to recurse.
while (target != null)
@ -86,7 +91,11 @@ namespace Google.Protobuf.Compatibility
/// class Child : Base declares public void Foo(long)).
/// </remarks>
/// <exception cref="AmbiguousMatchException">One type in the hierarchy declared more than one method with the same name</exception>
internal static MethodInfo GetMethod(this Type target, string name)
[UnconditionalSuppressMessage("Trimming", "IL2072",
Justification = "The BaseType of the target will have all properties because of the annotation.")]
internal static MethodInfo GetMethod(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
this Type target, string name)
{
// GetDeclaredMethod only returns methods declared in the given type, so we need to recurse.
while (target != null)

View File

@ -0,0 +1,117 @@
#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
#if !NET5_0_OR_GREATER
// Copied with permission from https://github.com/dotnet/runtime/tree/8fbf206d0e518b45ca855832e8bfb391afa85972/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis
namespace System.Diagnostics.CodeAnalysis
{
/// <summary>
/// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a
/// single code artifact.
/// </summary>
/// <remarks>
/// <see cref="UnconditionalSuppressMessageAttribute"/> is different than
/// <see cref="SuppressMessageAttribute"/> in that it doesn't have a
/// <see cref="ConditionalAttribute"/>. So it is always preserved in the compiled assembly.
/// </remarks>
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
internal sealed class UnconditionalSuppressMessageAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="UnconditionalSuppressMessageAttribute"/>
/// class, specifying the category of the tool and the identifier for an analysis rule.
/// </summary>
/// <param name="category">The category for the attribute.</param>
/// <param name="checkId">The identifier of the analysis rule the attribute applies to.</param>
public UnconditionalSuppressMessageAttribute(string category, string checkId)
{
Category = category;
CheckId = checkId;
}
/// <summary>
/// Gets the category identifying the classification of the attribute.
/// </summary>
/// <remarks>
/// The <see cref="Category"/> property describes the tool or tool analysis category
/// for which a message suppression attribute applies.
/// </remarks>
public string Category { get; }
/// <summary>
/// Gets the identifier of the analysis tool rule to be suppressed.
/// </summary>
/// <remarks>
/// Concatenated together, the <see cref="Category"/> and <see cref="CheckId"/>
/// properties form a unique check identifier.
/// </remarks>
public string CheckId { get; }
/// <summary>
/// Gets or sets the scope of the code that is relevant for the attribute.
/// </summary>
/// <remarks>
/// The Scope property is an optional argument that specifies the metadata scope for which
/// the attribute is relevant.
/// </remarks>
public string Scope { get; set; }
/// <summary>
/// Gets or sets a fully qualified path that represents the target of the attribute.
/// </summary>
/// <remarks>
/// The <see cref="Target"/> property is an optional argument identifying the analysis target
/// of the attribute. An example value is "System.IO.Stream.ctor():System.Void".
/// Because it is fully qualified, it can be long, particularly for targets such as parameters.
/// The analysis tool user interface should be capable of automatically formatting the parameter.
/// </remarks>
public string Target { get; set; }
/// <summary>
/// Gets or sets an optional argument expanding on exclusion criteria.
/// </summary>
/// <remarks>
/// The <see cref="MessageId "/> property is an optional argument that specifies additional
/// exclusion where the literal metadata target is not sufficiently precise. For example,
/// the <see cref="UnconditionalSuppressMessageAttribute"/> cannot be applied within a method,
/// and it may be desirable to suppress a violation against a statement in the method that will
/// give a rule violation, but not against all statements in the method.
/// </remarks>
public string MessageId { get; set; }
/// <summary>
/// Gets or sets the justification for suppressing the code analysis message.
/// </summary>
public string Justification { get; set; }
}
}
#endif

View File

@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>C# runtime library for Protocol Buffers - Google's data interchange format.</Description>
<Copyright>Copyright 2015, Google Inc.</Copyright>
<AssemblyTitle>Google Protocol Buffers</AssemblyTitle>
<VersionPrefix>3.18.1</VersionPrefix>
<VersionPrefix>3.19.4</VersionPrefix>
<!-- C# 7.2 is required for Span/BufferWriter/ReadOnlySequence -->
<LangVersion>7.2</LangVersion>
<Authors>Google Inc.</Authors>
@ -15,12 +15,14 @@
<PackageTags>Protocol;Buffers;Binary;Serialization;Format;Google;proto;proto3</PackageTags>
<PackageReleaseNotes>C# proto3 support</PackageReleaseNotes>
<PackageProjectUrl>https://github.com/protocolbuffers/protobuf</PackageProjectUrl>
<PackageLicenseUrl>https://github.com/protocolbuffers/protobuf/blob/master/LICENSE</PackageLicenseUrl>
<PackageLicenseExpression>BSD-3-Clause</PackageLicenseExpression>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/protocolbuffers/protobuf.git</RepositoryUrl>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<!-- Include PDB in the built .nupkg -->
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
@ -43,7 +45,7 @@
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="System.Memory" Version="4.5.3"/>
<!-- Needed for netcoreapp2.1 to work correctly. .NET is not able to load the assembly without this -->
<!-- Needed for netcoreapp3.1 to work correctly. .NET is not able to load the assembly without this -->
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.5.2"/>
</ItemGroup>

View File

@ -40,6 +40,7 @@ using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Diagnostics.CodeAnalysis;
namespace Google.Protobuf
{
@ -879,6 +880,8 @@ namespace Google.Protobuf
private static readonly Dictionary<System.Type, Dictionary<object, string>> dictionaries
= new Dictionary<System.Type, Dictionary<object, string>>();
[UnconditionalSuppressMessage("Trimming", "IL2072",
Justification = "The field for the value must still be present. It will be returned by reflection, will be in this collection, and its name can be resolved.")]
internal static string GetOriginalName(object value)
{
var enumType = value.GetType();
@ -898,21 +901,13 @@ namespace Google.Protobuf
return originalName;
}
#if NET35
// TODO: Consider adding functionality to TypeExtensions to avoid this difference.
private static Dictionary<object, string> GetNameMapping(System.Type enumType) =>
enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
.Where(f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
.FirstOrDefault() as OriginalNameAttribute)
?.PreferredAlias ?? true)
.ToDictionary(f => f.GetValue(null),
f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
.FirstOrDefault() as OriginalNameAttribute)
// If the attribute hasn't been applied, fall back to the name of the field.
?.Name ?? f.Name);
#else
private static Dictionary<object, string> GetNameMapping(System.Type enumType) =>
enumType.GetTypeInfo().DeclaredFields
private static Dictionary<object, string> GetNameMapping(
[DynamicallyAccessedMembers(
DynamicallyAccessedMemberTypes.PublicFields |
DynamicallyAccessedMemberTypes.NonPublicFields)]
System.Type enumType)
{
return enumType.GetTypeInfo().DeclaredFields
.Where(f => f.IsStatic)
.Where(f => f.GetCustomAttributes<OriginalNameAttribute>()
.FirstOrDefault()?.PreferredAlias ?? true)
@ -921,7 +916,7 @@ namespace Google.Protobuf
.FirstOrDefault()
// If the attribute hasn't been applied, fall back to the name of the field.
?.Name ?? f.Name);
#endif
}
}
}
}

View File

@ -471,9 +471,18 @@ namespace Google.Protobuf
// TODO: What exception should we throw if the value can't be represented as a double?
try
{
return double.Parse(builder.ToString(),
double result = double.Parse(builder.ToString(),
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture);
// .NET Core 3.0 and later returns infinity if the number is too large or small to be represented.
// For compatibility with other Protobuf implementations the tokenizer should still throw.
if (double.IsInfinity(result))
{
throw reader.CreateException("Numeric value out of range: " + builder);
}
return result;
}
catch (OverflowException)
{

View File

@ -187,14 +187,17 @@ namespace Google.Protobuf
internal void MergeFrom(IMessage message, CodedInputStream codedInput)
{
bool originalDiscard = codedInput.DiscardUnknownFields;
ExtensionRegistry originalRegistry = codedInput.ExtensionRegistry;
try
{
codedInput.DiscardUnknownFields = DiscardUnknownFields;
codedInput.ExtensionRegistry = Extensions;
message.MergeFrom(codedInput);
}
finally
{
codedInput.DiscardUnknownFields = originalDiscard;
codedInput.ExtensionRegistry = originalRegistry;
}
}

View File

@ -34,6 +34,7 @@ using Google.Protobuf.Collections;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
@ -63,6 +64,8 @@ namespace Google.Protobuf.Reflection
/// </remarks>
public sealed class CustomOptions
{
private const string UnreferencedCodeMessage = "CustomOptions is incompatible with trimming.";
private static readonly object[] EmptyParameters = new object[0];
private readonly IDictionary<int, IExtensionValue> values;
@ -77,6 +80,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetBool(int field, out bool value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -85,6 +89,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetInt32(int field, out int value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -93,6 +98,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetInt64(int field, out long value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -102,6 +108,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetFixed32(int field, out uint value) => TryGetUInt32(field, out value);
/// <summary>
@ -111,6 +118,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetFixed64(int field, out ulong value) => TryGetUInt64(field, out value);
/// <summary>
@ -120,6 +128,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetSFixed32(int field, out int value) => TryGetInt32(field, out value);
/// <summary>
@ -129,6 +138,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetSFixed64(int field, out long value) => TryGetInt64(field, out value);
/// <summary>
@ -138,6 +148,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetSInt32(int field, out int value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -147,6 +158,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetSInt64(int field, out long value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -155,6 +167,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetUInt32(int field, out uint value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -163,6 +176,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetUInt64(int field, out ulong value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -171,6 +185,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetFloat(int field, out float value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -179,6 +194,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetDouble(int field, out double value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -187,6 +203,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetString(int field, out string value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -195,6 +212,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetBytes(int field, out ByteString value) => TryGetPrimitiveValue(field, out value);
/// <summary>
@ -203,6 +221,7 @@ namespace Google.Protobuf.Reflection
/// <param name="field">The field to fetch the value for.</param>
/// <param name="value">The output variable to populate.</param>
/// <returns><c>true</c> if a suitable value for the field was found; <c>false</c> otherwise.</returns>
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
public bool TryGetMessage<T>(int field, out T value) where T : class, IMessage, new()
{
if (values == null)
@ -240,6 +259,7 @@ namespace Google.Protobuf.Reflection
return false;
}
[RequiresUnreferencedCode(UnreferencedCodeMessage)]
private bool TryGetPrimitiveValue<T>(int field, out T value)
{
if (values == null)

View File

@ -113,52 +113,53 @@ namespace Google.Protobuf.Reflection {
"CgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZRIRCgltYXBfZW50cnkYByABKAgS",
"QwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3Rv",
"YnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAkoEC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nByb3RvYnVmQhBEZXNjcmlwdG9y",
"UHJvdG9zSAFaLWdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2Rl",
"c2NyaXB0b3JwYvgBAaICA0dQQqoCGkdvb2dsZS5Qcm90b2J1Zi5SZWZsZWN0",
"aW9u"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
@ -175,7 +176,7 @@ namespace Google.Protobuf.Reflection {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MethodDescriptorProto), global::Google.Protobuf.Reflection.MethodDescriptorProto.Parser, new[]{ "Name", "InputType", "OutputType", "Options", "ClientStreaming", "ServerStreaming" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FileOptions), global::Google.Protobuf.Reflection.FileOptions.Parser, new[]{ "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "JavaGenerateEqualsAndHash", "JavaStringCheckUtf8", "OptimizeFor", "GoPackage", "CcGenericServices", "JavaGenericServices", "PyGenericServices", "PhpGenericServices", "Deprecated", "CcEnableArenas", "ObjcClassPrefix", "CsharpNamespace", "SwiftPrefix", "PhpClassPrefix", "PhpNamespace", "PhpMetadataNamespace", "RubyPackage", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.MessageOptions), global::Google.Protobuf.Reflection.MessageOptions.Parser, new[]{ "MessageSetWireFormat", "NoStandardDescriptorAccessor", "Deprecated", "MapEntry", "UninterpretedOption" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldOptions), global::Google.Protobuf.Reflection.FieldOptions.Parser, new[]{ "Ctype", "Packed", "Jstype", "Lazy", "Deprecated", "Weak", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.CType), typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.FieldOptions), global::Google.Protobuf.Reflection.FieldOptions.Parser, new[]{ "Ctype", "Packed", "Jstype", "Lazy", "UnverifiedLazy", "Deprecated", "Weak", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.CType), typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) }, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.OneofOptions), global::Google.Protobuf.Reflection.OneofOptions.Parser, new[]{ "UninterpretedOption" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumOptions), global::Google.Protobuf.Reflection.EnumOptions.Parser, new[]{ "AllowAlias", "Deprecated", "UninterpretedOption" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.Reflection.EnumValueOptions), global::Google.Protobuf.Reflection.EnumValueOptions.Parser, new[]{ "Deprecated", "UninterpretedOption" }, null, null, null, null),
@ -2507,7 +2508,6 @@ namespace Google.Protobuf.Reflection {
/// For booleans, "true" or "false".
/// For strings, contains the default text contents (not escaped in any way).
/// For bytes, contains the C escaped value. All bytes >= 128 are escaped.
/// TODO(kenton): Base-64 encode?
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
@ -6943,6 +6943,7 @@ namespace Google.Protobuf.Reflection {
packed_ = other.packed_;
jstype_ = other.jstype_;
lazy_ = other.lazy_;
unverifiedLazy_ = other.unverifiedLazy_;
deprecated_ = other.deprecated_;
weak_ = other.weak_;
uninterpretedOption_ = other.uninterpretedOption_.Clone();
@ -7096,6 +7097,12 @@ namespace Google.Protobuf.Reflection {
/// implementation must either *always* check its required fields, or *never*
/// check its required fields, regardless of whether or not the message has
/// been parsed.
///
/// As of 2021, lazy does no correctness checks on the byte stream during
/// parsing. This may lead to crashes if and when an invalid byte stream is
/// finally parsed upon access.
///
/// TODO(b/211906113): Enable validation on lazy fields.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
@ -7119,6 +7126,38 @@ namespace Google.Protobuf.Reflection {
_hasBits0 &= ~8;
}
/// <summary>Field number for the "unverified_lazy" field.</summary>
public const int UnverifiedLazyFieldNumber = 15;
private readonly static bool UnverifiedLazyDefaultValue = false;
private bool unverifiedLazy_;
/// <summary>
/// unverified_lazy does no correctness checks on the byte stream. This should
/// only be used where lazy with verification is prohibitive for performance
/// reasons.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool UnverifiedLazy {
get { if ((_hasBits0 & 64) != 0) { return unverifiedLazy_; } else { return UnverifiedLazyDefaultValue; } }
set {
_hasBits0 |= 64;
unverifiedLazy_ = value;
}
}
/// <summary>Gets whether the "unverified_lazy" field is set</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool HasUnverifiedLazy {
get { return (_hasBits0 & 64) != 0; }
}
/// <summary>Clears the value of the "unverified_lazy" field</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void ClearUnverifiedLazy() {
_hasBits0 &= ~64;
}
/// <summary>Field number for the "deprecated" field.</summary>
public const int DeprecatedFieldNumber = 3;
private readonly static bool DeprecatedDefaultValue = false;
@ -7215,6 +7254,7 @@ namespace Google.Protobuf.Reflection {
if (Packed != other.Packed) return false;
if (Jstype != other.Jstype) return false;
if (Lazy != other.Lazy) return false;
if (UnverifiedLazy != other.UnverifiedLazy) return false;
if (Deprecated != other.Deprecated) return false;
if (Weak != other.Weak) return false;
if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false;
@ -7232,6 +7272,7 @@ namespace Google.Protobuf.Reflection {
if (HasPacked) hash ^= Packed.GetHashCode();
if (HasJstype) hash ^= Jstype.GetHashCode();
if (HasLazy) hash ^= Lazy.GetHashCode();
if (HasUnverifiedLazy) hash ^= UnverifiedLazy.GetHashCode();
if (HasDeprecated) hash ^= Deprecated.GetHashCode();
if (HasWeak) hash ^= Weak.GetHashCode();
hash ^= uninterpretedOption_.GetHashCode();
@ -7280,6 +7321,10 @@ namespace Google.Protobuf.Reflection {
output.WriteRawTag(80);
output.WriteBool(Weak);
}
if (HasUnverifiedLazy) {
output.WriteRawTag(120);
output.WriteBool(UnverifiedLazy);
}
uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec);
if (_extensions != null) {
_extensions.WriteTo(output);
@ -7318,6 +7363,10 @@ namespace Google.Protobuf.Reflection {
output.WriteRawTag(80);
output.WriteBool(Weak);
}
if (HasUnverifiedLazy) {
output.WriteRawTag(120);
output.WriteBool(UnverifiedLazy);
}
uninterpretedOption_.WriteTo(ref output, _repeated_uninterpretedOption_codec);
if (_extensions != null) {
_extensions.WriteTo(ref output);
@ -7344,6 +7393,9 @@ namespace Google.Protobuf.Reflection {
if (HasLazy) {
size += 1 + 1;
}
if (HasUnverifiedLazy) {
size += 1 + 1;
}
if (HasDeprecated) {
size += 1 + 1;
}
@ -7378,6 +7430,9 @@ namespace Google.Protobuf.Reflection {
if (other.HasLazy) {
Lazy = other.Lazy;
}
if (other.HasUnverifiedLazy) {
UnverifiedLazy = other.UnverifiedLazy;
}
if (other.HasDeprecated) {
Deprecated = other.Deprecated;
}
@ -7427,6 +7482,10 @@ namespace Google.Protobuf.Reflection {
Weak = input.ReadBool();
break;
}
case 120: {
UnverifiedLazy = input.ReadBool();
break;
}
case 7994: {
uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec);
break;
@ -7472,6 +7531,10 @@ namespace Google.Protobuf.Reflection {
Weak = input.ReadBool();
break;
}
case 120: {
UnverifiedLazy = input.ReadBool();
break;
}
case 7994: {
uninterpretedOption_.AddEntriesFrom(ref input, _repeated_uninterpretedOption_codec);
break;

View File

@ -68,6 +68,14 @@ namespace Google.Protobuf.Reflection
internal EnumDescriptorProto Proto { get { return proto; } }
/// <summary>
/// Returns a clone of the underlying <see cref="EnumDescriptorProto"/> describing this enum.
/// Note that a copy is taken every time this method is called, so clients using it frequently
/// (and not modifying it) may want to cache the returned value.
/// </summary>
/// <returns>A protobuf representation of this enum descriptor.</returns>
public EnumDescriptorProto ToProto() => Proto.Clone();
/// <summary>
/// The brief name of the descriptor's target.
/// </summary>

View File

@ -55,6 +55,14 @@ namespace Google.Protobuf.Reflection
internal EnumValueDescriptorProto Proto { get { return proto; } }
/// <summary>
/// Returns a clone of the underlying <see cref="EnumValueDescriptorProto"/> describing this enum value.
/// Note that a copy is taken every time this method is called, so clients using it frequently
/// (and not modifying it) may want to cache the returned value.
/// </summary>
/// <returns>A protobuf representation of this enum value descriptor.</returns>
public EnumValueDescriptorProto ToProto() => Proto.Clone();
/// <summary>
/// Returns the name of the enum value described by this object.
/// </summary>

View File

@ -45,7 +45,6 @@ namespace Google.Protobuf.Reflection
private MessageDescriptor extendeeType;
private MessageDescriptor messageType;
private FieldType fieldType;
private readonly string propertyName; // Annoyingly, needed in Crosslink.
private IFieldAccessor accessor;
/// <summary>
@ -70,6 +69,11 @@ namespace Google.Protobuf.Reflection
/// </summary>
public string JsonName { get; }
/// <summary>
/// The name of the property in the <c>ContainingType.ClrType</c> class.
/// </summary>
public string PropertyName { get; }
/// <summary>
/// Indicates whether this field supports presence, either implicitly (e.g. due to it being a message
/// type field) or explicitly via Has/Clear members. If this returns true, it is safe to call
@ -87,6 +91,14 @@ namespace Google.Protobuf.Reflection
internal FieldDescriptorProto Proto { get; }
/// <summary>
/// Returns a clone of the underlying <see cref="FieldDescriptorProto"/> describing this field.
/// Note that a copy is taken every time this method is called, so clients using it frequently
/// (and not modifying it) may want to cache the returned value.
/// </summary>
/// <returns>A protobuf representation of this field descriptor.</returns>
public FieldDescriptorProto ToProto() => Proto.Clone();
/// <summary>
/// An extension identifier for this field, or <c>null</c> if this field isn't an extension.
/// </summary>
@ -123,7 +135,7 @@ namespace Google.Protobuf.Reflection
// for later.
// We could trust the generated code and check whether the type of the property is
// a MapField, but that feels a tad nasty.
this.propertyName = propertyName;
PropertyName = propertyName;
Extension = extension;
JsonName = Proto.JsonName == "" ? JsonFormatter.ToJsonName(Proto.Name) : Proto.JsonName;
}
@ -235,7 +247,8 @@ namespace Google.Protobuf.Reflection
}
else
{
return !Proto.Options.HasPacked || Proto.Options.Packed;
// Packed by default with proto3
return Proto.Options == null || !Proto.Options.HasPacked || Proto.Options.Packed;
}
}
}
@ -436,19 +449,19 @@ namespace Google.Protobuf.Reflection
// If we're given no property name, that's because we really don't want an accessor.
// This could be because it's a map message, or it could be that we're loading a FileDescriptor dynamically.
// TODO: Support dynamic messages.
if (propertyName == null)
if (PropertyName == null)
{
return null;
}
var property = ContainingType.ClrType.GetProperty(propertyName);
var property = ContainingType.ClrType.GetProperty(PropertyName);
if (property == null)
{
throw new DescriptorValidationException(this, $"Property {propertyName} not found in {ContainingType.ClrType}");
throw new DescriptorValidationException(this, $"Property {PropertyName} not found in {ContainingType.ClrType}");
}
return IsMap ? new MapFieldAccessor(property, this)
: IsRepeated ? new RepeatedFieldAccessor(property, this)
: (IFieldAccessor) new SingleFieldAccessor(property, this);
: (IFieldAccessor) new SingleFieldAccessor(ContainingType.ClrType, property, this);
}
}
}

View File

@ -249,6 +249,14 @@ namespace Google.Protobuf.Reflection
/// </value>
internal FileDescriptorProto Proto { get; }
/// <summary>
/// Returns a clone of the underlying <see cref="FileDescriptorProto"/> describing this file.
/// Note that a copy is taken every time this method is called, so clients using it frequently
/// (and not modifying it) may want to cache the returned value.
/// </summary>
/// <returns>A protobuf representation of this file descriptor.</returns>
public FileDescriptorProto ToProto() => Proto.Clone();
/// <summary>
/// The syntax of the file
/// </summary>

View File

@ -30,6 +30,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Diagnostics.CodeAnalysis;
namespace Google.Protobuf.Reflection
{
@ -43,10 +44,19 @@ namespace Google.Protobuf.Reflection
private static readonly string[] EmptyNames = new string[0];
private static readonly GeneratedClrTypeInfo[] EmptyCodeInfo = new GeneratedClrTypeInfo[0];
private static readonly Extension[] EmptyExtensions = new Extension[0];
internal const DynamicallyAccessedMemberTypes MessageAccessibility =
// Creating types
DynamicallyAccessedMemberTypes.PublicConstructors |
// Getting and setting properties
DynamicallyAccessedMemberTypes.PublicProperties |
DynamicallyAccessedMemberTypes.NonPublicProperties |
// Calling presence methods
DynamicallyAccessedMemberTypes.PublicMethods;
/// <summary>
/// Irrelevant for file descriptors; the CLR type for the message for message descriptors.
/// </summary>
[DynamicallyAccessedMembers(MessageAccessibility)]
public Type ClrType { get; private set; }
/// <summary>
@ -88,7 +98,11 @@ namespace Google.Protobuf.Reflection
/// Each array parameter may be null, to indicate a lack of values.
/// The parameter order is designed to make it feasible to format the generated code readably.
/// </summary>
public GeneratedClrTypeInfo(Type clrType, MessageParser parser, string[] propertyNames, string[] oneofNames, Type[] nestedEnums, Extension[] extensions, GeneratedClrTypeInfo[] nestedTypes)
public GeneratedClrTypeInfo(
// Preserve all public members on message types when trimming is enabled.
// This ensures that members used by reflection, e.g. JSON serialization, are preserved.
[DynamicallyAccessedMembers(MessageAccessibility)]
Type clrType, MessageParser parser, string[] propertyNames, string[] oneofNames, Type[] nestedEnums, Extension[] extensions, GeneratedClrTypeInfo[] nestedTypes)
{
NestedTypes = nestedTypes ?? EmptyCodeInfo;
NestedEnums = nestedEnums ?? ReflectionUtil.EmptyTypes;
@ -104,7 +118,11 @@ namespace Google.Protobuf.Reflection
/// Each array parameter may be null, to indicate a lack of values.
/// The parameter order is designed to make it feasible to format the generated code readably.
/// </summary>
public GeneratedClrTypeInfo(Type clrType, MessageParser parser, string[] propertyNames, string[] oneofNames, Type[] nestedEnums, GeneratedClrTypeInfo[] nestedTypes)
public GeneratedClrTypeInfo(
// Preserve all public members on message types when trimming is enabled.
// This ensures that members used by reflection, e.g. JSON serialization, are preserved.
[DynamicallyAccessedMembers(MessageAccessibility)]
Type clrType, MessageParser parser, string[] propertyNames, string[] oneofNames, Type[] nestedEnums, GeneratedClrTypeInfo[] nestedTypes)
: this(clrType, parser, propertyNames, oneofNames, nestedEnums, null, nestedTypes)
{
}

View File

@ -33,6 +33,7 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
#if NET35
@ -150,6 +151,14 @@ namespace Google.Protobuf.Reflection
internal DescriptorProto Proto { get; }
/// <summary>
/// Returns a clone of the underlying <see cref="DescriptorProto"/> describing this message.
/// Note that a copy is taken every time this method is called, so clients using it frequently
/// (and not modifying it) may want to cache the returned value.
/// </summary>
/// <returns>A protobuf representation of this message descriptor.</returns>
public DescriptorProto ToProto() => Proto.Clone();
internal bool IsExtensionsInitialized(IMessage message)
{
if (Proto.ExtensionRange.Count == 0)
@ -182,6 +191,7 @@ namespace Google.Protobuf.Reflection
/// a wrapper type, and handle the result appropriately.
/// </para>
/// </remarks>
[DynamicallyAccessedMembers(GeneratedClrTypeInfo.MessageAccessibility)]
public Type ClrType { get; }
/// <summary>

View File

@ -114,6 +114,14 @@ namespace Google.Protobuf.Reflection
internal MethodDescriptorProto Proto { get { return proto; } }
/// <summary>
/// Returns a clone of the underlying <see cref="MethodDescriptorProto"/> describing this method.
/// Note that a copy is taken every time this method is called, so clients using it frequently
/// (and not modifying it) may want to cache the returned value.
/// </summary>
/// <returns>A protobuf representation of this method descriptor.</returns>
public MethodDescriptorProto ToProto() => Proto.Clone();
/// <summary>
/// The brief name of the descriptor's target.
/// </summary>

View File

@ -45,7 +45,6 @@ namespace Google.Protobuf.Reflection
/// </summary>
public sealed class OneofDescriptor : DescriptorBase
{
private readonly OneofDescriptorProto proto;
private MessageDescriptor containingType;
private IList<FieldDescriptor> fields;
private readonly OneofAccessor accessor;
@ -53,7 +52,7 @@ namespace Google.Protobuf.Reflection
internal OneofDescriptor(OneofDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, string clrName)
: base(file, file.ComputeFullName(parent, proto.Name), index)
{
this.proto = proto;
this.Proto = proto;
containingType = parent;
file.DescriptorPool.AddSymbol(this);
@ -68,7 +67,18 @@ namespace Google.Protobuf.Reflection
/// <summary>
/// The brief name of the descriptor's target.
/// </summary>
public override string Name { get { return proto.Name; } }
public override string Name => Proto.Name;
// Visible for testing
internal OneofDescriptorProto Proto { get; }
/// <summary>
/// Returns a clone of the underlying <see cref="OneofDescriptorProto"/> describing this oneof.
/// Note that a copy is taken every time this method is called, so clients using it frequently
/// (and not modifying it) may want to cache the returned value.
/// </summary>
/// <returns>A protobuf representation of this oneof descriptor.</returns>
public OneofDescriptorProto ToProto() => Proto.Clone();
/// <summary>
/// Gets the message type containing this oneof.
@ -118,7 +128,7 @@ namespace Google.Protobuf.Reflection
/// The (possibly empty) set of custom options for this oneof.
/// </summary>
[Obsolete("CustomOptions are obsolete. Use the GetOptions method.")]
public CustomOptions CustomOptions => new CustomOptions(proto.Options?._extensions?.ValuesByNumber);
public CustomOptions CustomOptions => new CustomOptions(Proto.Options?._extensions?.ValuesByNumber);
/// <summary>
/// The <c>OneofOptions</c>, defined in <c>descriptor.proto</c>.
@ -126,7 +136,7 @@ namespace Google.Protobuf.Reflection
/// Custom options can be retrieved as extensions of the returned message.
/// NOTE: A defensive copy is created each time this property is retrieved.
/// </summary>
public OneofOptions GetOptions() => proto.Options?.Clone();
public OneofOptions GetOptions() => Proto.Options?.Clone();
/// <summary>
/// Gets a single value oneof option for this descriptor
@ -134,7 +144,7 @@ namespace Google.Protobuf.Reflection
[Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public T GetOption<T>(Extension<OneofOptions, T> extension)
{
var value = proto.Options.GetExtension(extension);
var value = Proto.Options.GetExtension(extension);
return value is IDeepCloneable<T> ? (value as IDeepCloneable<T>).Clone() : value;
}
@ -144,7 +154,7 @@ namespace Google.Protobuf.Reflection
[Obsolete("GetOption is obsolete. Use the GetOptions() method.")]
public RepeatedField<T> GetOption<T>(RepeatedExtension<OneofOptions, T> extension)
{
return proto.Options.GetExtension(extension).Clone();
return Proto.Options.GetExtension(extension).Clone();
}
internal void CrossLink()

View File

@ -32,6 +32,7 @@
using Google.Protobuf.Compatibility;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace Google.Protobuf.Reflection
@ -115,13 +116,15 @@ namespace Google.Protobuf.Reflection
internal static Func<IMessage, bool> CreateFuncIMessageBool(MethodInfo method) =>
GetReflectionHelper(method.DeclaringType, method.ReturnType).CreateFuncIMessageBool(method);
internal static Func<IMessage, bool> CreateIsInitializedCaller(Type msg) =>
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Type parameter members are preserved with DynamicallyAccessedMembers on GeneratedClrTypeInfo.ctor clrType parameter.")]
internal static Func<IMessage, bool> CreateIsInitializedCaller([DynamicallyAccessedMembers(GeneratedClrTypeInfo.MessageAccessibility)]Type msg) =>
((IExtensionSetReflector)Activator.CreateInstance(typeof(ExtensionSetReflector<>).MakeGenericType(msg))).CreateIsInitializedCaller();
/// <summary>
/// Creates a delegate which will execute the given method after casting the first argument to
/// the type that declares the method, and the second argument to the first parameter type of the method.
/// </summary>
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Type parameter members are preserved with DynamicallyAccessedMembers on GeneratedClrTypeInfo.ctor clrType parameter.")]
internal static IExtensionReflectionHelper CreateExtensionHelper(Extension extension) =>
(IExtensionReflectionHelper)Activator.CreateInstance(typeof(ExtensionReflectionHelper<,>).MakeGenericType(extension.TargetType, extension.GetType().GenericTypeArguments[1]), extension);
@ -131,6 +134,7 @@ namespace Google.Protobuf.Reflection
/// they can be garbage collected. We could cache them by type if that proves to be important, but creating
/// an object is pretty cheap.
/// </summary>
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Type parameter members are preserved with DynamicallyAccessedMembers on GeneratedClrTypeInfo.ctor clrType parameter.")]
private static IReflectionHelper GetReflectionHelper(Type t1, Type t2) =>
(IReflectionHelper) Activator.CreateInstance(typeof(ReflectionHelper<,>).MakeGenericType(t1, t2));
@ -308,16 +312,14 @@ namespace Google.Protobuf.Reflection
}
}
private class ExtensionSetReflector<T1> : IExtensionSetReflector where T1 : IExtendableMessage<T1>
private class ExtensionSetReflector<
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
T1> : IExtensionSetReflector where T1 : IExtendableMessage<T1>
{
public Func<IMessage, bool> CreateIsInitializedCaller()
{
var prop = typeof(T1).GetTypeInfo().GetDeclaredProperty("_Extensions");
#if NET35
var getFunc = (Func<T1, ExtensionSet<T1>>)prop.GetGetMethod(true).CreateDelegate(typeof(Func<T1, ExtensionSet<T1>>));
#else
var getFunc = (Func<T1, ExtensionSet<T1>>)prop.GetMethod.CreateDelegate(typeof(Func<T1, ExtensionSet<T1>>));
#endif
var initializedFunc = (Func<ExtensionSet<T1>, bool>)
typeof(ExtensionSet<T1>)
.GetTypeInfo()

View File

@ -73,6 +73,14 @@ namespace Google.Protobuf.Reflection
internal ServiceDescriptorProto Proto { get { return proto; } }
/// <summary>
/// Returns a clone of the underlying <see cref="ServiceDescriptorProto"/> describing this service.
/// Note that a copy is taken every time this method is called, so clients using it frequently
/// (and not modifying it) may want to cache the returned value.
/// </summary>
/// <returns>A protobuf representation of this service descriptor.</returns>
public ServiceDescriptorProto ToProto() => Proto.Clone();
/// <value>
/// An unmodifiable list of methods in this service.
/// </value>

View File

@ -31,6 +31,8 @@
#endregion
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Google.Protobuf.Compatibility;
@ -50,7 +52,9 @@ namespace Google.Protobuf.Reflection
private readonly Action<IMessage> clearDelegate;
private readonly Func<IMessage, bool> hasDelegate;
internal SingleFieldAccessor(PropertyInfo property, FieldDescriptor descriptor) : base(property, descriptor)
internal SingleFieldAccessor(
[DynamicallyAccessedMembers(GeneratedClrTypeInfo.MessageAccessibility)]
Type messageType, PropertyInfo property, FieldDescriptor descriptor) : base(property, descriptor)
{
if (!property.CanWrite)
{
@ -87,13 +91,13 @@ namespace Google.Protobuf.Reflection
// Primitive fields always support presence in proto2, and support presence in proto3 for optional fields.
else if (descriptor.File.Syntax == Syntax.Proto2 || descriptor.Proto.Proto3Optional)
{
MethodInfo hasMethod = property.DeclaringType.GetRuntimeProperty("Has" + property.Name).GetMethod;
MethodInfo hasMethod = messageType.GetRuntimeProperty("Has" + property.Name).GetMethod;
if (hasMethod == null)
{
throw new ArgumentException("Not all required properties/methods are available");
}
hasDelegate = ReflectionUtil.CreateFuncIMessageBool(hasMethod);
MethodInfo clearMethod = property.DeclaringType.GetRuntimeMethod("Clear" + property.Name, ReflectionUtil.EmptyTypes);
MethodInfo clearMethod = messageType.GetRuntimeMethod("Clear" + property.Name, ReflectionUtil.EmptyTypes);
if (clearMethod == null)
{
throw new ArgumentException("Not all required properties/methods are available");
@ -107,16 +111,48 @@ namespace Google.Protobuf.Reflection
hasDelegate = message => { throw new InvalidOperationException("Presence is not implemented for this field"); };
// While presence isn't supported, clearing still is; it's just setting to a default value.
var clrType = property.PropertyType;
object defaultValue =
clrType == typeof(string) ? ""
: clrType == typeof(ByteString) ? ByteString.Empty
: Activator.CreateInstance(clrType);
object defaultValue = GetDefaultValue(descriptor);
clearDelegate = message => SetValue(message, defaultValue);
}
}
private static object GetDefaultValue(FieldDescriptor descriptor)
{
switch (descriptor.FieldType)
{
case FieldType.Bool:
return false;
case FieldType.Bytes:
return ByteString.Empty;
case FieldType.String:
return "";
case FieldType.Double:
return 0.0;
case FieldType.SInt32:
case FieldType.Int32:
case FieldType.SFixed32:
case FieldType.Enum:
return 0;
case FieldType.Fixed32:
case FieldType.UInt32:
return (uint)0;
case FieldType.Fixed64:
case FieldType.UInt64:
return 0UL;
case FieldType.SFixed64:
case FieldType.Int64:
case FieldType.SInt64:
return 0L;
case FieldType.Float:
return 0f;
case FieldType.Message:
case FieldType.Group: // Never expect to get this, but...
return null;
default:
throw new ArgumentException("Invalid field type");
}
}
public override void Clear(IMessage message) => clearDelegate(message);
public override bool HasValue(IMessage message) => hasDelegate(message);
public override void SetValue(IMessage message, object value) => setValueDelegate(message, value);

View File

@ -33,6 +33,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using Google.Protobuf.Reflection;
@ -115,7 +116,7 @@ namespace Google.Protobuf.WellKnownTypes
/// Parses from a string to a FieldMask and validates all field paths.
/// </summary>
/// <typeparam name="T">The type to validate the field paths against.</typeparam>
public static FieldMask FromString<T>(string value) where T : IMessage
public static FieldMask FromString<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T>(string value) where T : IMessage
{
return FromStringEnumerable<T>(new List<string>(value.Split(FIELD_PATH_SEPARATOR)));
}
@ -124,7 +125,7 @@ namespace Google.Protobuf.WellKnownTypes
/// Constructs a FieldMask for a list of field paths in a certain type.
/// </summary>
/// <typeparam name="T">The type to validate the field paths against.</typeparam>
public static FieldMask FromStringEnumerable<T>(IEnumerable<string> paths) where T : IMessage
public static FieldMask FromStringEnumerable<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T>(IEnumerable<string> paths) where T : IMessage
{
var mask = new FieldMask();
foreach (var path in paths)
@ -151,7 +152,7 @@ namespace Google.Protobuf.WellKnownTypes
/// Constructs a FieldMask from the passed field numbers.
/// </summary>
/// <typeparam name="T">The type to validate the field paths against.</typeparam>
public static FieldMask FromFieldNumbers<T>(params int[] fieldNumbers) where T : IMessage
public static FieldMask FromFieldNumbers<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T>(params int[] fieldNumbers) where T : IMessage
{
return FromFieldNumbers<T>((IEnumerable<int>)fieldNumbers);
}
@ -160,7 +161,7 @@ namespace Google.Protobuf.WellKnownTypes
/// Constructs a FieldMask from the passed field numbers.
/// </summary>
/// <typeparam name="T">The type to validate the field paths against.</typeparam>
public static FieldMask FromFieldNumbers<T>(IEnumerable<int> fieldNumbers) where T : IMessage
public static FieldMask FromFieldNumbers<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T>(IEnumerable<int> fieldNumbers) where T : IMessage
{
var descriptor = Activator.CreateInstance<T>().Descriptor;
@ -208,7 +209,7 @@ namespace Google.Protobuf.WellKnownTypes
/// Checks whether paths in a given fields mask are valid.
/// </summary>
/// <typeparam name="T">The type to validate the field paths against.</typeparam>
public static bool IsValid<T>(FieldMask fieldMask) where T : IMessage
public static bool IsValid<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T>(FieldMask fieldMask) where T : IMessage
{
var descriptor = Activator.CreateInstance<T>().Descriptor;
@ -235,7 +236,7 @@ namespace Google.Protobuf.WellKnownTypes
/// Checks whether a given field path is valid.
/// </summary>
/// <typeparam name="T">The type to validate the field paths against.</typeparam>
public static bool IsValid<T>(string path) where T : IMessage
public static bool IsValid<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]T>(string path) where T : IMessage
{
var descriptor = Activator.CreateInstance<T>().Descriptor;

View File

@ -292,3 +292,11 @@ with info about your project (name and website) so we can add an entry for you.
1. Protoc-gen-jsonschema
* Website: https://github.com/chrusty/protoc-gen-jsonschema
* Extension: 1125-1129
1. Protoc-gen-checker
* Website: https://github.com/Intrinsec/protoc-gen-checker
* Extension: 1130-1139
1. Protoc-gen-go-svc
* Website: https://github.com/dane/protoc-gen-go-svc
* Extension: 1140

View File

@ -2,31 +2,32 @@
This page lists code related to Protocol Buffers which is developed and maintained by third parties. You may find this code useful, but note that **these projects are not affiliated with or endorsed by Google (unless explicitly marked)**; try them at your own risk. Also note that many projects here are in the early stages of development and not production-ready.
If you have a project that should be listed here, please [send us a pull request](https://github.com/google/protobuf/pulls) to update this page.
If you have a project that should be listed here, please
[send us a pull request](https://github.com/protocolbuffers/protobuf/pulls) to update this page.
## Programming Languages
These are projects we know about implementing Protocol Buffers for other programming languages:
* Action Script: http://code.google.com/p/protobuf-actionscript3/
* Action Script: https://code.google.com/p/protobuf-actionscript3/
* Action Script: https://code.google.com/p/protoc-gen-as3/
* Action Script: https://github.com/matrix3d/JProtoc
* Action Script: https://github.com/zhongfq/protobuf-as3/
* Ada: https://github.com/reznikmm/protobuf
* C: https://github.com/protobuf-c/protobuf-c
* C: http://koti.kapsi.fi/jpa/nanopb/
* C: https://koti.kapsi.fi/jpa/nanopb/
* C: https://github.com/cloudwu/pbc/
* C: https://github.com/haberman/upb/wiki
* C: https://github.com/squidfunk/protobluff
* C: https://github.com/eerimoq/pbtools
* C++: https://github.com/google/protobuf (Google-official implementation)
* C++: https://github.com/protocolbuffers/protobuf (Google-official implementation)
* C++: https://EmbeddedProto.com
* C/C++: http://spbc.sf.net/
* C#: http://code.google.com/p/protobuf-csharp-port
* C#: https://code.google.com/p/protobuf-csharp-port
* C#: https://silentorbit.com/protobuf/
* C#/.NET/WCF/VB: http://code.google.com/p/protobuf-net/
* C#/.NET/WCF/VB: https://code.google.com/p/protobuf-net/
* Clojure: http://github.com/ninjudd/clojure-protobuf
* Clojure: https://github.com/clojusc/protobuf
* Clojure: https://protojure.github.io
* Clojure: https://protojure.readthedocs.io
* Common Lisp: http://github.com/brown/protobuf
* Common Lisp: http://github.com/qitab/cl-protobuf
* D: https://github.com/dcarp/protobuf-d
@ -48,21 +49,20 @@ These are projects we know about implementing Protocol Buffers for other program
* Go: https://github.com/akunspy/gopbuf
* Go: https://github.com/gogo/protobuf
* GopherJS: https://github.com/johanbrandhorst/protobuf
* Haskell: http://hackage.haskell.org/package/hprotoc
* Haskell: https://hackage.haskell.org/package/hprotoc
* Haskell: https://github.com/google/proto-lens (Google-unofficial implementation)
* Haskell: https://github.com/awakesecurity/proto3-suite (code generator) https://github.com/awakesecurity/proto3-wire (binary serializer/deserializer)
* Haxe: https://github.com/Atry/protoc-gen-haxe
* Java: https://github.com/google/protobuf (Google-official implementation)
* Java: https://github.com/protocolbuffers/protobuf (Google-official implementation)
* Java/Android: https://github.com/square/wire
* Java: https://github.com/HebiRobotics/QuickBuffers/
* Java ME: http://code.google.com/p/protobuf-javame/
* Java ME: https://code.google.com/p/protobuf-javame/
* Java ME: http://swingme.sourceforge.net/encode.shtml
* Java ME: http://code.google.com/p/protobuf-j2me/
* Javascript: http://code.google.com/p/protobuf-js/
* Javascript: https://code.google.com/p/protobuf-js/
* Javascript: http://github.com/sirikata/protojs
* Javascript: https://github.com/dcodeIO/ProtoBuf.js
* Javascript: http://code.google.com/p/protobuf-for-node/
* Javascript: http://code.google.com/p/protostuff/
* Javascript: https://code.google.com/p/protobuf-for-node/
* Javascript: https://code.google.com/p/protostuff/
* Javascript: https://github.com/seishun/node-protoc-plugin (Node.js port of plugin.h)
* Javascript: https://github.com/seishun/node-protoc-gen-javascript (Node.js port of the Google-official implementation)
* Javascript: https://github.com/ButterCam/sisyphus-js
@ -71,43 +71,45 @@ These are projects we know about implementing Protocol Buffers for other program
* Kotlin: https://github.com/Kotlin/kotlinx.serialization
* Kotlin: https://github.com/ButterCam/sisyphus
* Kotlin: https://github.com/open-toast/protokt
* Lua: http://code.google.com/p/protoc-gen-lua/
* Lua: https://code.google.com/p/protoc-gen-lua/
* Lua: http://github.com/indygreg/lua-protobuf
* Lua: https://github.com/Neopallium/lua-pb
* Matlab: http://code.google.com/p/protobuf-matlab/
* Mercury: http://code.google.com/p/protobuf-mercury/
* Objective C: http://code.google.com/p/protobuf-objc/
* Matlab: https://code.google.com/p/protobuf-matlab/
* Mercury: https://code.google.com/p/protobuf-mercury/
* Objective C: https://code.google.com/p/protobuf-objc/
* Objective C: https://github.com/alexeyxo/protobuf-objc
* OCaml: http://piqi.org/
* Perl: http://groups.google.com/group/protobuf-perl
* Perl: http://search.cpan.org/perldoc?Google::ProtocolBuffers
* Perl: https://metacpan.org/pod/Google::ProtocolBuffers
* Perl: https://metacpan.org/pod/Google::ProtocolBuffers::Dynamic
* Perl/XS: http://code.google.com/p/protobuf-perlxs/
* PHP: http://code.google.com/p/pb4php/
* Perl/XS: https://code.google.com/p/protobuf-perlxs/
* PHP: https://code.google.com/p/pb4php/
* PHP: https://github.com/allegro/php-protobuf/
* PHP: https://github.com/chobie/php-protocolbuffers
* PHP: http://drslump.github.com/Protobuf-PHP
* Prolog: http://www.swi-prolog.org/pldoc/package/protobufs.html
* Purescript: https://github.com/xc-jp/purescript-protobuf
* Python: https://github.com/google/protobuf (Google-official implementation)
* Python: https://github.com/protocolbuffers/protobuf (Google-official implementation)
* Python: https://github.com/eigenein/protobuf
* Python: https://github.com/danielgtaylor/python-betterproto
* R: http://cran.r-project.org/package=RProtoBuf
* Ruby: http://code.google.com/p/ruby-protobuf/
* Ruby: https://code.google.com/p/ruby-protobuf/
* Ruby: http://github.com/mozy/ruby-protocol-buffers
* Ruby: https://github.com/bmizerany/beefcake/tree/master/lib/beefcake
* Ruby: https://github.com/localshred/protobuf
* Rust: https://github.com/tokio-rs/prost
* Rust: https://github.com/stepancheg/rust-protobuf/
* Rust: https://github.com/tafia/quick-protobuf
* Scala: http://github.com/jeffplaisance/scala-protobuf
* Scala: http://code.google.com/p/protobuf-scala
* Scala: https://code.google.com/p/protobuf-scala
* Scala: https://github.com/SandroGrzicic/ScalaBuff
* Scala: https://scalapb.github.io
* Solidity: https://github.com/celer-network/pb3-gen-sol
* Swift: https://github.com/alexeyxo/protobuf-swift
* Swift: https://github.com/apple/swift-protobuf/
* Typescript: https://github.com/thesayyn/protoc-gen-ts
* Typescript: https://github.com/pbkit/pbkit
* Vala: https://launchpad.net/protobuf-vala
* Visual Basic: http://code.google.com/p/protobuf-net/
* Visual Basic: https://code.google.com/p/protobuf-net/
## RPC Implementations
@ -128,6 +130,7 @@ GRPC (http://www.grpc.io/) is Google's RPC implementation for Protocol Buffers.
* https://github.com/awakesecurity/gRPC-haskell (Haskell)
* https://github.com/Yeolar/raster (C++)
* https://github.com/jnordberg/wsrpc (JavaScript Node.js/Browser)
* https://github.com/pbkit/npm-packages/blob/main/frpc-test/src/index.spec.ts (TypeScript Node.js/Browser)
* https://github.com/ppissias/xsrpcj (Java)
* https://github.com/twitchtv/twirp (Multiple languages)
@ -157,24 +160,23 @@ There are miscellaneous other things you may find useful as a Protocol Buffers d
* [rules_closure](https://github.com/bazelbuild/rules_closure) `js-closure`
* [rules_go](https://github.com/bazelbuild/rules_go) `go`
* [rules_protobuf](https://github.com/pubref/rules_protobuf) `java` `c++` `c#` `go` `js-closure` `js-node` `python` `ruby`
* [NetBeans IDE plugin](http://code.google.com/p/protobuf-netbeans-plugin/)
* [Wireshark/Ethereal packet sniffer plugin](http://code.google.com/p/protobuf-wireshark/)
* [Alternate encodings (JSON, XML, HTML) for Java protobufs](http://code.google.com/p/protobuf-java-format/)
* [NetBeans IDE plugin](https://code.google.com/p/protobuf-netbeans-plugin/)
* [Wireshark/Ethereal packet sniffer plugin](https://code.google.com/p/protobuf-wireshark/)
* [Alternate encodings (JSON, XML, HTML) for Java protobufs](https://code.google.com/p/protobuf-java-format/)
* [Another JSON encoder/decoder for Java](https://github.com/sijuv/protobuf-codec)
* [Editor for serialized protobufs](http://code.google.com/p/protobufeditor/)
* [Editor for serialized protobufs](https://code.google.com/p/protobufeditor/)
* [IntelliJ IDEA plugin](http://github.com/jvolkman/intellij-protobuf-editor)
* [IntelliJ Protobuf Plugin](https://github.com/devkanro/intellij-protobuf-plugin)
* [TextMate syntax highlighting](http://github.com/michaeledgar/protobuf-tmbundle)
* [Oracle PL SQL plugin](http://code.google.com/p/protocol-buffer-plsql/)
* [Eclipse editor for protobuf (from Google)](http://code.google.com/p/protobuf-dt/)
* [Oracle PL SQL plugin](https://code.google.com/p/protocol-buffer-plsql/)
* [Eclipse editor for protobuf (from Google)](https://code.google.com/p/protobuf-dt/)
* [C++ Builder compatible protobuf](https://github.com/saadware/protobuf-cppbuilder)
* Maven Protobuf Compiler Plugin
* By xolstice.org ([Documentation](https://www.xolstice.org/protobuf-maven-plugin/)) ([Source](https://github.com/xolstice/protobuf-maven-plugin/)) [![Maven Central](https://img.shields.io/maven-central/v/org.xolstice.maven.plugins/protobuf-maven-plugin.svg)](https://repo1.maven.org/maven2/org/xolstice/maven/plugins/protobuf-maven-plugin/)
* http://igor-petruk.github.com/protobuf-maven-plugin/
* http://code.google.com/p/maven-protoc-plugin/
* https://code.google.com/p/maven-protoc-plugin/
* https://github.com/os72/protoc-jar-maven-plugin
* [Documentation generator plugin (Markdown/HTML/DocBook/...)](https://github.com/pseudomuto/protoc-gen-doc)
* [DocBook generator for .proto files](http://code.google.com/p/protoc-gen-docbook/)
* [DocBook generator for .proto files](https://code.google.com/p/protoc-gen-docbook/)
* [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)

View File

@ -193,7 +193,7 @@
;;;###autoload (add-to-list 'auto-mode-alist '("\\.proto\\'" . protobuf-mode))
;;;###autoload
(defun protobuf-mode ()
(define-derived-mode protobuf-mode prog-mode "Protobuf"
"Major mode for editing Protocol Buffers description language.
The hook `c-mode-common-hook' is run with no argument at mode

View File

@ -16,7 +16,7 @@ clean:
rm -f javac_middleman AddPerson*.class ListPeople*.class com/example/tutorial/*.class
rm -f protoc_middleman addressbook.pb.cc addressbook.pb.h addressbook_pb2.py com/example/tutorial/AddressBookProtos.java
rm -f *.pyc
rm -f protoc_middleman_go tutorial/*.pb.go add_person_go list_people_go go.mod go.sum
rm -f go/tutorialpb/*.pb.go add_person_go list_people_go
rm -f protoc_middleman_dart dart_tutorial/*.pb*.dart
rmdir dart_tutorial 2>/dev/null || true
rmdir tutorial 2>/dev/null || true
@ -28,10 +28,9 @@ protoc_middleman: addressbook.proto
protoc $$PROTO_PATH --cpp_out=. --java_out=. --python_out=. addressbook.proto
@touch protoc_middleman
protoc_middleman_go: addressbook.proto
mkdir -p tutorial # make directory for go package
protoc $$PROTO_PATH --go_out=tutorial addressbook.proto
@touch protoc_middleman_go
go/tutorialpb/addressbook.pb.go: addressbook.proto
mkdir -p go/tutorialpb # make directory for go package
protoc $$PROTO_PATH --go_opt=paths=source_relative --go_out=go/tutorialpb addressbook.proto
protoc_middleman_dart: addressbook.proto
mkdir -p dart_tutorial # make directory for the dart package
@ -51,21 +50,17 @@ add_person_dart: add_person.dart protoc_middleman_dart
list_people_dart: list_people.dart protoc_middleman_dart
go_mod:
go mod init github.com/protocolbuffers/protobuf/examples
go mod tidy
add_person_go: go/cmd/add_person/add_person.go go/tutorialpb/addressbook.pb.go
cd go && go build -o ../add_person_go ./cmd/add_person
add_person_go: add_person.go protoc_middleman_go go_mod
go build -o add_person_go add_person.go
add_person_gotest: go/tutorialpb/addressbook.pb.go
cd go && go test ./cmd/add_person
add_person_gotest: add_person_test.go add_person_go go_mod
go test add_person.go add_person_test.go
list_people_go: go/cmd/list_people/list_people.go go/tutorialpb/addressbook.pb.go
cd go && go build -o ../list_people_go ./cmd/list_people
list_people_go: list_people.go protoc_middleman_go go_mod
go build -o list_people_go list_people.go
list_people_gotest: list_people.go list_people_go go_mod
go test list_people.go list_people_test.go
list_people_gotest: go/tutorialpb/addressbook.pb.go
cd go && go test ./cmd/list_people
javac_middleman: AddPerson.java ListPeople.java protoc_middleman
javac -cp $$CLASSPATH AddPerson.java ListPeople.java com/example/tutorial/AddressBookProtos.java

View File

@ -91,22 +91,18 @@ scripts) and can be used to create/display an address book data file.
### Go
The Go example requires a plugin to the protocol buffer compiler, so it is not
build with all the other examples. See:
Follow instructions in [../README.md](../README.md) to install protoc. Then
install the Go protoc plugin (protoc-gen-go):
https://github.com/golang/protobuf
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
for more information about Go protocol buffer support.
The "go install" command will install protoc-gen-go into the GOBIN
directory. You can set the $GOBIN environment variable before
running "go install" to change the install location. Make sure the
install directory is in your shell $PATH.
First, install the Protocol Buffers compiler (protoc).
Then, install the Go Protocol Buffers plugin ($GOPATH/bin must be in your $PATH
for protoc to find it):
go get github.com/golang/protobuf/protoc-gen-go
Build the Go samples in this directory with "make go". This creates the
following executable files in the current directory:
Build the Go samples with "make go". This creates the following
executable files in the current directory:
add_person_go list_people_go

View File

@ -24,7 +24,7 @@ option csharp_namespace = "Google.Protobuf.Examples.AddressBook";
// [END csharp_declaration]
// [START go_declaration]
option go_package = "../tutorial";
option go_package = "github.com/protocolbuffers/protobuf/examples/go/tutorialpb";
// [END go_declaration]
// [START messages]

View File

@ -9,8 +9,8 @@ import (
"os"
"strings"
"github.com/golang/protobuf/proto"
pb "github.com/protocolbuffers/protobuf/examples/tutorial"
pb "github.com/protocolbuffers/protobuf/examples/go/tutorialpb"
"google.golang.org/protobuf/proto"
)
func promptForAddress(r io.Reader) (*pb.Person, error) {

View File

@ -4,8 +4,8 @@ import (
"strings"
"testing"
"github.com/golang/protobuf/proto"
pb "github.com/protocolbuffers/protobuf/examples/tutorial"
pb "github.com/protocolbuffers/protobuf/examples/go/tutorialpb"
"google.golang.org/protobuf/proto"
)
func TestPromptForAddressReturnsAddress(t *testing.T) {
@ -51,7 +51,7 @@ unknown
}
for i := 0; i < phones; i++ {
if !proto.Equal(got.Phones[i], want[i]) {
t.Errorf("want phone %q, got %q", *want[i], *got.Phones[i])
t.Errorf("want phone %q, got %q", want[i], got.Phones[i])
}
}

View File

@ -7,8 +7,8 @@ import (
"log"
"os"
"github.com/golang/protobuf/proto"
pb "github.com/protocolbuffers/protobuf/examples/tutorial"
pb "github.com/protocolbuffers/protobuf/examples/go/tutorialpb"
"google.golang.org/protobuf/proto"
)
func writePerson(w io.Writer, p *pb.Person) {

View File

@ -5,7 +5,7 @@ import (
"strings"
"testing"
pb "github.com/protocolbuffers/protobuf/examples/tutorial"
pb "github.com/protocolbuffers/protobuf/examples/go/tutorialpb"
)
func TestWritePersonWritesPerson(t *testing.T) {

5
examples/go/go.mod Normal file
View File

@ -0,0 +1,5 @@
module github.com/protocolbuffers/protobuf/examples/go
go 1.14
require google.golang.org/protobuf v1.27.1

6
examples/go/go.sum Normal file
View File

@ -0,0 +1,6 @@
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=

View File

@ -1,6 +1,6 @@
{
"sdk": {
"version": "5.0.102",
"version": "6.0.100",
"rollForward": "latestMinor"
}
}

View File

@ -2,6 +2,8 @@ test_suite(
name = "tests",
tests = [
"//java/core:tests",
"//java/kotlin:tests",
"//java/kotlin-lite:tests",
"//java/lite:tests",
"//java/util:tests",
],
@ -13,4 +15,4 @@ filegroup(
"//java/core:release", # contains lite.
"//java/util:release",
]
)
)

View File

@ -23,7 +23,7 @@ If you are using Maven, use the following:
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.18.0</version>
<version>3.19.4</version>
</dependency>
```
@ -37,7 +37,7 @@ protobuf-java-util package:
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
<version>3.18.0</version>
<version>3.19.4</version>
</dependency>
```
@ -45,7 +45,7 @@ protobuf-java-util package:
If you are using Gradle, add the following to your `build.gradle` file's dependencies:
```
implementation 'com.google.protobuf:protobuf-java:3.18.0'
implementation 'com.google.protobuf:protobuf-java:3.19.4'
```
Again, be sure to check that the version number matches (or is newer than) the version number of protoc that you are using.

View File

@ -4,7 +4,7 @@
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-bom</artifactId>
<version>3.18.1</version>
<version>3.19.4</version>
<packaging>pom</packaging>
<name>Protocol Buffers [BOM]</name>
@ -29,7 +29,7 @@
<licenses>
<license>
<name>3-Clause BSD License</name>
<name>BSD-3-Clause</name>
<url>https://opensource.org/licenses/BSD-3-Clause</url>
</license>
</licenses>

View File

@ -1,5 +1,5 @@
load("@bazel_skylib//rules:build_test.bzl", "build_test")
load("@rules_java//java:defs.bzl", "java_library", "java_proto_library", "java_lite_proto_library")
load("@rules_java//java:defs.bzl", "java_library", "java_lite_proto_library", "java_proto_library")
load("@rules_jvm_external//:defs.bzl", "java_export")
load("@rules_proto//proto:defs.bzl", "proto_lang_toolchain", "proto_library")
load("//:internal.bzl", "conformance_test")
@ -103,7 +103,7 @@ LITE_SRCS = [
java_library(
name = "lite",
srcs = LITE_SRCS + [
"//:gen_well_known_protos_javalite"
"//:gen_well_known_protos_javalite",
],
visibility = [
"//java/lite:__pkg__",
@ -115,10 +115,10 @@ java_export(
name = "lite_mvn",
maven_coordinates = "com.google.protobuf:protobuf-javalite:%s" % PROTOBUF_VERSION,
pom_template = "//java/lite:pom_template.xml",
runtime_deps = [":lite"],
resources = [
"//:lite_well_known_protos",
],
runtime_deps = [":lite"],
)
java_library(
@ -150,25 +150,25 @@ java_export(
name = "core_mvn",
maven_coordinates = "com.google.protobuf:protobuf-java:%s" % PROTOBUF_VERSION,
pom_template = "pom_template.xml",
runtime_deps = [":core"],
resources = [
"//:well_known_protos",
],
runtime_deps = [":core"],
)
filegroup(
name = "release",
visibility = ["//java:__pkg__"],
srcs = [
":core_mvn-pom",
":core_mvn-maven-source",
":core_mvn-docs",
":core_mvn-maven-source",
":core_mvn-pom",
":core_mvn-project",
":lite_mvn-pom",
":lite_mvn-maven-source",
":lite_mvn-docs",
":lite_mvn-maven-source",
":lite_mvn-pom",
":lite_mvn-project",
]
],
visibility = ["//java:__pkg__"],
)
proto_lang_toolchain(
@ -176,6 +176,21 @@ proto_lang_toolchain(
command_line = "--java_out=$(OUT)",
runtime = ":core",
visibility = ["//visibility:public"],
# keep this in sync w/ WELL_KNOWN_PROTO_MAP in //:BUILD
blacklisted_protos = [
"//:any_proto",
"//:api_proto",
"//:compiler_plugin_proto",
"//:descriptor_proto",
"//:duration_proto",
"//:empty_proto",
"//:field_mask_proto",
"//:source_context_proto",
"//:struct_proto",
"//:timestamp_proto",
"//:type_proto",
"//:wrappers_proto",
],
)
proto_library(
@ -207,23 +222,25 @@ java_library(
name = "test_util",
srcs = [
"src/test/java/com/google/protobuf/TestUtil.java",
"src/test/java/com/google/protobuf/TestUtilLite.java"
"src/test/java/com/google/protobuf/TestUtilLite.java",
],
deps = [
":core",
":generic_test_protos_java_proto",
":java_test_protos_java_proto",
"//external:guava",
"//external:junit",
"@maven//:com_google_guava_guava",
"@maven//:junit_junit",
],
visibility = ["//java:__subpackages__"],
)
test_suite(
name = "tests",
tests = [
"core_build_test",
"conformance_test",
"core_build_test",
"core_tests",
"utf8_tests",
],
)
@ -236,30 +253,52 @@ build_test(
conformance_test(
name = "conformance_test",
testee = "//:conformance_java",
failure_list = "//:conformance/failure_list_java.txt",
testee = "//:conformance_java",
text_format_failure_list = "//:conformance/text_format_failure_list_java.txt",
)
junit_tests(
name = "core_tests",
srcs = glob(["src/test/java/**/*.java"], exclude = [
"src/test/java/com/google/protobuf/TestUtil.java",
"src/test/java/com/google/protobuf/TestUtilLite.java",
]),
size = "small",
srcs = glob(
["src/test/java/**/*.java"],
exclude = [
"src/test/java/com/google/protobuf/DecodeUtf8Test.java",
"src/test/java/com/google/protobuf/IsValidUtf8Test.java",
"src/test/java/com/google/protobuf/TestUtil.java",
"src/test/java/com/google/protobuf/TestUtilLite.java",
],
),
data = ["//:testdata"],
size = "large",
deps = [
":core",
":generic_test_protos_java_proto",
":java_test_protos_java_proto",
":test_util",
"//external:easymock",
"//external:easymock_classextension",
"//external:guava",
"//external:junit",
"//external:truth",
]
"@maven//:com_google_guava_guava",
"@maven//:com_google_truth_truth",
"@maven//:junit_junit",
"@maven//:org_easymock_easymock",
],
)
# The UTF-8 validation tests are much slower than the other tests, so they get
# their own test target with a longer timeout.
junit_tests(
name = "utf8_tests",
size = "large",
srcs = [
"src/test/java/com/google/protobuf/DecodeUtf8Test.java",
"src/test/java/com/google/protobuf/IsValidUtf8Test.java",
"src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java",
],
deps = [
":core",
"@maven//:com_google_guava_guava",
"@maven//:com_google_truth_truth",
"@maven//:junit_junit",
],
)
java_lite_proto_library(
@ -282,27 +321,28 @@ genrule(
name = "rewrite_javalite_test_util",
srcs = [
"//java/lite:lite.awk",
"src/test/java/com/google/protobuf/TestUtil.java"
"src/test/java/com/google/protobuf/TestUtil.java",
],
outs = ["TestUtil.java"],
cmd = "awk -f $(location //java/lite:lite.awk) $(location src/test/java/com/google/protobuf/TestUtil.java) > $@"
cmd = "awk -f $(location //java/lite:lite.awk) $(location src/test/java/com/google/protobuf/TestUtil.java) > $@",
)
java_library(
name = "test_util_lite",
srcs = [
"src/test/java/com/google/protobuf/TestUtilLite.java",
":rewrite_javalite_test_util",
"src/test/java/com/google/protobuf/TestUtilLite.java"
],
visibility = [
"//java/lite:__pkg__",
"//java/kotlin-lite:__pkg__",
],
deps = [
":generic_test_protos_java_proto_lite",
":java_test_protos_java_proto_lite",
":lite_runtime_only",
"//external:guava",
"//external:junit",
"@maven//:com_google_guava_guava",
"@maven//:junit_junit",
],
)
@ -344,6 +384,7 @@ LITE_TEST_EXCLUSIONS = [
"src/test/java/com/google/protobuf/TypeRegistryTest.java",
"src/test/java/com/google/protobuf/UnknownEnumValueTest.java",
"src/test/java/com/google/protobuf/UnknownFieldSetLiteTest.java",
"src/test/java/com/google/protobuf/UnknownFieldSetPerformanceTest.java",
"src/test/java/com/google/protobuf/UnknownFieldSetTest.java",
"src/test/java/com/google/protobuf/WellKnownTypesTest.java",
"src/test/java/com/google/protobuf/WireFormatTest.java",
@ -351,18 +392,20 @@ LITE_TEST_EXCLUSIONS = [
junit_tests(
name = "lite_tests",
srcs = glob(["src/test/java/**/*.java"], exclude = LITE_TEST_EXCLUSIONS),
size = "large",
srcs = glob(
["src/test/java/**/*.java"],
exclude = LITE_TEST_EXCLUSIONS,
),
data = ["//:testdata"],
test_prefix = "Lite",
size = "large",
deps = [
":lite",
":generic_test_protos_java_proto_lite",
":java_test_protos_java_proto_lite",
":lite",
":test_util_lite",
"//external:easymock",
"//external:junit",
"//external:truth",
]
"@maven//:com_google_truth_truth",
"@maven//:junit_junit",
"@maven//:org_easymock_easymock",
],
)

View File

@ -30,7 +30,6 @@
<arg value="${test.proto.dir}/com/google/protobuf/map_initialization_order_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/map_lite_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/map_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/message_lite_extension_util_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/multiple_files_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/nested_builders_test.proto"/>
<arg value="${test.proto.dir}/com/google/protobuf/nested_extension.proto"/>

View File

@ -4,7 +4,7 @@
<parent>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-parent</artifactId>
<version>3.18.1</version>
<version>3.19.4</version>
</parent>
<artifactId>protobuf-java</artifactId>

View File

@ -224,7 +224,7 @@ public abstract class AbstractMessage
}
/**
* Compares two set of fields. This method is used to implement {@link
* Compares two sets of fields. This method is used to implement {@link
* AbstractMessage#equals(Object)} and {@link AbstractMutableMessage#equals(Object)}. It takes
* special care of bytes fields because immutable messages and mutable messages use different Java
* type to represent a bytes field and this method should be able to compare immutable messages,
@ -242,8 +242,8 @@ public abstract class AbstractMessage
Object value2 = b.get(descriptor);
if (descriptor.getType() == FieldDescriptor.Type.BYTES) {
if (descriptor.isRepeated()) {
List list1 = (List) value1;
List list2 = (List) value2;
List<?> list1 = (List) value1;
List<?> list2 = (List) value2;
if (list1.size() != list2.size()) {
return false;
}
@ -383,8 +383,6 @@ public abstract class AbstractMessage
// them to insure that they don't change after verification (since
// the Message interface itself cannot enforce immutability of
// implementations).
// TODO(kenton): Provide a function somewhere called makeDeepCopy()
// which allows people to make secure deep copies of messages.
for (final Map.Entry<FieldDescriptor, Object> entry : allFields.entrySet()) {
final FieldDescriptor field = entry.getKey();
@ -568,17 +566,6 @@ public abstract class AbstractMessage
final InputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException {
return (BuilderType) super.mergeFrom(input, extensionRegistry);
}
@Override
public boolean mergeDelimitedFrom(final InputStream input) throws IOException {
return super.mergeDelimitedFrom(input);
}
@Override
public boolean mergeDelimitedFrom(
final InputStream input, final ExtensionRegistryLite extensionRegistry) throws IOException {
return super.mergeDelimitedFrom(input, extensionRegistry);
}
}
/**

View File

@ -89,9 +89,9 @@ public abstract class AbstractMessageLite<
final int serialized = getSerializedSize();
final int bufferSize =
CodedOutputStream.computePreferredBufferSize(
CodedOutputStream.computeRawVarint32Size(serialized) + serialized);
CodedOutputStream.computeUInt32SizeNoTag(serialized) + serialized);
final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize);
codedOutput.writeRawVarint32(serialized);
codedOutput.writeUInt32NoTag(serialized);
writeTo(codedOutput);
codedOutput.flush();
}
@ -316,8 +316,11 @@ public abstract class AbstractMessageLite<
@Override
public long skip(final long n) throws IOException {
final long result = super.skip(Math.min(n, limit));
// because we take the minimum of an int and a long, result is guaranteed to be
// less than or equal to Integer.MAX_INT so this cast is safe
int result = (int) super.skip(Math.min(n, limit));
if (result >= 0) {
// if the superclass adheres to the contract for skip, this condition is always true
limit -= result;
}
return result;

View File

@ -38,6 +38,7 @@ import java.nio.ByteBuffer;
* A buffer that was allocated by a {@link BufferAllocator}. For every buffer, it is guaranteed that
* at least one of {@link #hasArray()} or {@link #hasNioBuffer()} will be {@code true}.
*/
@CheckReturnValue
@ExperimentalApi
abstract class AllocatedBuffer {
/**
@ -106,6 +107,7 @@ abstract class AllocatedBuffer {
* @return This buffer
* @throws IllegalArgumentException If the preconditions on {@code position} do not hold
*/
@CanIgnoreReturnValue
public abstract AllocatedBuffer position(int position);
/**

View File

@ -43,6 +43,7 @@ import java.io.IOException;
* IndexOutOfBoundsException and convert it to protobuf's InvalidProtocolBufferException when
* crossing protobuf public API boundaries.
*/
@CheckReturnValue
final class ArrayDecoders {
/**
* A helper used to return multiple values in a Java function. Java doesn't natively support
@ -548,7 +549,6 @@ final class ArrayDecoders {
}
/** Decodes a packed sint64 field. Returns the position after all read values. */
@SuppressWarnings("unchecked")
static int decodePackedSInt64List(
byte[] data, int position, ProtobufList<?> list, Registers registers) throws IOException {
final LongArrayList output = (LongArrayList) list;

View File

@ -48,6 +48,7 @@ import java.util.Map;
* A {@link Reader} that reads from a buffer containing a message serialized with the binary
* protocol.
*/
@CheckReturnValue
@ExperimentalApi
abstract class BinaryReader implements Reader {
private static final int FIXED32_MULTIPLE_MASK = FIXED32_SIZE - 1;
@ -271,6 +272,7 @@ abstract class BinaryReader implements Reader {
}
}
@Deprecated
@Override
public <T> T readGroup(Class<T> clazz, ExtensionRegistryLite extensionRegistry)
throws IOException {
@ -278,6 +280,7 @@ abstract class BinaryReader implements Reader {
return readGroup(Protobuf.getInstance().schemaFor(clazz), extensionRegistry);
}
@Deprecated
@Override
public <T> T readGroupBySchemaWithCheck(
Schema<T> schema, ExtensionRegistryLite extensionRegistry) throws IOException {
@ -956,6 +959,7 @@ abstract class BinaryReader implements Reader {
}
}
@Deprecated
@Override
public <T> void readGroupList(
List<T> target, Class<T> targetType, ExtensionRegistryLite extensionRegistry)
@ -964,6 +968,7 @@ abstract class BinaryReader implements Reader {
readGroupList(target, schema, extensionRegistry);
}
@Deprecated
@Override
public <T> void readGroupList(
List<T> target, Schema<T> schema, ExtensionRegistryLite extensionRegistry)

View File

@ -65,6 +65,7 @@ import java.util.Queue;
* The {@link #getTotalBytesWritten()} will continue to reflect the total of the write and will not
* be reset.
*/
@CheckReturnValue
@ExperimentalApi
abstract class BinaryWriter extends ByteOutput implements Writer {
public static final int DEFAULT_CHUNK_SIZE = 4096;
@ -162,6 +163,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
* <p>After calling this method, the writer can not be reused. Create a new writer for future
* writes.
*/
@CanIgnoreReturnValue
public final Queue<AllocatedBuffer> complete() {
finishCurrentBuffer();
return buffers;
@ -808,6 +810,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
@Deprecated
@Override
public final void writeGroupList(int fieldNumber, List<?> list) throws IOException {
for (int i = list.size() - 1; i >= 0; i--) {
@ -815,6 +818,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
}
}
@Deprecated
@Override
public final void writeGroupList(int fieldNumber, List<?> list, Schema schema)
throws IOException {
@ -1080,6 +1084,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Deprecated
@Override
public void writeGroup(int fieldNumber, Object value) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
@ -1497,8 +1502,8 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
this.allocatedBuffer = allocatedBuffer;
this.buffer = allocatedBuffer.array();
int arrayOffset = allocatedBuffer.arrayOffset();
this.limit = arrayOffset + allocatedBuffer.limit();
this.offset = arrayOffset + allocatedBuffer.position();
this.limit = (long) arrayOffset + allocatedBuffer.limit();
this.offset = (long) arrayOffset + allocatedBuffer.position();
this.offsetMinusOne = offset - 1;
this.limitMinusOne = limit - 1;
this.pos = limitMinusOne;
@ -2148,6 +2153,7 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED);
}
@Deprecated
@Override
public void writeGroup(int fieldNumber, Object value) throws IOException {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
@ -2162,11 +2168,13 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeStartGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeEndGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_END_GROUP);
@ -2719,11 +2727,13 @@ abstract class BinaryWriter extends ByteOutput implements Writer {
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeStartGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeEndGroup(int fieldNumber) {
writeTag(fieldNumber, WIRETYPE_END_GROUP);

View File

@ -36,6 +36,7 @@ import java.nio.ByteBuffer;
* An object responsible for allocation of buffers. This is an extension point to enable buffer
* pooling within an application.
*/
@CheckReturnValue
@ExperimentalApi
abstract class BufferAllocator {
private static final BufferAllocator UNPOOLED =

View File

@ -236,6 +236,11 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
return size() == 0;
}
/** Returns an empty {@code ByteString} of size {@code 0}. */
public static final ByteString empty() {
return EMPTY;
}
// =================================================================
// Comparison
@ -253,6 +258,38 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
return value & UNSIGNED_BYTE_MASK;
}
/** Returns the numeric value of the given character in hex, or -1 if invalid. */
private static int hexDigit(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
} else {
return -1;
}
}
/**
* Returns the numeric value of the given character at index in hexString.
*
* @throws NumberFormatException if the hexString character is invalid.
*/
private static int extractHexDigit(String hexString, int index) {
int digit = hexDigit(hexString.charAt(index));
if (digit == -1) {
throw new NumberFormatException(
"Invalid hexString "
+ hexString
+ " must only contain [0-9a-fA-F] but contained "
+ hexString.charAt(index)
+ " at index "
+ index);
}
return digit;
}
/**
* Compares two {@link ByteString}s lexicographically, treating their contents as unsigned byte
* values between 0 and 255 (inclusive).
@ -282,8 +319,8 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
};
/**
* Returns a {@link Comparator} which compares {@link ByteString}-s lexicographically
* as sequences of unsigned bytes (i.e. values between 0 and 255, inclusive).
* Returns a {@link Comparator} which compares {@link ByteString}-s lexicographically as sequences
* of unsigned bytes (i.e. values between 0 and 255, inclusive).
*
* <p>For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because it
* is interpreted as an unsigned value, {@code 255}:
@ -346,6 +383,30 @@ public abstract class ByteString implements Iterable<Byte>, Serializable {
return size() >= suffix.size() && substring(size() - suffix.size()).equals(suffix);
}
// =================================================================
// String -> ByteString
/**
* Returns a {@code ByteString} from a hexadecimal String. Alternative CharSequences should use
* {@link ByteStrings#decode(CharSequence, BaseEncoding)}
*
* @param hexString String of hexadecimal digits to create {@code ByteString} from.
* @throws NumberFormatException if the hexString does not contain a parsable hex String.
*/
public static ByteString fromHex(@CompileTimeConstant String hexString) {
if (hexString.length() % 2 != 0) {
throw new NumberFormatException(
"Invalid hexString " + hexString + " of length " + hexString.length() + " must be even.");
}
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < bytes.length; i++) {
int d1 = extractHexDigit(hexString, 2 * i);
int d2 = extractHexDigit(hexString, 2 * i + 1);
bytes[i] = (byte) (d1 << 4 | d2);
}
return new LiteralByteString(bytes);
}
// =================================================================
// byte[] -> ByteString

View File

@ -680,33 +680,33 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_VARINT:
{
long value = readInt64();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeUInt64NoTag(value);
return true;
}
case WireFormat.WIRETYPE_FIXED64:
{
long value = readRawLittleEndian64();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeFixed64NoTag(value);
return true;
}
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
{
ByteString value = readBytes();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeBytesNoTag(value);
return true;
}
case WireFormat.WIRETYPE_START_GROUP:
{
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
skipMessage(output);
int endtag =
WireFormat.makeTag(
WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP);
checkLastTagWas(endtag);
output.writeRawVarint32(endtag);
output.writeUInt32NoTag(endtag);
return true;
}
case WireFormat.WIRETYPE_END_GROUP:
@ -716,7 +716,7 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_FIXED32:
{
int value = readRawLittleEndian32();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeFixed32NoTag(value);
return true;
}
@ -1395,33 +1395,33 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_VARINT:
{
long value = readInt64();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeUInt64NoTag(value);
return true;
}
case WireFormat.WIRETYPE_FIXED64:
{
long value = readRawLittleEndian64();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeFixed64NoTag(value);
return true;
}
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
{
ByteString value = readBytes();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeBytesNoTag(value);
return true;
}
case WireFormat.WIRETYPE_START_GROUP:
{
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
skipMessage(output);
int endtag =
WireFormat.makeTag(
WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP);
checkLastTagWas(endtag);
output.writeRawVarint32(endtag);
output.writeUInt32NoTag(endtag);
return true;
}
case WireFormat.WIRETYPE_END_GROUP:
@ -1431,7 +1431,7 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_FIXED32:
{
int value = readRawLittleEndian32();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeFixed32NoTag(value);
return true;
}
@ -2163,33 +2163,33 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_VARINT:
{
long value = readInt64();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeUInt64NoTag(value);
return true;
}
case WireFormat.WIRETYPE_FIXED64:
{
long value = readRawLittleEndian64();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeFixed64NoTag(value);
return true;
}
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
{
ByteString value = readBytes();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeBytesNoTag(value);
return true;
}
case WireFormat.WIRETYPE_START_GROUP:
{
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
skipMessage(output);
int endtag =
WireFormat.makeTag(
WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP);
checkLastTagWas(endtag);
output.writeRawVarint32(endtag);
output.writeUInt32NoTag(endtag);
return true;
}
case WireFormat.WIRETYPE_END_GROUP:
@ -2199,7 +2199,7 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_FIXED32:
{
int value = readRawLittleEndian32();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeFixed32NoTag(value);
return true;
}
@ -3284,33 +3284,33 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_VARINT:
{
long value = readInt64();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeUInt64NoTag(value);
return true;
}
case WireFormat.WIRETYPE_FIXED64:
{
long value = readRawLittleEndian64();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeFixed64NoTag(value);
return true;
}
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
{
ByteString value = readBytes();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeBytesNoTag(value);
return true;
}
case WireFormat.WIRETYPE_START_GROUP:
{
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
skipMessage(output);
int endtag =
WireFormat.makeTag(
WireFormat.getTagFieldNumber(tag), WireFormat.WIRETYPE_END_GROUP);
checkLastTagWas(endtag);
output.writeRawVarint32(endtag);
output.writeUInt32NoTag(endtag);
return true;
}
case WireFormat.WIRETYPE_END_GROUP:
@ -3320,7 +3320,7 @@ public abstract class CodedInputStream {
case WireFormat.WIRETYPE_FIXED32:
{
int value = readRawLittleEndian32();
output.writeRawVarint32(tag);
output.writeUInt32NoTag(tag);
output.writeFixed32NoTag(value);
return true;
}

View File

@ -44,6 +44,7 @@ import java.util.List;
import java.util.Map;
/** An adapter between the {@link Reader} interface and {@link CodedInputStream}. */
@CheckReturnValue
@ExperimentalApi
final class CodedInputStreamReader implements Reader {
private static final int FIXED32_MULTIPLE_MASK = FIXED32_SIZE - 1;
@ -165,7 +166,6 @@ final class CodedInputStreamReader implements Reader {
return input.readStringRequireUtf8();
}
@SuppressWarnings("unchecked")
@Override
public <T> T readMessage(Class<T> clazz, ExtensionRegistryLite extensionRegistry)
throws IOException {
@ -181,7 +181,7 @@ final class CodedInputStreamReader implements Reader {
return readMessage(schema, extensionRegistry);
}
@SuppressWarnings("unchecked")
@Deprecated
@Override
public <T> T readGroup(Class<T> clazz, ExtensionRegistryLite extensionRegistry)
throws IOException {
@ -189,7 +189,7 @@ final class CodedInputStreamReader implements Reader {
return readGroup(Protobuf.getInstance().schemaFor(clazz), extensionRegistry);
}
@SuppressWarnings("unchecked")
@Deprecated
@Override
public <T> T readGroupBySchemaWithCheck(Schema<T> schema, ExtensionRegistryLite extensionRegistry)
throws IOException {
@ -821,6 +821,7 @@ final class CodedInputStreamReader implements Reader {
}
}
@Deprecated
@Override
public <T> void readGroupList(
List<T> target, Class<T> targetType, ExtensionRegistryLite extensionRegistry)
@ -829,6 +830,7 @@ final class CodedInputStreamReader implements Reader {
readGroupList(target, schema, extensionRegistry);
}
@Deprecated
@Override
public <T> void readGroupList(
List<T> target, Schema<T> schema, ExtensionRegistryLite extensionRegistry)
@ -1314,7 +1316,7 @@ final class CodedInputStreamReader implements Reader {
case UINT64:
return readUInt64();
default:
throw new RuntimeException("unsupported field type.");
throw new IllegalArgumentException("unsupported field type.");
}
}

View File

@ -1056,7 +1056,7 @@ public abstract class CodedOutputStream extends ByteOutput {
*/
@Deprecated
public static int computeGroupSize(final int fieldNumber, final MessageLite value) {
return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value);
return computeTagSize(fieldNumber) * 2 + value.getSerializedSize();
}
/**
@ -1072,6 +1072,7 @@ public abstract class CodedOutputStream extends ByteOutput {
/** Compute the number of bytes that would be needed to encode a {@code group} field. */
@Deprecated
@InlineMe(replacement = "value.getSerializedSize()")
public static int computeGroupSizeNoTag(final MessageLite value) {
return value.getSerializedSize();
}
@ -1089,6 +1090,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* @deprecated use {@link #writeUInt32NoTag} instead.
*/
@Deprecated
@InlineMe(replacement = "this.writeUInt32NoTag(value)")
public final void writeRawVarint32(int value) throws IOException {
writeUInt32NoTag(value);
}
@ -1099,6 +1101,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* @deprecated use {@link #writeUInt64NoTag} instead.
*/
@Deprecated
@InlineMe(replacement = "this.writeUInt64NoTag(value)")
public final void writeRawVarint64(long value) throws IOException {
writeUInt64NoTag(value);
}
@ -1110,6 +1113,9 @@ public abstract class CodedOutputStream extends ByteOutput {
* @deprecated use {@link #computeUInt32SizeNoTag(int)} instead.
*/
@Deprecated
@InlineMe(
replacement = "CodedOutputStream.computeUInt32SizeNoTag(value)",
imports = "com.google.protobuf.CodedOutputStream")
public static int computeRawVarint32Size(final int value) {
return computeUInt32SizeNoTag(value);
}
@ -1120,6 +1126,9 @@ public abstract class CodedOutputStream extends ByteOutput {
* @deprecated use {@link #computeUInt64SizeNoTag(long)} instead.
*/
@Deprecated
@InlineMe(
replacement = "CodedOutputStream.computeUInt64SizeNoTag(value)",
imports = "com.google.protobuf.CodedOutputStream")
public static int computeRawVarint64Size(long value) {
return computeUInt64SizeNoTag(value);
}
@ -1130,6 +1139,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* @deprecated Use {@link #writeFixed32NoTag} instead.
*/
@Deprecated
@InlineMe(replacement = "this.writeFixed32NoTag(value)")
public final void writeRawLittleEndian32(final int value) throws IOException {
writeFixed32NoTag(value);
}
@ -1140,6 +1150,7 @@ public abstract class CodedOutputStream extends ByteOutput {
* @deprecated Use {@link #writeFixed64NoTag} instead.
*/
@Deprecated
@InlineMe(replacement = "this.writeFixed64NoTag(value)")
public final void writeRawLittleEndian64(final long value) throws IOException {
writeFixed64NoTag(value);
}

View File

@ -39,6 +39,7 @@ import java.util.List;
import java.util.Map;
/** An adapter between the {@link Writer} interface and {@link CodedOutputStream}. */
@CheckReturnValue
@ExperimentalApi
final class CodedOutputStreamWriter implements Writer {
private final CodedOutputStream output;
@ -154,6 +155,7 @@ final class CodedOutputStreamWriter implements Writer {
output.writeMessage(fieldNumber, (MessageLite) value, schema);
}
@Deprecated
@Override
public void writeGroup(int fieldNumber, Object value) throws IOException {
output.writeGroup(fieldNumber, (MessageLite) value);
@ -164,11 +166,13 @@ final class CodedOutputStreamWriter implements Writer {
output.writeGroup(fieldNumber, (MessageLite) value, schema);
}
@Deprecated
@Override
public void writeStartGroup(int fieldNumber) throws IOException {
output.writeTag(fieldNumber, WireFormat.WIRETYPE_START_GROUP);
}
@Deprecated
@Override
public void writeEndGroup(int fieldNumber) throws IOException {
output.writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP);
@ -561,6 +565,7 @@ final class CodedOutputStreamWriter implements Writer {
}
}
@Deprecated
@Override
public void writeGroupList(int fieldNumber, List<?> value) throws IOException {
for (int i = 0; i < value.size(); ++i) {

View File

@ -30,18 +30,18 @@
package com.google.protobuf;
/**
* A prerun for a test suite that allows running the full protocol buffer tests in a mode that
* disables the optimization for not using {@link RepeatedFieldBuilder} and {@link
* SingleFieldBuilder} until they are requested. This allows us to run all the tests through both
* code paths and ensures that both code paths produce identical results.
*
* @author jonp@google.com (Jon Perlow)
*/
public class ForceFieldBuildersPreRun implements Runnable {
import static java.lang.annotation.RetentionPolicy.CLASS;
@Override
public void run() {
GeneratedMessage.enableAlwaysUseFieldBuildersForTesting();
}
}
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation for method parameter and class field declarations, which denotes that corresponding
* actual values must be compile-time constant expressions.
*/
@Documented
@Retention(CLASS)
@Target({ElementType.PARAMETER, ElementType.FIELD})
@interface CompileTimeConstant {}

View File

@ -278,14 +278,13 @@ public final class Descriptors {
/**
* Construct a {@code FileDescriptor}.
*
* @param proto The protocol message form of the FileDescriptor.
* @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies.
* @param proto the protocol message form of the FileDescriptort
* @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies
* @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur
* for a number of reasons, e.g. because a field has an undefined type or because two
* messages were defined with the same name.
* for a number of reasons; for instance, because a field has an undefined type or because
* two messages were defined with the same name.
*/
public static FileDescriptor buildFrom(
final FileDescriptorProto proto, final FileDescriptor[] dependencies)
public static FileDescriptor buildFrom(FileDescriptorProto proto, FileDescriptor[] dependencies)
throws DescriptorValidationException {
return buildFrom(proto, dependencies, false);
}
@ -293,18 +292,19 @@ public final class Descriptors {
/**
* Construct a {@code FileDescriptor}.
*
* @param proto The protocol message form of the FileDescriptor.
* @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies.
* @param allowUnknownDependencies If true, non-exist dependenncies will be ignored and
* undefined message types will be replaced with a placeholder type.
* @param proto the protocol message form of the FileDescriptor
* @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies
* @param allowUnknownDependencies if true, non-existing dependencies will be ignored and
* undefined message types will be replaced with a placeholder type. Undefined enum types
* still cause a DescriptorValidationException.
* @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur
* for a number of reasons, e.g. because a field has an undefined type or because two
* messages were defined with the same name.
* for a number of reasons; for instance, because a field has an undefined type or because
* two messages were defined with the same name.
*/
public static FileDescriptor buildFrom(
final FileDescriptorProto proto,
final FileDescriptor[] dependencies,
final boolean allowUnknownDependencies)
FileDescriptorProto proto,
FileDescriptor[] dependencies,
boolean allowUnknownDependencies)
throws DescriptorValidationException {
// Building descriptors involves two steps: translating and linking.
// In the translation step (implemented by FileDescriptor's
@ -315,8 +315,8 @@ public final class Descriptors {
// FieldDescriptor for an embedded message contains a pointer directly
// to the Descriptor for that message's type. We also detect undefined
// types in the linking step.
final DescriptorPool pool = new DescriptorPool(dependencies, allowUnknownDependencies);
final FileDescriptor result =
DescriptorPool pool = new DescriptorPool(dependencies, allowUnknownDependencies);
FileDescriptor result =
new FileDescriptor(proto, dependencies, pool, allowUnknownDependencies);
result.crossLink();
return result;
@ -1837,8 +1837,8 @@ public final class Descriptors {
// The number represents an unknown enum value.
synchronized (this) {
if (cleanupQueue == null) {
cleanupQueue = new ReferenceQueue<EnumValueDescriptor>();
unknownValues = new HashMap<Integer, WeakReference<EnumValueDescriptor>>();
cleanupQueue = new ReferenceQueue<>();
unknownValues = new HashMap<>();
} else {
while (true) {
UnknownEnumValueReference toClean = (UnknownEnumValueReference) cleanupQueue.poll();
@ -2415,7 +2415,7 @@ public final class Descriptors {
}
private final Set<FileDescriptor> dependencies;
private boolean allowUnknownDependencies;
private final boolean allowUnknownDependencies;
private final Map<String, GenericDescriptor> descriptorsByName = new HashMap<>();
@ -2475,7 +2475,6 @@ public final class Descriptors {
final GenericDescriptor relativeTo,
final DescriptorPool.SearchFilter filter)
throws DescriptorValidationException {
// TODO(kenton): This could be optimized in a number of ways.
GenericDescriptor result;
String fullname;
@ -2547,11 +2546,11 @@ public final class Descriptors {
logger.warning(
"The descriptor for message type \""
+ name
+ "\" can not be found and a placeholder is created for it");
+ "\" cannot be found and a placeholder is created for it");
// We create a dummy message descriptor here regardless of the
// expected type. If the type should be message, this dummy
// descriptor will work well and if the type should be enum, a
// DescriptorValidationException will be thrown latter. In either
// DescriptorValidationException will be thrown later. In either
// case, the code works as expected: we allow unknown message types
// but not unknown enum types.
result = new Descriptor(fullname);
@ -2766,8 +2765,7 @@ public final class Descriptors {
final OneofDescriptorProto proto,
final FileDescriptor file,
final Descriptor parent,
final int index)
throws DescriptorValidationException {
final int index) {
this.proto = proto;
fullName = computeFullName(file, parent, proto.getName());
this.file = file;

View File

@ -38,6 +38,7 @@ import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Descriptors.OneofDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@ -318,14 +319,14 @@ public final class DynamicMessage extends AbstractMessage {
/** Builder for {@link DynamicMessage}s. */
public static final class Builder extends AbstractMessage.Builder<Builder> {
private final Descriptor type;
private FieldSet<FieldDescriptor> fields;
private FieldSet.Builder<FieldDescriptor> fields;
private final FieldDescriptor[] oneofCases;
private UnknownFieldSet unknownFields;
/** Construct a {@code Builder} for the given type. */
private Builder(Descriptor type) {
this.type = type;
this.fields = FieldSet.newFieldSet();
this.fields = FieldSet.newBuilder();
this.unknownFields = UnknownFieldSet.getDefaultInstance();
this.oneofCases = new FieldDescriptor[type.toProto().getOneofDeclCount()];
}
@ -335,11 +336,7 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public Builder clear() {
if (fields.isImmutable()) {
fields = FieldSet.newFieldSet();
} else {
fields.clear();
}
fields = FieldSet.newBuilder();
unknownFields = UnknownFieldSet.getDefaultInstance();
return this;
}
@ -353,7 +350,6 @@ public final class DynamicMessage extends AbstractMessage {
throw new IllegalArgumentException(
"mergeFrom(Message) can only merge messages of the same type.");
}
ensureIsMutable();
fields.mergeFrom(otherDynamicMessage.fields);
mergeUnknownFields(otherDynamicMessage.unknownFields);
for (int i = 0; i < oneofCases.length; i++) {
@ -378,10 +374,7 @@ public final class DynamicMessage extends AbstractMessage {
if (!isInitialized()) {
throw newUninitializedMessageException(
new DynamicMessage(
type,
fields,
java.util.Arrays.copyOf(oneofCases, oneofCases.length),
unknownFields));
type, fields.build(), Arrays.copyOf(oneofCases, oneofCases.length), unknownFields));
}
return buildPartial();
}
@ -395,8 +388,8 @@ public final class DynamicMessage extends AbstractMessage {
throw newUninitializedMessageException(
new DynamicMessage(
type,
fields,
java.util.Arrays.copyOf(oneofCases, oneofCases.length),
fields.build(),
Arrays.copyOf(oneofCases, oneofCases.length),
unknownFields))
.asInvalidProtocolBufferException();
}
@ -418,17 +411,16 @@ public final class DynamicMessage extends AbstractMessage {
}
}
fields.makeImmutable();
DynamicMessage result =
new DynamicMessage(
type, fields, java.util.Arrays.copyOf(oneofCases, oneofCases.length), unknownFields);
type, fields.build(), Arrays.copyOf(oneofCases, oneofCases.length), unknownFields);
return result;
}
@Override
public Builder clone() {
Builder result = new Builder(type);
result.fields.mergeFrom(fields);
result.fields.mergeFrom(fields.build());
result.mergeUnknownFields(unknownFields);
System.arraycopy(oneofCases, 0, result.oneofCases, 0, oneofCases.length);
return result;
@ -436,7 +428,17 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public boolean isInitialized() {
return DynamicMessage.isInitialized(type, fields);
// Check that all required fields are present.
for (FieldDescriptor field : type.getFields()) {
if (field.isRequired()) {
if (!fields.hasField(field)) {
return false;
}
}
}
// Check that embedded messages are initialized.
return fields.isInitialized();
}
@Override
@ -517,15 +519,12 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public Builder setField(FieldDescriptor field, Object value) {
verifyContainingType(field);
ensureIsMutable();
// TODO(xiaofeng): This check should really be put in FieldSet.setField()
// where all other such checks are done. However, currently
// FieldSet.setField() permits Integer value for enum fields probably
// because of some internal features we support. Should figure it out
// and move this check to a more appropriate place.
if (field.getType() == FieldDescriptor.Type.ENUM) {
ensureEnumValueDescriptor(field, value);
}
verifyType(field, value);
OneofDescriptor oneofDescriptor = field.getContainingOneof();
if (oneofDescriptor != null) {
int index = oneofDescriptor.getIndex();
@ -550,7 +549,6 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public Builder clearField(FieldDescriptor field) {
verifyContainingType(field);
ensureIsMutable();
OneofDescriptor oneofDescriptor = field.getContainingOneof();
if (oneofDescriptor != null) {
int index = oneofDescriptor.getIndex();
@ -577,7 +575,7 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public Builder setRepeatedField(FieldDescriptor field, int index, Object value) {
verifyContainingType(field);
ensureIsMutable();
verifySingularValueType(field, value);
fields.setRepeatedField(field, index, value);
return this;
}
@ -585,7 +583,7 @@ public final class DynamicMessage extends AbstractMessage {
@Override
public Builder addRepeatedField(FieldDescriptor field, Object value) {
verifyContainingType(field);
ensureIsMutable();
verifySingularValueType(field, value);
fields.addRepeatedField(field, value);
return this;
}
@ -622,53 +620,116 @@ public final class DynamicMessage extends AbstractMessage {
}
}
/** Verifies that the value is EnumValueDescriptor and matches Enum Type. */
private void ensureSingularEnumValueDescriptor(FieldDescriptor field, Object value) {
checkNotNull(value);
if (!(value instanceof EnumValueDescriptor)) {
throw new IllegalArgumentException(
"DynamicMessage should use EnumValueDescriptor to set Enum Value.");
/**
* Verifies that {@code value} is of the appropriate type, in addition to the checks already
* performed by {@link FieldSet.Builder}.
*/
private void verifySingularValueType(FieldDescriptor field, Object value) {
// Most type checks are performed by FieldSet.Builder, but FieldSet.Builder is more permissive
// than generated Message.Builder subclasses, so we perform extra checks in this class so that
// DynamicMessage.Builder's semantics more closely match the semantics of generated builders.
switch (field.getType()) {
case ENUM:
checkNotNull(value);
// FieldSet.Builder accepts Integer values for enum fields.
if (!(value instanceof EnumValueDescriptor)) {
throw new IllegalArgumentException(
"DynamicMessage should use EnumValueDescriptor to set Enum Value.");
}
// TODO(xiaofeng): Re-enable this check after Orgstore is fixed to not
// set incorrect EnumValueDescriptors.
// EnumDescriptor fieldType = field.getEnumType();
// EnumDescriptor fieldValueType = ((EnumValueDescriptor) value).getType();
// if (fieldType != fieldValueType) {
// throw new IllegalArgumentException(String.format(
// "EnumDescriptor %s of field doesn't match EnumDescriptor %s of field value",
// fieldType.getFullName(), fieldValueType.getFullName()));
// }
break;
case MESSAGE:
// FieldSet.Builder accepts Message.Builder values for message fields.
if (value instanceof Message.Builder) {
throw new IllegalArgumentException(
String.format(
"Wrong object type used with protocol message reflection.\n"
+ "Field number: %d, field java type: %s, value type: %s\n",
field.getNumber(),
field.getLiteType().getJavaType(),
value.getClass().getName()));
}
break;
default:
break;
}
// TODO(xiaofeng): Re-enable this check after Orgstore is fixed to not
// set incorrect EnumValueDescriptors.
// EnumDescriptor fieldType = field.getEnumType();
// EnumDescriptor fieldValueType = ((EnumValueDescriptor) value).getType();
// if (fieldType != fieldValueType) {
// throw new IllegalArgumentException(String.format(
// "EnumDescriptor %s of field doesn't match EnumDescriptor %s of field value",
// fieldType.getFullName(), fieldValueType.getFullName()));
// }
}
/** Verifies the value for an enum field. */
private void ensureEnumValueDescriptor(FieldDescriptor field, Object value) {
/**
* Verifies that {@code value} is of the appropriate type, in addition to the checks already
* performed by {@link FieldSet.Builder}.
*/
private void verifyType(FieldDescriptor field, Object value) {
if (field.isRepeated()) {
for (Object item : (List) value) {
ensureSingularEnumValueDescriptor(field, item);
for (Object item : (List<?>) value) {
verifySingularValueType(field, item);
}
} else {
ensureSingularEnumValueDescriptor(field, value);
}
}
private void ensureIsMutable() {
if (fields.isImmutable()) {
fields = fields.clone();
verifySingularValueType(field, value);
}
}
@Override
public com.google.protobuf.Message.Builder getFieldBuilder(FieldDescriptor field) {
// TODO(xiangl): need implementation for dynamic message
throw new UnsupportedOperationException(
"getFieldBuilder() called on a dynamic message type.");
verifyContainingType(field);
// Error messages chosen for parity with GeneratedMessage.getFieldBuilder.
if (field.isMapField()) {
throw new UnsupportedOperationException("Nested builder not supported for map fields.");
}
if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
throw new UnsupportedOperationException("getFieldBuilder() called on a non-Message type.");
}
Object existingValue = fields.getFieldAllowBuilders(field);
Message.Builder builder =
existingValue == null
? new Builder(field.getMessageType())
: toMessageBuilder(existingValue);
fields.setField(field, builder);
return builder;
}
@Override
public com.google.protobuf.Message.Builder getRepeatedFieldBuilder(
FieldDescriptor field, int index) {
throw new UnsupportedOperationException(
"getRepeatedFieldBuilder() called on a dynamic message type.");
verifyContainingType(field);
// Error messages chosen for parity with GeneratedMessage.getRepeatedFieldBuilder.
if (field.isMapField()) {
throw new UnsupportedOperationException("Map fields cannot be repeated");
}
if (field.getJavaType() != FieldDescriptor.JavaType.MESSAGE) {
throw new UnsupportedOperationException(
"getRepeatedFieldBuilder() called on a non-Message type.");
}
Message.Builder builder =
toMessageBuilder(fields.getRepeatedFieldAllowBuilders(field, index));
fields.setRepeatedField(field, index, builder);
return builder;
}
private static Message.Builder toMessageBuilder(Object o) {
if (o instanceof Message.Builder) {
return (Message.Builder) o;
}
if (o instanceof LazyField) {
o = ((LazyField) o).getValue();
}
if (o instanceof Message) {
return ((Message) o).toBuilder();
}
throw new IllegalArgumentException(
String.format("Cannot convert %s to Message.Builder", o.getClass()));
}
}
}

View File

@ -154,7 +154,7 @@ public class ExtensionRegistry extends ExtensionRegistryLite {
return mutableExtensionsByName.get(fullName);
}
/** Deprecated. Use {@link #findImmutableExtensionByNumber( Descriptors.Descriptor, int)} */
/** Deprecated. Use {@link #findImmutableExtensionByNumber(Descriptors.Descriptor, int)} */
@Deprecated
public ExtensionInfo findExtensionByNumber(
final Descriptor containingType, final int fieldNumber) {

View File

@ -33,6 +33,7 @@ package com.google.protobuf;
import java.io.IOException;
import java.util.Map;
@CheckReturnValue
abstract class ExtensionSchema<T extends FieldSet.FieldDescriptorLite<T>> {
/** Returns true for messages that support extensions. */

Some files were not shown because too many files have changed in this diff Show More