Compare commits

...

28 Commits

Author SHA1 Message Date
Hong Shin 22a9ebe0c4 rename upb_Message_WhichOneof to upb_Message_WhichOneofByDef
and introduce upb_Message_WhichOneof that returns a minitable field

PiperOrigin-RevId: 631583174
2024-05-09 17:07:08 -07:00
Protobuf Team Bot fefec68753 Internal changes/optimizations
PiperOrigin-RevId: 632294209
2024-05-09 15:54:16 -07:00
Protobuf Team Bot af1ecc0353 Add a check to ensure that the byte limit is not negative.
PiperOrigin-RevId: 632284538
2024-05-09 15:18:31 -07:00
Protobuf Team Bot eb31de3097 Auto-generate files after cl/632277936 2024-05-09 22:09:21 +00:00
Éamonn McManus b5fc2735e9 In `upb_MiniTableExtension_GetSubMessage`, return NULL for non-messages.
This parallels the logic in `upb_MiniTable_SubMessage`.

PiperOrigin-RevId: 632277936
2024-05-09 14:57:53 -07:00
Joshua Haberman 5a91d6fe5e [php] Added a unit test that bad UTF-8 is rejected in the parser.
PiperOrigin-RevId: 632274113
2024-05-09 14:42:05 -07:00
Protobuf Team Bot b51dc1b438 Auto-generate files after cl/632267379 2024-05-09 21:34:06 +00:00
Eric Salo 6245733655 upb: remove the unused (upb_MiniTable*) arg from upb_Message_SetMessage()
PiperOrigin-RevId: 632267379
2024-05-09 14:22:25 -07:00
Sandy Zhang f68350225f Move system_python.bzl to the correct open source folder
PiperOrigin-RevId: 632265705
2024-05-09 14:18:46 -07:00
Jie Luo 495ba7bcdb Nextgen Proto Pythonic API: “Add-on” proto for serialize/parse
- add google.protobuf.proto module
- wrap generated SerializeToString and ParseFromString to the new module:

def serialize(message: Message, deterministic: bool=None) -> bytes:
        """Return the serialized proto."""
def parse(message_class: typing.Type[Message], payload: bytes) -> Message:
        """Given a serialized proto, deserialize it into a Message."""

PiperOrigin-RevId: 632223409
2024-05-09 11:53:56 -07:00
Hong Shin 82e83ddc95 wire_format.cc: Refactor Message and Group handling into a helper func
PiperOrigin-RevId: 632191495
2024-05-09 10:21:36 -07:00
Éamonn McManus 510c1434ed Add `null` to the list of reserved words.
The previous change claimed to do this in addition to `true` and `false`, but it was not actually in the code.

To reiterate the text from the earlier change, now actually reflected entirely in the code:

> The identifiers `true`, `false`, and `null` are effectively reserved words in Java, although for some reason they are listed separately from the "keywords" in the Java Language Specification.
>
> This doesn't matter for regular fields, because a proto field called `true` will be accessed with `getTrue` and `setTrue`. But for extensions, the generated Java code will have a public static field whose name is the same as the name of the extension field, with `_` appended if the name is a reserved word. Previously there was no `_` for `true` etc, so the generated code would not compile.

This change should not affect any existing client code in Java. If someone had tried to use an extension called `true` (etc), they would have found that the generated proto code did not compile. Now it is possible to reference such an extension as `true_`.

PiperOrigin-RevId: 632174190
2024-05-09 09:30:45 -07:00
Protobuf Team Bot dbc2baf5bd Generate extension and k[FieldName]FieldNumber as constexpr int(s).
PiperOrigin-RevId: 632173946
2024-05-09 09:26:57 -07:00
Protobuf Team Bot 13caa08692 Enable textproto conformance tests for "-0" and "-0F".
-0 should be treated as distinct from 0 when deciding it is default valued for implicit presence fields.

PiperOrigin-RevId: 632162352
2024-05-09 08:46:57 -07:00
Protobuf Team Bot 1b06cefe33 Move casting functions to MessageLite and use ClassData as the uniqueness
instead of Reflection. This allows using these functions instead of
`dynamic_cast` for all generated types including LITE.

PiperOrigin-RevId: 632135009
2024-05-09 07:00:26 -07:00
Sandy Zhang 7febb4c48f Move upb/bazel/system_python.bzl (new alias file) to correct open source directory.
PiperOrigin-RevId: 631958564
2024-05-08 16:22:35 -07:00
Protobuf Team Bot b694cfa441 Clarify that the input to proto2::DynamicMessageFactory::GetPrototype should be non-null
PiperOrigin-RevId: 631938646
2024-05-08 15:16:02 -07:00
Protobuf Team Bot ec126a5069 Replace the single user of `PROTOBUF_ALIGNAS` with `alignas` and remove the now
dead macro.
This reduces the compile time cost of port_def.inc

PiperOrigin-RevId: 631886181
2024-05-08 12:27:42 -07:00
Protobuf Team Bot 64580b29c1 Expose JavaPackageDirectory and FileClassName in java/names.h
PiperOrigin-RevId: 631870244
2024-05-08 11:35:56 -07:00
Protobuf Team Bot d5b7d7a87f Remove dead feature macro.
The opt-out code was removed some time ago.

PiperOrigin-RevId: 631826723
2024-05-08 09:30:53 -07:00
Brent Shaffer 01744cccae chore(php): conformance testing for edition (#16712)
COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/16712 from bshaffer:php-editions a1c41add7d
PiperOrigin-RevId: 631824623
2024-05-08 09:23:08 -07:00
Sandy Zhang b77343aa2c Add temporary alias for system_python.bzl at previous location .
This was added to protobuf_deps.bzl in cl/629786458 and no longer needs to be specified directly in WORKSPACE. However, an alias is needed to prevent users from breaking when upgrading from 26.x -> 27.x due to the obsolete load pointing to the wrong path.

This alias will be removed in a future release, tentatively 4.30.x.

PiperOrigin-RevId: 631821637
2024-05-08 09:18:42 -07:00
Protobuf Team Bot d8329b68e4 Add .to_owned(&self)->Msg functions to MsgMut and MsgView
PiperOrigin-RevId: 631686314
2024-05-08 00:54:28 -07:00
Protobuf Team Bot 6afb130dca Auto-generate files after cl/631620526 2024-05-08 02:19:22 +00:00
Eric Salo d923896299 upb: implement most of the non-universal setters
PiperOrigin-RevId: 631620526
2024-05-07 19:07:33 -07:00
Protobuf Team Bot 4d3a98c27e Auto-generate files after cl/631612923 2024-05-08 01:37:14 +00:00
Eric Salo 65821a67d6 upb: finish cleaning up message/accessors.h and message/internal/accessors.h
PiperOrigin-RevId: 631612923
2024-05-07 18:25:25 -07:00
Éamonn McManus 98d5bdd111 Add "reserved literals" to the list of reserved names for Java.
The identifiers `true`, `false`, and `null` are effectively reserved words in Java, although for some reason they are listed separately from the "keywords" in the Java Language Specification.

This doesn't matter for regular fields, because a proto field called `true` will be accessed with `getTrue` and `setTrue`. But for extensions, the generated Java code will have a public static field whose name is the same as the name of the extension field, with `_` appended if the name is a reserved word. Previously there was no `_` for `true` etc, so the generated code would not compile.

PiperOrigin-RevId: 631599695
2024-05-07 17:23:09 -07:00
63 changed files with 2048 additions and 1138 deletions

17
bazel/system_python.bzl Normal file
View File

@ -0,0 +1,17 @@
# Copyright (c) 2009-2021, Google LLC
# All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Temporary alias to repository rule for using Python 3.x headers from the system."""
load(
"//python/dist:system_python.bzl",
_system_python = "system_python",
)
# TODO: Temporary alias. This is deprecated and to be removed in a future
# release. Users should now get system_python from protobuf_deps.bzl.
system_python = _system_python

View File

@ -332,13 +332,14 @@ inline_sh_binary(
],
cmd = """
php -dextension=$(rootpath //php:extension) \\
-d include_path=conformance:src/google/protobuf \\
-d include_path=conformance:src/google/protobuf:editions/golden \\
$(rootpath conformance_php.php)
""",
visibility = ["//php:__subpackages__"],
deps = [
":conformance_php_proto",
"//:test_messages_proto3_php_proto",
"//editions:test_messages_proto3_editions_php_proto",
],
)

View File

@ -1,80 +1,134 @@
<?php
require_once("Conformance/WireFormat.php");
require_once("Conformance/ConformanceResponse.php");
require_once("Conformance/ConformanceRequest.php");
require_once("Conformance/FailureSet.php");
require_once("Conformance/JspbEncodingConfig.php");
require_once("Conformance/TestCategory.php");
require_once("Protobuf_test_messages/Proto3/ForeignMessage.php");
require_once("Protobuf_test_messages/Proto3/ForeignEnum.php");
require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3.php");
require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3/AliasedEnum.php");
require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3/NestedMessage.php");
require_once("Protobuf_test_messages/Proto3/TestAllTypesProto3/NestedEnum.php");
require_once('Conformance/WireFormat.php');
require_once('Conformance/ConformanceResponse.php');
require_once('Conformance/ConformanceRequest.php');
require_once('Conformance/FailureSet.php');
require_once('Conformance/JspbEncodingConfig.php');
require_once('Conformance/TestCategory.php');
require_once('Protobuf_test_messages/Proto3/ForeignMessage.php');
require_once('Protobuf_test_messages/Proto3/ForeignEnum.php');
require_once('Protobuf_test_messages/Proto3/TestAllTypesProto3.php');
require_once('Protobuf_test_messages/Proto3/TestAllTypesProto3/AliasedEnum.php');
require_once('Protobuf_test_messages/Proto3/TestAllTypesProto3/NestedMessage.php');
require_once('Protobuf_test_messages/Proto3/TestAllTypesProto3/NestedEnum.php');
require_once('Protobuf_test_messages/Editions/Proto3/EnumOnlyProto3/PBBool.php');
require_once('Protobuf_test_messages/Editions/Proto3/EnumOnlyProto3.php');
require_once('Protobuf_test_messages/Editions/Proto3/TestAllTypesProto3/NestedMessage.php');
require_once('Protobuf_test_messages/Editions/Proto3/TestAllTypesProto3/NestedEnum.php');
require_once('Protobuf_test_messages/Editions/Proto3/TestAllTypesProto3/AliasedEnum.php');
require_once('Protobuf_test_messages/Editions/Proto3/TestAllTypesProto3.php');
require_once('Protobuf_test_messages/Editions/Proto3/NullHypothesisProto3.php');
require_once('Protobuf_test_messages/Editions/Proto3/ForeignEnum.php');
require_once('Protobuf_test_messages/Editions/Proto3/ForeignMessage.php');
require_once('GPBMetadata/Conformance.php');
require_once('GPBMetadata/TestMessagesProto3.php');
require_once('GPBMetadata/TestMessagesProto3Editions.php');
require_once("GPBMetadata/Conformance.php");
require_once("GPBMetadata/TestMessagesProto3.php");
use Conformance\ConformanceRequest;
use Conformance\ConformanceResponse;
use Conformance\TestCategory;
use Conformance\WireFormat;
use Protobuf_test_messages\Proto3\TestAllTypesProto3;
use Protobuf_test_messages\Editions\Proto3\TestAllTypesProto3 as TestAllTypesProto3Editions;
use \Conformance\TestCategory;
use \Conformance\WireFormat;
if (!ini_get("date.timezone")) {
ini_set("date.timezone", "UTC");
if (!ini_get('date.timezone')) {
ini_set('date.timezone', 'UTC');
}
$test_count = 0;
function doTest($request)
{
$test_message = new \Protobuf_test_messages\Proto3\TestAllTypesProto3();
$response = new \Conformance\ConformanceResponse();
if ($request->getPayload() == "protobuf_payload") {
if ($request->getMessageType() == "conformance.FailureSet") {
$response->setProtobufPayload("");
return $response;
} elseif ($request->getMessageType() == "protobuf_test_messages.proto3.TestAllTypesProto3") {
try {
$test_message->mergeFromString($request->getProtobufPayload());
} catch (Exception $e) {
$response->setParseError($e->getMessage());
return $response;
}
} elseif ($request->getMessageType() == "protobuf_test_messages.proto2.TestAllTypesProto2") {
$response->setSkipped("PHP doesn't support proto2");
return $response;
} else {
trigger_error("Protobuf request doesn't have specific payload type", E_USER_ERROR);
}
} elseif ($request->getPayload() == "json_payload") {
$ignore_json_unknown =
($request->getTestCategory() ==
TestCategory::JSON_IGNORE_UNKNOWN_PARSING_TEST);
try {
$test_message->mergeFromJsonString($request->getJsonPayload(),
$ignore_json_unknown);
} catch (Exception $e) {
$response->setParseError($e->getMessage());
return $response;
}
} elseif ($request->getPayload() == "text_payload") {
$response->setSkipped("PHP doesn't support text format yet");
return $response;
} else {
trigger_error("Request didn't have payload.", E_USER_ERROR);
$response = new ConformanceResponse();
switch ($request->getPayload()) {
case 'protobuf_payload':
switch ($request->getMessageType()) {
case 'protobuf_test_messages.proto3.TestAllTypesProto3':
$test_message = new TestAllTypesProto3();
break;
case 'protobuf_test_messages.editions.proto3.TestAllTypesProto3':
$test_message = new TestAllTypesProto3Editions();
break;
case 'conformance.FailureSet':
$response->setProtobufPayload('');
return $response;
case 'protobuf_test_messages.proto2.TestAllTypesProto2':
case 'protobuf_test_messages.editions.proto2.TestAllTypesProto2':
$response->setSkipped('PHP doesn\'t support proto2');
return $response;
case 'protobuf_test_messages.editions.TestAllTypesEdition2023':
$response->setSkipped('PHP doesn\'t support editions-specific features yet');
return $response;
case '':
trigger_error(
'Protobuf request doesn\'t have specific payload type',
E_USER_ERROR
);
default:
trigger_error(sprintf(
'Protobuf request doesn\'t support %s message type',
$request->getMessageType(),
), E_USER_ERROR);
}
try {
$test_message->mergeFromString($request->getProtobufPayload());
} catch (Exception $e) {
$response->setParseError($e->getMessage());
return $response;
}
break;
case 'json_payload':
switch ($request->getMessageType()) {
case 'protobuf_test_messages.editions.proto3.TestAllTypesProto3':
$test_message = new TestAllTypesProto3Editions();
break;
case 'protobuf_test_messages.editions.proto2.TestAllTypesProto2':
$response->setSkipped('PHP doesn\'t support proto2');
return $response;
default:
$test_message = new TestAllTypesProto3();
}
$ignore_json_unknown =
($request->getTestCategory() == TestCategory::JSON_IGNORE_UNKNOWN_PARSING_TEST);
try {
$test_message->mergeFromJsonString(
$request->getJsonPayload(),
$ignore_json_unknown
);
} catch (Exception $e) {
$response->setParseError($e->getMessage());
return $response;
}
break;
case 'text_payload':
$response->setSkipped('PHP doesn\'t support text format yet');
return $response;
default:
trigger_error('Request didn\'t have payload.', E_USER_ERROR);
}
if ($request->getRequestedOutputFormat() == WireFormat::UNSPECIFIED) {
trigger_error("Unspecified output format.", E_USER_ERROR);
} elseif ($request->getRequestedOutputFormat() == WireFormat::PROTOBUF) {
$response->setProtobufPayload($test_message->serializeToString());
} elseif ($request->getRequestedOutputFormat() == WireFormat::JSON) {
try {
$response->setJsonPayload($test_message->serializeToJsonString());
} catch (Exception $e) {
$response->setSerializeError($e->getMessage());
return $response;
}
switch ($request->getRequestedOutputFormat()) {
case WireFormat::TEXT_FORMAT:
$response->setSkipped('PHP doesn\'t support text format yet');
return $response;
case WireFormat::UNSPECIFIED:
trigger_error('Unspecified output format.', E_USER_ERROR);
case WireFormat::PROTOBUF:
$response->setProtobufPayload($test_message->serializeToString());
break;
case WireFormat::JSON:
try {
$response->setJsonPayload($test_message->serializeToJsonString());
} catch (Exception $e) {
$response->setSerializeError($e->getMessage());
return $response;
}
}
return $response;
@ -84,25 +138,25 @@ function doTestIO()
{
$length_bytes = fread(STDIN, 4);
if (strlen($length_bytes) == 0) {
return false; # EOF
return false; # EOF
} elseif (strlen($length_bytes) != 4) {
fwrite(STDERR, "I/O error\n");
return false;
fwrite(STDERR, "I/O error\n");
return false;
}
$length = unpack("V", $length_bytes)[1];
$length = unpack('V', $length_bytes)[1];
$serialized_request = fread(STDIN, $length);
if (strlen($serialized_request) != $length) {
trigger_error("I/O error", E_USER_ERROR);
trigger_error('I/O error', E_USER_ERROR);
}
$request = new \Conformance\ConformanceRequest();
$request = new ConformanceRequest();
$request->mergeFromString($serialized_request);
$response = doTest($request);
$serialized_response = $response->serializeToString();
fwrite(STDOUT, pack("V", strlen($serialized_response)));
fwrite(STDOUT, pack('V', strlen($serialized_response)));
fwrite(STDOUT, $serialized_response);
$GLOBALS['test_count'] += 1;
@ -111,10 +165,10 @@ function doTestIO()
}
while(true){
if (!doTestIO()) {
fprintf(STDERR,
"conformance_php: received EOF from test runner " .
"after %d tests, exiting\n", $test_count);
exit;
}
if (!doTestIO()) {
fprintf(STDERR,
'conformance_php: received EOF from test runner ' .
"after %d tests, exiting\n", $test_count);
exit;
}
}

View File

@ -440,13 +440,11 @@ void TextFormatConformanceTestSuiteImpl<MessageType>::RunAllTests() {
absl::StrCat("FloatFieldLargerThanUint64", name_suffix), REQUIRED,
absl::StrCat("optional_float: 18446744073709551616", suffix));
// https://protobuf.dev/reference/protobuf/textformat-spec/#literals says
// "-0" is a valid float literal.
// TODO: Figure out if this should count as not setting
// presence or if -0 should be reflected back.
// RunValidTextFormatTestWithExpected(
// absl::StrCat("FloatFieldNegativeZero", name_suffix), REQUIRED,
// absl::StrCat("optional_float: -0", suffix),
// "" /* implicit presence, so zero means unset*/);
// "-0" is a valid float literal. -0 should be considered not the same as 0
// when considering implicit presence, and so should round trip.
RunValidTextFormatTest(absl::StrCat("FloatFieldNegativeZero", name_suffix),
REQUIRED,
absl::StrCat("optional_float: -0", suffix));
// https://protobuf.dev/reference/protobuf/textformat-spec/#literals says
// ".123", "-.123", ".123e2" are a valid float literal.
RunValidTextFormatTest(absl::StrCat("FloatFieldNoLeadingZero", name_suffix),
@ -502,6 +500,19 @@ void TextFormatConformanceTestSuiteImpl<MessageType>::RunAllTests() {
RunValidTextFormatTestWithExpected(
"DoubleFieldOverflowInfinityHugeExponent", REQUIRED,
"optional_double: 1e18446744073709551616", "optional_double: inf");
RunValidTextFormatTestWithExpected(
"DoubleFieldLargeNegativeExponentParsesAsZero", REQUIRED,
"optional_double: 1e-18446744073709551616", "");
RunValidTextFormatTestWithExpected(
"NegDoubleFieldLargeNegativeExponentParsesAsNegZero", REQUIRED,
"optional_double: -1e-18446744073709551616", "optional_double: -0");
RunValidTextFormatTestWithExpected(
"FloatFieldLargeNegativeExponentParsesAsZero", REQUIRED,
"optional_float: 1e-50", "");
RunValidTextFormatTestWithExpected(
"NegFloatFieldLargeNegativeExponentParsesAsNegZero", REQUIRED,
"optional_float: -1e-50", "optional_float: -0");
// String literals x {Strings, Bytes}
for (const auto& field_type : std::vector<std::string>{"String", "Bytes"}) {

View File

@ -1,8 +0,0 @@
Recommended.Proto3.ProtobufInput.GroupUnknownFields_Drop.TextFormatOutput
Recommended.Proto3.ProtobufInput.GroupUnknownFields_Print.TextFormatOutput
Recommended.Proto3.ProtobufInput.MessageUnknownFields_Drop.TextFormatOutput
Recommended.Proto3.ProtobufInput.MessageUnknownFields_Print.TextFormatOutput
Recommended.Proto3.ProtobufInput.RepeatedUnknownFields_Drop.TextFormatOutput
Recommended.Proto3.ProtobufInput.RepeatedUnknownFields_Print.TextFormatOutput
Recommended.Proto3.ProtobufInput.ScalarUnknownFields_Drop.TextFormatOutput
Recommended.Proto3.ProtobufInput.ScalarUnknownFields_Print.TextFormatOutput

View File

@ -77,3 +77,23 @@ Required.Proto3.TextFormatInput.StringLiteralBasicEscapesBytes.ProtobufOutput
Required.Proto3.TextFormatInput.StringLiteralBasicEscapesBytes.TextFormatOutput
Required.Proto3.TextFormatInput.StringLiteralBasicEscapesString.ProtobufOutput
Required.Proto3.TextFormatInput.StringLiteralBasicEscapesString.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero_F.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero_F.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero_f.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero_f.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.NegDoubleFieldLargeNegativeExponentParsesAsNegZero.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.NegDoubleFieldLargeNegativeExponentParsesAsNegZero.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.NegFloatFieldLargeNegativeExponentParsesAsNegZero.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.NegFloatFieldLargeNegativeExponentParsesAsNegZero.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero_F.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero_F.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero_f.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero_f.TextFormatOutput
Required.Proto3.TextFormatInput.NegDoubleFieldLargeNegativeExponentParsesAsNegZero.ProtobufOutput
Required.Proto3.TextFormatInput.NegDoubleFieldLargeNegativeExponentParsesAsNegZero.TextFormatOutput
Required.Proto3.TextFormatInput.NegFloatFieldLargeNegativeExponentParsesAsNegZero.ProtobufOutput
Required.Proto3.TextFormatInput.NegFloatFieldLargeNegativeExponentParsesAsNegZero.TextFormatOutput

View File

@ -28,6 +28,8 @@ Required.Editions_Proto3.TextFormatInput.FloatFieldWithVeryPreciseNumber_F.Proto
Required.Editions_Proto3.TextFormatInput.FloatFieldWithVeryPreciseNumber_F.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldZero_F.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldZero_F.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero_F.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero_F.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.StringLiteralBasicEscapesBytes.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.StringLiteralBasicEscapesBytes.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.StringLiteralBasicEscapesString.ProtobufOutput
@ -62,6 +64,8 @@ Required.Proto3.TextFormatInput.FloatFieldWithVeryPreciseNumber_F.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldWithVeryPreciseNumber_F.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldZero_F.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldZero_F.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero_F.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero_F.TextFormatOutput
Required.Proto3.TextFormatInput.StringLiteralBasicEscapesBytes.ProtobufOutput
Required.Proto3.TextFormatInput.StringLiteralBasicEscapesBytes.TextFormatOutput
Required.Proto3.TextFormatInput.StringLiteralBasicEscapesString.ProtobufOutput

View File

@ -15,6 +15,8 @@ Required.Editions_Proto3.TextFormatInput.FloatFieldNegative_F.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegative_F.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeNoLeadingZero_F.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeNoLeadingZero_F.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero_F.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNegativeZero_F.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNoLeadingZero_F.ProtobufOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNoLeadingZero_F.TextFormatOutput
Required.Editions_Proto3.TextFormatInput.FloatFieldNoLeadingZeroWithExponent_F.ProtobufOutput
@ -49,6 +51,8 @@ Required.Proto3.TextFormatInput.FloatFieldNegative_F.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldNegative_F.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeNoLeadingZero_F.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeNoLeadingZero_F.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero_F.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldNegativeZero_F.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldNoLeadingZero_F.ProtobufOutput
Required.Proto3.TextFormatInput.FloatFieldNoLeadingZero_F.TextFormatOutput
Required.Proto3.TextFormatInput.FloatFieldNoLeadingZeroWithExponent_F.ProtobufOutput

View File

@ -1,5 +1,5 @@
load("@bazel_skylib//:bzl_library.bzl", "bzl_library")
load("//:protobuf.bzl", "internal_objc_proto_library", "internal_py_proto_library")
load("//:protobuf.bzl", "internal_objc_proto_library", "internal_php_proto_library", "internal_py_proto_library")
load("//bazel:cc_proto_library.bzl", "cc_proto_library")
load("//bazel:upb_proto_library.bzl", "upb_c_proto_library", "upb_proto_reflection_library")
load(":defaults.bzl", "compile_edition_defaults", "embed_edition_defaults")
@ -236,6 +236,31 @@ java_lite_proto_library(
deps = [":test_messages_proto3_editions_proto"],
)
internal_php_proto_library(
name = "test_messages_proto3_editions_php_proto",
testonly = 1,
srcs = ["golden/test_messages_proto3_editions.proto"],
outs = [
"GPBMetadata/TestMessagesProto3Editions.php",
"Protobuf_test_messages/Editions/Proto3/EnumOnlyProto3.php",
"Protobuf_test_messages/Editions/Proto3/EnumOnlyProto3/PBBool.php",
"Protobuf_test_messages/Editions/Proto3/ForeignEnum.php",
"Protobuf_test_messages/Editions/Proto3/ForeignMessage.php",
"Protobuf_test_messages/Editions/Proto3/NullHypothesisProto3.php",
"Protobuf_test_messages/Editions/Proto3/TestAllTypesProto3.php",
"Protobuf_test_messages/Editions/Proto3/TestAllTypesProto3/AliasedEnum.php",
"Protobuf_test_messages/Editions/Proto3/TestAllTypesProto3/NestedEnum.php",
"Protobuf_test_messages/Editions/Proto3/TestAllTypesProto3/NestedMessage.php",
],
enable_editions = True,
includes = [
"golden",
"src",
],
proto_deps = ["//:well_known_protos"],
visibility = ["//conformance:__pkg__"],
)
internal_py_proto_library(
name = "test_messages_proto3_editions_py_pb2",
testonly = True,

View File

@ -60,6 +60,8 @@ LITE_SRCS = [
"src/main/java/com/google/protobuf/LazyStringArrayList.java",
"src/main/java/com/google/protobuf/LazyStringList.java",
"src/main/java/com/google/protobuf/ListFieldSchema.java",
"src/main/java/com/google/protobuf/ListFieldSchemaLite.java",
"src/main/java/com/google/protobuf/ListFieldSchemas.java",
"src/main/java/com/google/protobuf/LongArrayList.java",
"src/main/java/com/google/protobuf/ManifestSchemaFactory.java",
"src/main/java/com/google/protobuf/MapEntryLite.java",

View File

@ -2690,6 +2690,9 @@ public abstract class CodedInputStream {
throw InvalidProtocolBufferException.negativeSize();
}
byteLimit += totalBytesRetired + pos;
if (byteLimit < 0) {
throw InvalidProtocolBufferException.parseFailure();
}
final int oldLimit = currentLimit;
if (byteLimit > oldLimit) {
throw InvalidProtocolBufferException.truncatedMessage();

View File

@ -31,4 +31,6 @@ final class ExtensionSchemas {
}
return FULL_SCHEMA;
}
private ExtensionSchemas() {}
}

View File

@ -7,162 +7,17 @@
package com.google.protobuf;
import com.google.protobuf.Internal.ProtobufList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Utility class that aids in properly manipulating list fields for either the lite or full runtime.
*/
@CheckReturnValue
abstract class ListFieldSchema {
// Disallow construction.
private ListFieldSchema() {}
interface ListFieldSchema {
private static final ListFieldSchema FULL_INSTANCE = new ListFieldSchemaFull();
private static final ListFieldSchema LITE_INSTANCE = new ListFieldSchemaLite();
<L> List<L> mutableListAt(Object msg, long offset);
abstract <L> List<L> mutableListAt(Object msg, long offset);
void makeImmutableListAt(Object msg, long offset);
abstract void makeImmutableListAt(Object msg, long offset);
abstract <L> void mergeListsAt(Object msg, Object otherMsg, long offset);
static ListFieldSchema full() {
return FULL_INSTANCE;
}
static ListFieldSchema lite() {
return LITE_INSTANCE;
}
/** Implementation for the full runtime. */
private static final class ListFieldSchemaFull extends ListFieldSchema {
private static final Class<?> UNMODIFIABLE_LIST_CLASS =
Collections.unmodifiableList(Collections.emptyList()).getClass();
@Override
<L> List<L> mutableListAt(Object message, long offset) {
return mutableListAt(message, offset, AbstractProtobufList.DEFAULT_CAPACITY);
}
@Override
void makeImmutableListAt(Object message, long offset) {
List<?> list = (List<?>) UnsafeUtil.getObject(message, offset);
Object immutable = null;
if (list instanceof LazyStringList) {
immutable = ((LazyStringList) list).getUnmodifiableView();
} else if (UNMODIFIABLE_LIST_CLASS.isAssignableFrom(list.getClass())) {
// already immutable
return;
} else if (list instanceof PrimitiveNonBoxingCollection && list instanceof ProtobufList) {
if (((ProtobufList<?>) list).isModifiable()) {
((ProtobufList<?>) list).makeImmutable();
}
return;
} else {
immutable = Collections.unmodifiableList((List<?>) list);
}
UnsafeUtil.putObject(message, offset, immutable);
}
@SuppressWarnings("unchecked")
private static <L> List<L> mutableListAt(Object message, long offset, int additionalCapacity) {
List<L> list = getList(message, offset);
if (list.isEmpty()) {
if (list instanceof LazyStringList) {
list = (List<L>) new LazyStringArrayList(additionalCapacity);
} else if (list instanceof PrimitiveNonBoxingCollection && list instanceof ProtobufList) {
list = ((ProtobufList<L>) list).mutableCopyWithCapacity(additionalCapacity);
} else {
list = new ArrayList<L>(additionalCapacity);
}
UnsafeUtil.putObject(message, offset, list);
} else if (UNMODIFIABLE_LIST_CLASS.isAssignableFrom(list.getClass())) {
ArrayList<L> newList = new ArrayList<L>(list.size() + additionalCapacity);
newList.addAll(list);
list = newList;
UnsafeUtil.putObject(message, offset, list);
} else if (list instanceof UnmodifiableLazyStringList) {
LazyStringArrayList newList = new LazyStringArrayList(list.size() + additionalCapacity);
newList.addAll((UnmodifiableLazyStringList) list);
list = (List<L>) newList;
UnsafeUtil.putObject(message, offset, list);
} else if (list instanceof PrimitiveNonBoxingCollection
&& list instanceof ProtobufList
&& !((ProtobufList<L>) list).isModifiable()) {
list = ((ProtobufList<L>) list).mutableCopyWithCapacity(list.size() + additionalCapacity);
UnsafeUtil.putObject(message, offset, list);
}
return list;
}
@Override
<E> void mergeListsAt(Object msg, Object otherMsg, long offset) {
List<E> other = getList(otherMsg, offset);
List<E> mine = mutableListAt(msg, offset, other.size());
int size = mine.size();
int otherSize = other.size();
if (size > 0 && otherSize > 0) {
mine.addAll(other);
}
List<E> merged = size > 0 ? mine : other;
UnsafeUtil.putObject(msg, offset, merged);
}
@SuppressWarnings("unchecked")
static <E> List<E> getList(Object message, long offset) {
return (List<E>) UnsafeUtil.getObject(message, offset);
}
}
/** Implementation for the lite runtime. */
private static final class ListFieldSchemaLite extends ListFieldSchema {
@Override
<L> List<L> mutableListAt(Object message, long offset) {
ProtobufList<L> list = getProtobufList(message, offset);
if (!list.isModifiable()) {
int size = list.size();
list =
list.mutableCopyWithCapacity(
size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
UnsafeUtil.putObject(message, offset, list);
}
return list;
}
@Override
void makeImmutableListAt(Object message, long offset) {
ProtobufList<?> list = getProtobufList(message, offset);
list.makeImmutable();
}
@Override
<E> void mergeListsAt(Object msg, Object otherMsg, long offset) {
ProtobufList<E> mine = getProtobufList(msg, offset);
ProtobufList<E> other = getProtobufList(otherMsg, offset);
int size = mine.size();
int otherSize = other.size();
if (size > 0 && otherSize > 0) {
if (!mine.isModifiable()) {
mine = mine.mutableCopyWithCapacity(size + otherSize);
}
mine.addAll(other);
}
ProtobufList<E> merged = size > 0 ? mine : other;
UnsafeUtil.putObject(msg, offset, merged);
}
@SuppressWarnings("unchecked")
static <E> ProtobufList<E> getProtobufList(Object message, long offset) {
return (ProtobufList<E>) UnsafeUtil.getObject(message, offset);
}
}
<L> void mergeListsAt(Object msg, Object otherMsg, long offset);
}

View File

@ -0,0 +1,99 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import com.google.protobuf.Internal.ProtobufList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Utility class that aids in properly manipulating list fields for either the lite or full runtime.
*/
@CheckReturnValue
final class ListFieldSchemaFull implements ListFieldSchema {
private static final Class<?> UNMODIFIABLE_LIST_CLASS =
Collections.unmodifiableList(Collections.emptyList()).getClass();
@Override
public <L> List<L> mutableListAt(Object message, long offset) {
return mutableListAt(message, offset, AbstractProtobufList.DEFAULT_CAPACITY);
}
@SuppressWarnings("unchecked")
private static <L> List<L> mutableListAt(Object message, long offset, int additionalCapacity) {
List<L> list = getList(message, offset);
if (list.isEmpty()) {
if (list instanceof LazyStringList) {
list = (List<L>) new LazyStringArrayList(additionalCapacity);
} else if (list instanceof PrimitiveNonBoxingCollection && list instanceof ProtobufList) {
list = ((ProtobufList<L>) list).mutableCopyWithCapacity(additionalCapacity);
} else {
list = new ArrayList<L>(additionalCapacity);
}
UnsafeUtil.putObject(message, offset, list);
} else if (UNMODIFIABLE_LIST_CLASS.isAssignableFrom(list.getClass())) {
ArrayList<L> newList = new ArrayList<L>(list.size() + additionalCapacity);
newList.addAll(list);
list = newList;
UnsafeUtil.putObject(message, offset, list);
} else if (list instanceof UnmodifiableLazyStringList) {
LazyStringArrayList newList = new LazyStringArrayList(list.size() + additionalCapacity);
newList.addAll((UnmodifiableLazyStringList) list);
list = (List<L>) newList;
UnsafeUtil.putObject(message, offset, list);
} else if (list instanceof PrimitiveNonBoxingCollection
&& list instanceof ProtobufList
&& !((ProtobufList<L>) list).isModifiable()) {
list = ((ProtobufList<L>) list).mutableCopyWithCapacity(list.size() + additionalCapacity);
UnsafeUtil.putObject(message, offset, list);
}
return list;
}
@Override
public void makeImmutableListAt(Object message, long offset) {
List<?> list = (List<?>) UnsafeUtil.getObject(message, offset);
Object immutable = null;
if (list instanceof LazyStringList) {
immutable = ((LazyStringList) list).getUnmodifiableView();
} else if (UNMODIFIABLE_LIST_CLASS.isAssignableFrom(list.getClass())) {
// already immutable
return;
} else if (list instanceof PrimitiveNonBoxingCollection && list instanceof ProtobufList) {
if (((ProtobufList<?>) list).isModifiable()) {
((ProtobufList<?>) list).makeImmutable();
}
return;
} else {
immutable = Collections.unmodifiableList((List<?>) list);
}
UnsafeUtil.putObject(message, offset, immutable);
}
@Override
public <E> void mergeListsAt(Object msg, Object otherMsg, long offset) {
List<E> other = getList(otherMsg, offset);
List<E> mine = mutableListAt(msg, offset, other.size());
int size = mine.size();
int otherSize = other.size();
if (size > 0 && otherSize > 0) {
mine.addAll(other);
}
List<E> merged = size > 0 ? mine : other;
UnsafeUtil.putObject(msg, offset, merged);
}
@SuppressWarnings("unchecked")
static <E> List<E> getList(Object message, long offset) {
return (List<E>) UnsafeUtil.getObject(message, offset);
}
}

View File

@ -0,0 +1,59 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import com.google.protobuf.Internal.ProtobufList;
import java.util.List;
/**
* Utility class that aids in properly manipulating list fields for either the lite or full runtime.
*/
final class ListFieldSchemaLite implements ListFieldSchema {
@Override
public <L> List<L> mutableListAt(Object message, long offset) {
ProtobufList<L> list = getProtobufList(message, offset);
if (!list.isModifiable()) {
int size = list.size();
list =
list.mutableCopyWithCapacity(
size == 0 ? AbstractProtobufList.DEFAULT_CAPACITY : size * 2);
UnsafeUtil.putObject(message, offset, list);
}
return list;
}
@Override
public void makeImmutableListAt(Object message, long offset) {
ProtobufList<?> list = getProtobufList(message, offset);
list.makeImmutable();
}
@Override
public <E> void mergeListsAt(Object msg, Object otherMsg, long offset) {
ProtobufList<E> mine = getProtobufList(msg, offset);
ProtobufList<E> other = getProtobufList(otherMsg, offset);
int size = mine.size();
int otherSize = other.size();
if (size > 0 && otherSize > 0) {
if (!mine.isModifiable()) {
mine = mine.mutableCopyWithCapacity(size + otherSize);
}
mine.addAll(other);
}
ProtobufList<E> merged = size > 0 ? mine : other;
UnsafeUtil.putObject(msg, offset, merged);
}
@SuppressWarnings("unchecked")
static <E> ProtobufList<E> getProtobufList(Object message, long offset) {
return (ProtobufList<E>) UnsafeUtil.getObject(message, offset);
}
}

View File

@ -0,0 +1,33 @@
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
@CheckReturnValue
final class ListFieldSchemas {
private static final ListFieldSchema FULL_SCHEMA = loadSchemaForFullRuntime();
private static final ListFieldSchema LITE_SCHEMA = new ListFieldSchemaLite();
static ListFieldSchema full() {
return FULL_SCHEMA;
}
static ListFieldSchema lite() {
return LITE_SCHEMA;
}
private static ListFieldSchema loadSchemaForFullRuntime() {
try {
Class<?> clazz = Class.forName("com.google.protobuf.ListFieldSchemaFull");
return (ListFieldSchema) clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
return null;
}
}
private ListFieldSchemas() {}
}

View File

@ -34,57 +34,37 @@ final class ManifestSchemaFactory implements SchemaFactory {
// MessageSet has a special schema.
if (messageInfo.isMessageSetWireFormat()) {
if (GeneratedMessageLite.class.isAssignableFrom(messageType)) {
return MessageSetSchema.newSchema(
SchemaUtil.unknownFieldSetLiteSchema(),
ExtensionSchemas.lite(),
messageInfo.getDefaultInstance());
}
return MessageSetSchema.newSchema(
SchemaUtil.unknownFieldSetFullSchema(),
ExtensionSchemas.full(),
messageInfo.getDefaultInstance());
return useLiteRuntime(messageType)
? MessageSetSchema.newSchema(
SchemaUtil.unknownFieldSetLiteSchema(),
ExtensionSchemas.lite(),
messageInfo.getDefaultInstance())
: MessageSetSchema.newSchema(
SchemaUtil.unknownFieldSetFullSchema(),
ExtensionSchemas.full(),
messageInfo.getDefaultInstance());
}
return newSchema(messageType, messageInfo);
}
private static <T> Schema<T> newSchema(Class<T> messageType, MessageInfo messageInfo) {
if (GeneratedMessageLite.class.isAssignableFrom(messageType)) {
return allowExtensions(messageInfo)
? MessageSchema.newSchema(
messageType,
messageInfo,
NewInstanceSchemas.lite(),
ListFieldSchema.lite(),
SchemaUtil.unknownFieldSetLiteSchema(),
ExtensionSchemas.lite(),
MapFieldSchemas.lite())
: MessageSchema.newSchema(
messageType,
messageInfo,
NewInstanceSchemas.lite(),
ListFieldSchema.lite(),
SchemaUtil.unknownFieldSetLiteSchema(),
/* extensionSchema= */ null,
MapFieldSchemas.lite());
}
return allowExtensions(messageInfo)
return useLiteRuntime(messageType)
? MessageSchema.newSchema(
messageType,
messageInfo,
NewInstanceSchemas.full(),
ListFieldSchema.full(),
SchemaUtil.unknownFieldSetFullSchema(),
ExtensionSchemas.full(),
MapFieldSchemas.full())
NewInstanceSchemas.lite(),
ListFieldSchemas.lite(),
SchemaUtil.unknownFieldSetLiteSchema(),
allowExtensions(messageInfo) ? ExtensionSchemas.lite() : null,
MapFieldSchemas.lite())
: MessageSchema.newSchema(
messageType,
messageInfo,
NewInstanceSchemas.full(),
ListFieldSchema.full(),
ListFieldSchemas.full(),
SchemaUtil.unknownFieldSetFullSchema(),
/* extensionSchema= */ null,
allowExtensions(messageInfo) ? ExtensionSchemas.full() : null,
MapFieldSchemas.full());
}
@ -152,4 +132,8 @@ final class ManifestSchemaFactory implements SchemaFactory {
return EMPTY_FACTORY;
}
}
private static boolean useLiteRuntime(Class<?> messageType) {
return GeneratedMessageLite.class.isAssignableFrom(messageType);
}
}

View File

@ -10,7 +10,7 @@ package com.google.protobuf;
import com.google.protobuf.MapEntryLite.Metadata;
import java.util.Map;
class MapFieldSchemaFull implements MapFieldSchema {
final class MapFieldSchemaFull implements MapFieldSchema {
@Override
public Map<?, ?> forMutableMapData(Object mapField) {
return ((MapField<?, ?>) mapField).getMutableMap();

View File

@ -11,7 +11,7 @@ import com.google.protobuf.MapEntryLite.Metadata;
import java.util.Map;
@CheckReturnValue
class MapFieldSchemaLite implements MapFieldSchema {
final class MapFieldSchemaLite implements MapFieldSchema {
@Override
public Map<?, ?> forMutableMapData(Object mapField) {

View File

@ -28,4 +28,6 @@ final class MapFieldSchemas {
return null;
}
}
private MapFieldSchemas() {}
}

View File

@ -28,4 +28,6 @@ final class NewInstanceSchemas {
return null;
}
}
private NewInstanceSchemas() {}
}

View File

@ -139,6 +139,8 @@
<include>LazyStringArrayList.java</include>
<include>LazyStringList.java</include>
<include>ListFieldSchema.java</include>
<include>ListFieldSchemaLite.java</include>
<include>ListFieldSchemas.java</include>
<include>LongArrayList.java</include>
<include>ManifestSchemaFactory.java</include>
<include>MapEntryLite.java</include>

View File

@ -64,6 +64,7 @@ genrule(
conformance_test(
name = "conformance_test",
failure_list = "//conformance:failure_list_php.txt",
maximum_edition = "2023",
target_compatible_with = select({
"@platforms//os:osx": ["@platforms//:incompatible"],
"//conditions:default": [],
@ -75,6 +76,7 @@ conformance_test(
conformance_test(
name = "conformance_test_c",
failure_list = "//conformance:failure_list_php_c.txt",
maximum_edition = "2023",
target_compatible_with = select({
"@platforms//os:osx": [],
"//conditions:default": ["@platforms//:incompatible"],

View File

@ -6158,7 +6158,7 @@ upb_Message* _upb_Message_Copy(upb_Message* dst, const upb_Message* src,
return NULL;
}
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(dst, mini_table, field,
(dst, field,
UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(dst_sub_message,
is_empty));
}

View File

@ -413,113 +413,6 @@ void upb_Status_VAppendErrorFormat(upb_Status* status, const char* fmt,
#ifndef UPB_MESSAGE_ACCESSORS_H_
#define UPB_MESSAGE_ACCESSORS_H_
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#ifndef UPB_BASE_DESCRIPTOR_CONSTANTS_H_
#define UPB_BASE_DESCRIPTOR_CONSTANTS_H_
// Must be last.
// The types a field can have. Note that this list is not identical to the
// types defined in descriptor.proto, which gives INT32 and SINT32 separate
// types (we distinguish the two with the "integer encoding" enum below).
// This enum is an internal convenience only and has no meaning outside of upb.
typedef enum {
kUpb_CType_Bool = 1,
kUpb_CType_Float = 2,
kUpb_CType_Int32 = 3,
kUpb_CType_UInt32 = 4,
kUpb_CType_Enum = 5, // Enum values are int32. TODO: rename
kUpb_CType_Message = 6,
kUpb_CType_Double = 7,
kUpb_CType_Int64 = 8,
kUpb_CType_UInt64 = 9,
kUpb_CType_String = 10,
kUpb_CType_Bytes = 11
} upb_CType;
// The repeated-ness of each field; this matches descriptor.proto.
typedef enum {
kUpb_Label_Optional = 1,
kUpb_Label_Required = 2,
kUpb_Label_Repeated = 3
} upb_Label;
// Descriptor types, as defined in descriptor.proto.
typedef enum {
kUpb_FieldType_Double = 1,
kUpb_FieldType_Float = 2,
kUpb_FieldType_Int64 = 3,
kUpb_FieldType_UInt64 = 4,
kUpb_FieldType_Int32 = 5,
kUpb_FieldType_Fixed64 = 6,
kUpb_FieldType_Fixed32 = 7,
kUpb_FieldType_Bool = 8,
kUpb_FieldType_String = 9,
kUpb_FieldType_Group = 10,
kUpb_FieldType_Message = 11,
kUpb_FieldType_Bytes = 12,
kUpb_FieldType_UInt32 = 13,
kUpb_FieldType_Enum = 14,
kUpb_FieldType_SFixed32 = 15,
kUpb_FieldType_SFixed64 = 16,
kUpb_FieldType_SInt32 = 17,
kUpb_FieldType_SInt64 = 18,
} upb_FieldType;
#define kUpb_FieldType_SizeOf 19
#ifdef __cplusplus
extern "C" {
#endif
// Convert from upb_FieldType to upb_CType
UPB_INLINE upb_CType upb_FieldType_CType(upb_FieldType field_type) {
static const upb_CType c_type[] = {
kUpb_CType_Double, // kUpb_FieldType_Double
kUpb_CType_Float, // kUpb_FieldType_Float
kUpb_CType_Int64, // kUpb_FieldType_Int64
kUpb_CType_UInt64, // kUpb_FieldType_UInt64
kUpb_CType_Int32, // kUpb_FieldType_Int32
kUpb_CType_UInt64, // kUpb_FieldType_Fixed64
kUpb_CType_UInt32, // kUpb_FieldType_Fixed32
kUpb_CType_Bool, // kUpb_FieldType_Bool
kUpb_CType_String, // kUpb_FieldType_String
kUpb_CType_Message, // kUpb_FieldType_Group
kUpb_CType_Message, // kUpb_FieldType_Message
kUpb_CType_Bytes, // kUpb_FieldType_Bytes
kUpb_CType_UInt32, // kUpb_FieldType_UInt32
kUpb_CType_Enum, // kUpb_FieldType_Enum
kUpb_CType_Int32, // kUpb_FieldType_SFixed32
kUpb_CType_Int64, // kUpb_FieldType_SFixed64
kUpb_CType_Int32, // kUpb_FieldType_SInt32
kUpb_CType_Int64, // kUpb_FieldType_SInt64
};
// -1 here because the enum is one-based but the table is zero-based.
return c_type[field_type - 1];
}
UPB_INLINE bool upb_FieldType_IsPackable(upb_FieldType field_type) {
// clang-format off
const unsigned kUnpackableTypes =
(1 << kUpb_FieldType_String) |
(1 << kUpb_FieldType_Bytes) |
(1 << kUpb_FieldType_Message) |
(1 << kUpb_FieldType_Group);
// clang-format on
return (1 << field_type) & ~kUnpackableTypes;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* UPB_BASE_DESCRIPTOR_CONSTANTS_H_ */
#ifndef UPB_BASE_STRING_VIEW_H_
#define UPB_BASE_STRING_VIEW_H_
@ -827,6 +720,109 @@ void upb_Arena_SetTraceHandler(void (*initArenaTraceHandler)(const upb_Arena*,
#include <stddef.h>
#ifndef UPB_BASE_DESCRIPTOR_CONSTANTS_H_
#define UPB_BASE_DESCRIPTOR_CONSTANTS_H_
// Must be last.
// The types a field can have. Note that this list is not identical to the
// types defined in descriptor.proto, which gives INT32 and SINT32 separate
// types (we distinguish the two with the "integer encoding" enum below).
// This enum is an internal convenience only and has no meaning outside of upb.
typedef enum {
kUpb_CType_Bool = 1,
kUpb_CType_Float = 2,
kUpb_CType_Int32 = 3,
kUpb_CType_UInt32 = 4,
kUpb_CType_Enum = 5, // Enum values are int32. TODO: rename
kUpb_CType_Message = 6,
kUpb_CType_Double = 7,
kUpb_CType_Int64 = 8,
kUpb_CType_UInt64 = 9,
kUpb_CType_String = 10,
kUpb_CType_Bytes = 11
} upb_CType;
// The repeated-ness of each field; this matches descriptor.proto.
typedef enum {
kUpb_Label_Optional = 1,
kUpb_Label_Required = 2,
kUpb_Label_Repeated = 3
} upb_Label;
// Descriptor types, as defined in descriptor.proto.
typedef enum {
kUpb_FieldType_Double = 1,
kUpb_FieldType_Float = 2,
kUpb_FieldType_Int64 = 3,
kUpb_FieldType_UInt64 = 4,
kUpb_FieldType_Int32 = 5,
kUpb_FieldType_Fixed64 = 6,
kUpb_FieldType_Fixed32 = 7,
kUpb_FieldType_Bool = 8,
kUpb_FieldType_String = 9,
kUpb_FieldType_Group = 10,
kUpb_FieldType_Message = 11,
kUpb_FieldType_Bytes = 12,
kUpb_FieldType_UInt32 = 13,
kUpb_FieldType_Enum = 14,
kUpb_FieldType_SFixed32 = 15,
kUpb_FieldType_SFixed64 = 16,
kUpb_FieldType_SInt32 = 17,
kUpb_FieldType_SInt64 = 18,
} upb_FieldType;
#define kUpb_FieldType_SizeOf 19
#ifdef __cplusplus
extern "C" {
#endif
// Convert from upb_FieldType to upb_CType
UPB_INLINE upb_CType upb_FieldType_CType(upb_FieldType field_type) {
static const upb_CType c_type[] = {
kUpb_CType_Double, // kUpb_FieldType_Double
kUpb_CType_Float, // kUpb_FieldType_Float
kUpb_CType_Int64, // kUpb_FieldType_Int64
kUpb_CType_UInt64, // kUpb_FieldType_UInt64
kUpb_CType_Int32, // kUpb_FieldType_Int32
kUpb_CType_UInt64, // kUpb_FieldType_Fixed64
kUpb_CType_UInt32, // kUpb_FieldType_Fixed32
kUpb_CType_Bool, // kUpb_FieldType_Bool
kUpb_CType_String, // kUpb_FieldType_String
kUpb_CType_Message, // kUpb_FieldType_Group
kUpb_CType_Message, // kUpb_FieldType_Message
kUpb_CType_Bytes, // kUpb_FieldType_Bytes
kUpb_CType_UInt32, // kUpb_FieldType_UInt32
kUpb_CType_Enum, // kUpb_FieldType_Enum
kUpb_CType_Int32, // kUpb_FieldType_SFixed32
kUpb_CType_Int64, // kUpb_FieldType_SFixed64
kUpb_CType_Int32, // kUpb_FieldType_SInt32
kUpb_CType_Int64, // kUpb_FieldType_SInt64
};
// -1 here because the enum is one-based but the table is zero-based.
return c_type[field_type - 1];
}
UPB_INLINE bool upb_FieldType_IsPackable(upb_FieldType field_type) {
// clang-format off
const unsigned kUnpackableTypes =
(1 << kUpb_FieldType_String) |
(1 << kUpb_FieldType_Bytes) |
(1 << kUpb_FieldType_Message) |
(1 << kUpb_FieldType_Group);
// clang-format on
return (1 << field_type) & ~kUnpackableTypes;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* UPB_BASE_DESCRIPTOR_CONSTANTS_H_ */
#ifndef UPB_MESSAGE_INTERNAL_ARRAY_H_
#define UPB_MESSAGE_INTERNAL_ARRAY_H_
@ -1845,6 +1841,7 @@ UPB_INLINE uint64_t upb_BigEndian64(uint64_t val) {
#ifndef UPB_MINI_TABLE_INTERNAL_EXTENSION_H_
#define UPB_MINI_TABLE_INTERNAL_EXTENSION_H_
#include <stddef.h>
#include <stdint.h>
@ -1874,6 +1871,9 @@ upb_MiniTableExtension_Number(const struct upb_MiniTableExtension* e) {
UPB_API_INLINE const struct upb_MiniTable* upb_MiniTableExtension_GetSubMessage(
const struct upb_MiniTableExtension* e) {
if (upb_MiniTableExtension_CType(e) != kUpb_CType_Message) {
return NULL;
}
return upb_MiniTableSub_Message(e->UPB_PRIVATE(sub));
}
@ -1882,6 +1882,11 @@ UPB_API_INLINE void upb_MiniTableExtension_SetSubMessage(
e->UPB_PRIVATE(sub).UPB_PRIVATE(submsg) = m;
}
UPB_INLINE upb_FieldRep UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(
const struct upb_MiniTableExtension* e) {
return UPB_PRIVATE(_upb_MiniTableField_GetRep)(&e->UPB_PRIVATE(field));
}
#ifdef __cplusplus
} /* extern "C" */
#endif
@ -2796,7 +2801,6 @@ UPB_INLINE bool UPB_PRIVATE(_upb_MiniTableField_DataIsZero)(
// const upb_MiniTableField* field,
// bool value, upb_Arena* a) {
// UPB_ASSUME(field->UPB_PRIVATE(descriptortype) == kUpb_FieldType_Bool);
// UPB_ASSUME(upb_MiniTableField_IsScalar(field));
// UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(field) ==
// kUpb_FieldRep_1Byte);
// upb_Message_SetField(msg, field, &value, a);
@ -2927,8 +2931,8 @@ UPB_API_INLINE bool upb_Message_GetBool(const struct upb_Message* msg,
const upb_MiniTableField* f,
bool default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
upb_MessageValue def;
def.bool_val = default_val;
return upb_Message_GetField(msg, f, def).bool_val;
@ -2938,8 +2942,8 @@ UPB_API_INLINE double upb_Message_GetDouble(const struct upb_Message* msg,
const upb_MiniTableField* f,
double default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.double_val = default_val;
@ -2950,8 +2954,8 @@ UPB_API_INLINE float upb_Message_GetFloat(const struct upb_Message* msg,
const upb_MiniTableField* f,
float default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.float_val = default_val;
@ -2963,8 +2967,8 @@ UPB_API_INLINE int32_t upb_Message_GetInt32(const struct upb_Message* msg,
int32_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.int32_val = default_val;
@ -2975,8 +2979,8 @@ UPB_API_INLINE int64_t upb_Message_GetInt64(const struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.int64_val = default_val;
@ -3005,6 +3009,37 @@ UPB_API_INLINE const struct upb_Map* upb_Message_GetMap(
return ret;
}
UPB_API_INLINE uintptr_t upb_Message_GetTaggedMessagePtr(
const struct upb_Message* msg, const upb_MiniTableField* f,
struct upb_Message* default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
uintptr_t tagged;
_upb_Message_GetNonExtensionField(msg, f, &default_val, &tagged);
return tagged;
}
// For internal use only; users cannot set tagged messages because only the
// parser and the message copier are allowed to directly create an empty
// message.
UPB_INLINE void UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)(
struct upb_Message* msg, const upb_MiniTableField* f,
uintptr_t sub_message) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_Message_SetBaseField(msg, f, &sub_message);
}
UPB_API_INLINE const struct upb_Message* upb_Message_GetMessage(
const struct upb_Message* msg, const upb_MiniTableField* f) {
uintptr_t tagged = upb_Message_GetTaggedMessagePtr(msg, f, NULL);
return upb_TaggedMessagePtr_GetNonEmptyMessage(tagged);
}
UPB_API_INLINE upb_Array* upb_Message_GetMutableArray(
struct upb_Message* msg, const upb_MiniTableField* f) {
UPB_PRIVATE(_upb_MiniTableField_CheckIsArray)(f);
@ -3016,6 +3051,11 @@ UPB_API_INLINE struct upb_Map* upb_Message_GetMutableMap(
return (struct upb_Map*)upb_Message_GetMap(msg, f);
}
UPB_API_INLINE struct upb_Message* upb_Message_GetMutableMessage(
struct upb_Message* msg, const upb_MiniTableField* f) {
return (struct upb_Message*)upb_Message_GetMessage(msg, f);
}
UPB_API_INLINE upb_Array* upb_Message_GetOrCreateMutableArray(
struct upb_Message* msg, const upb_MiniTableField* f, upb_Arena* arena) {
UPB_ASSERT(arena);
@ -3091,7 +3131,6 @@ upb_Message_GetString(const struct upb_Message* msg,
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue def;
def.str_val = default_val;
@ -3102,8 +3141,8 @@ UPB_API_INLINE uint32_t upb_Message_GetUInt32(const struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.uint32_val = default_val;
@ -3114,23 +3153,89 @@ UPB_API_INLINE uint64_t upb_Message_GetUInt64(const struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.uint64_val = default_val;
return upb_Message_GetField(msg, f, def).uint64_val;
}
UPB_API_INLINE bool upb_Message_SetBool(struct upb_Message* msg,
const upb_MiniTableField* f, bool value,
upb_Arena* a) {
// BaseField Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE void upb_Message_SetBaseFieldBool(struct upb_Message* msg,
const upb_MiniTableField* f,
bool value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.bool_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldDouble(struct upb_Message* msg,
const upb_MiniTableField* f,
double value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldFloat(struct upb_Message* msg,
const upb_MiniTableField* f,
float value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
int32_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldString(struct upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_String ||
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldUInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldUInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetClosedEnum(
@ -3138,55 +3243,141 @@ UPB_API_INLINE void upb_Message_SetClosedEnum(
const upb_MiniTableField* f, int32_t value) {
UPB_ASSERT(upb_MiniTableField_IsClosedEnum(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSERT(upb_MiniTableEnum_CheckValue(
upb_MiniTable_GetSubEnumTable(msg_mini_table, f), value));
upb_Message_SetBaseField(msg, f, &value);
}
// Extension Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE bool upb_Message_SetExtensionBool(
struct upb_Message* msg, const upb_MiniTableExtension* e, bool value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_1Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionDouble(
struct upb_Message* msg, const upb_MiniTableExtension* e, double value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionFloat(
struct upb_Message* msg, const upb_MiniTableExtension* e, float value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionInt32(
struct upb_Message* msg, const upb_MiniTableExtension* e, int32_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Int32 ||
upb_MiniTableExtension_CType(e) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionInt64(
struct upb_Message* msg, const upb_MiniTableExtension* e, int64_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionString(
struct upb_Message* msg, const upb_MiniTableExtension* e,
upb_StringView value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_String ||
upb_MiniTableExtension_CType(e) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_StringView);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionUInt32(
struct upb_Message* msg, const upb_MiniTableExtension* e, uint32_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionUInt64(
struct upb_Message* msg, const upb_MiniTableExtension* e, uint64_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
// Universal Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE bool upb_Message_SetBool(struct upb_Message* msg,
const upb_MiniTableField* f, bool value,
upb_Arena* a) {
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionBool(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldBool(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetDouble(struct upb_Message* msg,
const upb_MiniTableField* f,
double value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.double_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionDouble(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldDouble(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetFloat(struct upb_Message* msg,
const upb_MiniTableField* f,
float value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.float_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionFloat(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldFloat(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
int32_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.int32_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionInt32(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldInt32(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.int64_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionInt64(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldInt64(msg, f, value), true);
}
// Sets the value of a message-typed field. The mini_tables of `msg` and
// `value` must have been linked for this to work correctly.
UPB_API_INLINE void upb_Message_SetMessage(struct upb_Message* msg,
const upb_MiniTableField* f,
struct upb_Message* value) {
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(msg, f, UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(value, false));
}
// Sets the value of a `string` or `bytes` field. The bytes of the value are not
@ -3196,36 +3387,28 @@ UPB_API_INLINE bool upb_Message_SetInt64(struct upb_Message* msg,
UPB_API_INLINE bool upb_Message_SetString(struct upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_String ||
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.str_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionString(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldString(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetUInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.uint32_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionUInt32(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldUInt32(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetUInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.uint64_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionUInt64(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldUInt64(msg, f, value), true);
}
UPB_API_INLINE void upb_Message_Clear(struct upb_Message* msg,
@ -3504,41 +3687,6 @@ UPB_API_INLINE upb_Message* upb_TaggedMessagePtr_GetNonEmptyMessage(
#endif /* UPB_MINI_TABLE_TAGGED_PTR_H_ */
#ifndef UPB_MINI_TABLE_SUB_H_
#define UPB_MINI_TABLE_SUB_H_
// Must be last.
typedef union upb_MiniTableSub upb_MiniTableSub;
#ifdef __cplusplus
extern "C" {
#endif
// Constructors
UPB_API_INLINE upb_MiniTableSub
upb_MiniTableSub_FromEnum(const upb_MiniTableEnum* subenum);
UPB_API_INLINE upb_MiniTableSub
upb_MiniTableSub_FromMessage(const upb_MiniTable* submsg);
// Getters
UPB_API_INLINE const upb_MiniTableEnum* upb_MiniTableSub_Enum(
upb_MiniTableSub sub);
UPB_API_INLINE const upb_MiniTable* upb_MiniTableSub_Message(
upb_MiniTableSub sub);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* UPB_MINI_TABLE_SUB_H_ */
// Must be last.
#ifdef __cplusplus
@ -3581,6 +3729,10 @@ UPB_API_INLINE upb_MessageValue
upb_Message_GetField(const upb_Message* msg, const upb_MiniTableField* f,
upb_MessageValue default_val);
UPB_API_INLINE upb_TaggedMessagePtr upb_Message_GetTaggedMessagePtr(
const upb_Message* msg, const upb_MiniTableField* field,
upb_Message* default_val);
UPB_API_INLINE const upb_Array* upb_Message_GetArray(
const upb_Message* msg, const upb_MiniTableField* f);
@ -3607,12 +3759,18 @@ UPB_API_INLINE int64_t upb_Message_GetInt64(const upb_Message* msg,
UPB_API_INLINE const upb_Map* upb_Message_GetMap(const upb_Message* msg,
const upb_MiniTableField* f);
UPB_API_INLINE const upb_Message* upb_Message_GetMessage(
const upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Array* upb_Message_GetMutableArray(
upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Map* upb_Message_GetMutableMap(upb_Message* msg,
const upb_MiniTableField* f);
UPB_API_INLINE upb_Message* upb_Message_GetMutableMessage(
upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Array* upb_Message_GetOrCreateMutableArray(
upb_Message* msg, const upb_MiniTableField* f, upb_Arena* arena);
@ -3660,6 +3818,10 @@ UPB_API_INLINE bool upb_Message_SetInt64(upb_Message* msg,
const upb_MiniTableField* f,
int64_t value, upb_Arena* a);
UPB_API_INLINE void upb_Message_SetMessage(upb_Message* msg,
const upb_MiniTableField* f,
upb_Message* value);
UPB_API_INLINE bool upb_Message_SetString(upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value, upb_Arena* a);
@ -3672,55 +3834,6 @@ UPB_API_INLINE bool upb_Message_SetUInt64(upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value, upb_Arena* a);
UPB_API_INLINE upb_TaggedMessagePtr upb_Message_GetTaggedMessagePtr(
const upb_Message* msg, const upb_MiniTableField* field,
upb_Message* default_val) {
UPB_ASSUME(upb_MiniTableField_CType(field) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(field) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(field));
upb_TaggedMessagePtr tagged;
_upb_Message_GetNonExtensionField(msg, field, &default_val, &tagged);
return tagged;
}
UPB_API_INLINE const upb_Message* upb_Message_GetMessage(
const upb_Message* msg, const upb_MiniTableField* field) {
upb_TaggedMessagePtr tagged =
upb_Message_GetTaggedMessagePtr(msg, field, NULL);
return upb_TaggedMessagePtr_GetNonEmptyMessage(tagged);
}
UPB_API_INLINE upb_Message* upb_Message_GetMutableMessage(
upb_Message* msg, const upb_MiniTableField* field) {
return (upb_Message*)upb_Message_GetMessage(msg, field);
}
// For internal use only; users cannot set tagged messages because only the
// parser and the message copier are allowed to directly create an empty
// message.
UPB_INLINE void UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)(
struct upb_Message* msg, const upb_MiniTable* mini_table,
const upb_MiniTableField* f, upb_TaggedMessagePtr sub_message) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_Message_SetBaseField(msg, f, &sub_message);
}
// Sets the value of a message-typed field. The `mini_table` and `field`
// parameters belong to `msg`, not `sub_message`. The mini_tables of `msg` and
// `sub_message` must have been linked for this to work correctly.
UPB_API_INLINE void upb_Message_SetMessage(upb_Message* msg,
const upb_MiniTable* mini_table,
const upb_MiniTableField* field,
upb_Message* sub_message) {
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(msg, mini_table, field,
UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(sub_message, false));
}
UPB_API_INLINE void* upb_Message_ResizeArrayUninitialized(
upb_Message* msg, const upb_MiniTableField* f, size_t size,
upb_Arena* arena);
@ -3793,6 +3906,41 @@ UPB_INLINE void _upb_msg_map_set_value(void* msg, const void* val,
#define UPB_MINI_TABLE_DECODE_H_
#ifndef UPB_MINI_TABLE_SUB_H_
#define UPB_MINI_TABLE_SUB_H_
// Must be last.
typedef union upb_MiniTableSub upb_MiniTableSub;
#ifdef __cplusplus
extern "C" {
#endif
// Constructors
UPB_API_INLINE upb_MiniTableSub
upb_MiniTableSub_FromEnum(const upb_MiniTableEnum* subenum);
UPB_API_INLINE upb_MiniTableSub
upb_MiniTableSub_FromMessage(const upb_MiniTable* submsg);
// Getters
UPB_API_INLINE const upb_MiniTableEnum* upb_MiniTableSub_Enum(
upb_MiniTableSub sub);
UPB_API_INLINE const upb_MiniTable* upb_MiniTableSub_Message(
upb_MiniTableSub sub);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* UPB_MINI_TABLE_SUB_H_ */
// Export the newer headers, for legacy users. New users should include the
// more specific headers directly.
// IWYU pragma: begin_exports

View File

@ -394,7 +394,8 @@ class Message
}
break;
case GPBType::STRING:
// TODO: Add utf-8 check.
// We don't check UTF-8 here; that will be validated by the
// setter later.
if (!GPBWire::readString($input, $value)) {
throw new GPBDecodeException(
"Unexpected EOF inside string field.");

View File

@ -683,6 +683,21 @@ class EncodeDecodeTest extends TestBase
$m->mergeFromString(hex2bin('7201'));
}
public function testDecodeInvalidStringDataBadUtf8()
{
$this->expectException(Exception::class);
$m = new TestMessage();
$m->mergeFromString(hex2bin('720180'));
}
public function testDecodeValidStringData()
{
$m = new TestMessage();
$m->mergeFromString(hex2bin('720161'));
$this->assertSame('a', $m->getOptionalString());
}
public function testDecodeInvalidBytesLengthMiss()
{
$this->expectException(Exception::class);

View File

@ -80,6 +80,7 @@ def _proto_gen_impl(ctx):
srcs = ctx.files.srcs
langs = ctx.attr.langs or []
out_type = ctx.attr.out_type
enable_editions = ctx.attr.enable_editions
deps = depset(direct = ctx.files.srcs)
source_dir = _SourceDir(ctx)
gen_dir = _GenDir(ctx).rstrip("/")
@ -130,6 +131,8 @@ def _proto_gen_impl(ctx):
generated_files = []
for src in srcs:
args = []
if enable_editions:
args.append("--experimental_editions")
in_gen_dir = src.root.path == gen_dir
if in_gen_dir:
@ -231,6 +234,7 @@ Args:
srcs: Protocol Buffers definition files (.proto) to run the protocol compiler
against.
deps: a list of dependency labels; must be other proto libraries.
enable_editions: if true, sets the --experimental_editions flag.
includes: a list of include paths to .proto files.
protoc: the label of the protocol compiler to generate the sources.
plugin: the label of the protocol compiler plugin to be passed to the protocol
@ -247,6 +251,7 @@ _proto_gen = rule(
attrs = {
"srcs": attr.label_list(allow_files = True),
"deps": attr.label_list(providers = [ProtoGenInfo]),
"enable_editions": attr.bool(),
"includes": attr.string_list(),
"protoc": attr.label(
cfg = "exec",
@ -655,6 +660,7 @@ def _source_proto_library(
protoc = Label("//:protoc"),
testonly = None,
visibility = ["//visibility:public"],
enable_editions = False,
**kwargs):
"""Bazel rule to create generated protobuf code from proto source files for
languages not well supported by Bazel yet. This will output the generated
@ -699,6 +705,7 @@ def _source_proto_library(
srcs = proto_deps,
protoc = protoc,
includes = includes,
enable_editions = enable_editions,
)
full_deps.append(":%s_deps_genproto" % name)
@ -712,6 +719,7 @@ def _source_proto_library(
protoc = protoc,
testonly = testonly,
visibility = visibility,
enable_editions = enable_editions,
)
native.filegroup(

View File

@ -7,11 +7,14 @@
#include "protos_generator/gen_messages.h"
#include <cstddef>
#include <string>
#include <vector>
#include "google/protobuf/descriptor.pb.h"
#include "absl/strings/ascii.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "google/protobuf/descriptor.h"
#include "protos_generator/gen_accessors.h"
#include "protos_generator/gen_enums.h"
@ -120,6 +123,55 @@ void WriteModelAccessDeclaration(const protobuf::Descriptor* descriptor,
output("};\n");
}
std::string UnderscoresToCamelCase(absl::string_view input,
bool cap_next_letter) {
std::string result;
for (size_t i = 0; i < input.size(); i++) {
if (absl::ascii_islower(input[i])) {
if (cap_next_letter) {
result += absl::ascii_toupper(input[i]);
} else {
result += input[i];
}
cap_next_letter = false;
} else if (absl::ascii_isupper(input[i])) {
// Capital letters are left as-is.
result += input[i];
cap_next_letter = false;
} else if (absl::ascii_isdigit(input[i])) {
result += input[i];
cap_next_letter = true;
} else {
cap_next_letter = true;
}
}
return result;
}
std::string FieldConstantName(const protobuf::FieldDescriptor* field) {
std::string field_name = UnderscoresToCamelCase(field->name(), true);
std::string result = absl::StrCat("k", field_name, "FieldNumber");
if (!field->is_extension() &&
field->containing_type()->FindFieldByCamelcaseName(
field->camelcase_name()) != field) {
// This field's camelcase name is not unique, add field number to make it
// unique.
absl::StrAppend(&result, "_", field->number());
}
return result;
}
void WriteConstFieldNumbers(Output& output,
const protobuf::Descriptor* descriptor) {
for (auto field : FieldRange(descriptor)) {
output("static constexpr ::uint32_t $0 = $1;\n", FieldConstantName(field),
field->number());
}
output("\n\n");
}
void WriteModelPublicDeclaration(
const protobuf::Descriptor* descriptor,
const std::vector<const protobuf::FieldDescriptor*>& file_exts,
@ -178,6 +230,7 @@ void WriteModelPublicDeclaration(
)cc",
ClassName(descriptor));
output("\n");
WriteConstFieldNumbers(output, descriptor);
output(
R"cc(
private:

View File

@ -9,6 +9,7 @@
#include <limits>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
@ -1134,6 +1135,11 @@ TEST(CppGeneratedCode, HasExtensionAndRegistry) {
EXPECT_TRUE(::protos::HasExtension(&parsed_model, theme));
}
TEST(CppGeneratedCode, FieldNumberConstants) {
static_assert(TestModel::kChildMapFieldNumber == 225);
EXPECT_EQ(225, TestModel::kChildMapFieldNumber);
}
// TODO : Add BUILD rule to test failures below.
#ifdef TEST_CLEAR_MESSAGE_FAILURE
TEST(CppGeneratedCode, ClearConstMessageShouldFail) {

View File

@ -0,0 +1,34 @@
# -*- coding: utf-8 -*-
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Tests Nextgen Pythonic protobuf APIs."""
import unittest
from google.protobuf import proto
from google.protobuf.internal import test_util
from google.protobuf.internal import testing_refleaks
from google.protobuf.internal import _parameterized
from google.protobuf import unittest_pb2
from google.protobuf import unittest_proto3_arena_pb2
@_parameterized.named_parameters(('_proto2', unittest_pb2),
('_proto3', unittest_proto3_arena_pb2))
@testing_refleaks.TestCase
class ProtoTest(unittest.TestCase):
def testSerializeParse(self, message_module):
msg = message_module.TestAllTypes()
test_util.SetAllFields(msg)
serialized_data = proto.serialize(msg)
parsed_msg = proto.parse(message_module.TestAllTypes, serialized_data)
self.assertEqual(msg, parsed_msg)
if __name__ == '__main__':
unittest.main()

View File

@ -0,0 +1,39 @@
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Contains the Nextgen Pythonic protobuf APIs."""
import typing
from google.protobuf.message import Message
def serialize(message: Message, deterministic: bool=None) -> bytes:
"""Return the serialized proto.
Args:
message: The proto message to be serialized.
deterministic: If true, requests deterministic serialization
of the protobuf, with predictable ordering of map keys.
Returns:
A binary bytes representation of the message.
"""
return message.SerializeToString(deterministic=deterministic)
def parse(message_class: typing.Type[Message], payload: bytes) -> Message:
"""Given a serialized data in binary form, deserialize it into a Message.
Args:
message_class: The message meta class.
payload: A serialized bytes in binary form.
Returns:
A new message deserialized from payload.
"""
new_message = message_class()
new_message.ParseFromString(payload)
return new_message

View File

@ -1039,9 +1039,9 @@ static PyObject* PyUpb_Message_HasField(PyObject* _self, PyObject* arg) {
if (PyUpb_Message_IsStub(self)) Py_RETURN_FALSE;
return PyBool_FromLong(field ? upb_Message_HasFieldByDef(self->ptr.msg, field)
: upb_Message_WhichOneof(self->ptr.msg, oneof) !=
NULL);
return PyBool_FromLong(
field ? upb_Message_HasFieldByDef(self->ptr.msg, field)
: upb_Message_WhichOneofByDef(self->ptr.msg, oneof) != NULL);
}
static PyObject* PyUpb_Message_Contains(PyObject* _self, PyObject* arg) {
@ -1421,7 +1421,7 @@ static PyObject* PyUpb_Message_ClearField(PyObject* _self, PyObject* arg) {
return NULL;
}
if (o) f = upb_Message_WhichOneof(self->ptr.msg, o);
if (o) f = upb_Message_WhichOneofByDef(self->ptr.msg, o);
if (f) PyUpb_Message_DoClearField(_self, f);
Py_RETURN_NONE;
}
@ -1616,7 +1616,7 @@ static PyObject* PyUpb_Message_WhichOneof(PyObject* _self, PyObject* name) {
}
upb_Message* msg = PyUpb_Message_GetIfReified(_self);
if (!msg) Py_RETURN_NONE;
const upb_FieldDef* f = upb_Message_WhichOneof(msg, o);
const upb_FieldDef* f = upb_Message_WhichOneofByDef(msg, o);
if (!f) Py_RETURN_NONE;
return PyUnicode_FromString(upb_FieldDef_Name(f));
}

View File

@ -248,7 +248,7 @@ static int extract_method_call(VALUE method_name, Message* self,
static VALUE Message_oneof_accessor(VALUE _self, const upb_OneofDef* o,
int accessor_type) {
Message* self = ruby_to_Message(_self);
const upb_FieldDef* oneof_field = upb_Message_WhichOneof(self->msg, o);
const upb_FieldDef* oneof_field = upb_Message_WhichOneofByDef(self->msg, o);
switch (accessor_type) {
case METHOD_PRESENCE:

View File

@ -5650,7 +5650,7 @@ upb_Message* _upb_Message_Copy(upb_Message* dst, const upb_Message* src,
return NULL;
}
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(dst, mini_table, field,
(dst, field,
UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(dst_sub_message,
is_empty));
}

View File

@ -415,113 +415,6 @@ void upb_Status_VAppendErrorFormat(upb_Status* status, const char* fmt,
#ifndef UPB_MESSAGE_ACCESSORS_H_
#define UPB_MESSAGE_ACCESSORS_H_
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#ifndef UPB_BASE_DESCRIPTOR_CONSTANTS_H_
#define UPB_BASE_DESCRIPTOR_CONSTANTS_H_
// Must be last.
// The types a field can have. Note that this list is not identical to the
// types defined in descriptor.proto, which gives INT32 and SINT32 separate
// types (we distinguish the two with the "integer encoding" enum below).
// This enum is an internal convenience only and has no meaning outside of upb.
typedef enum {
kUpb_CType_Bool = 1,
kUpb_CType_Float = 2,
kUpb_CType_Int32 = 3,
kUpb_CType_UInt32 = 4,
kUpb_CType_Enum = 5, // Enum values are int32. TODO: rename
kUpb_CType_Message = 6,
kUpb_CType_Double = 7,
kUpb_CType_Int64 = 8,
kUpb_CType_UInt64 = 9,
kUpb_CType_String = 10,
kUpb_CType_Bytes = 11
} upb_CType;
// The repeated-ness of each field; this matches descriptor.proto.
typedef enum {
kUpb_Label_Optional = 1,
kUpb_Label_Required = 2,
kUpb_Label_Repeated = 3
} upb_Label;
// Descriptor types, as defined in descriptor.proto.
typedef enum {
kUpb_FieldType_Double = 1,
kUpb_FieldType_Float = 2,
kUpb_FieldType_Int64 = 3,
kUpb_FieldType_UInt64 = 4,
kUpb_FieldType_Int32 = 5,
kUpb_FieldType_Fixed64 = 6,
kUpb_FieldType_Fixed32 = 7,
kUpb_FieldType_Bool = 8,
kUpb_FieldType_String = 9,
kUpb_FieldType_Group = 10,
kUpb_FieldType_Message = 11,
kUpb_FieldType_Bytes = 12,
kUpb_FieldType_UInt32 = 13,
kUpb_FieldType_Enum = 14,
kUpb_FieldType_SFixed32 = 15,
kUpb_FieldType_SFixed64 = 16,
kUpb_FieldType_SInt32 = 17,
kUpb_FieldType_SInt64 = 18,
} upb_FieldType;
#define kUpb_FieldType_SizeOf 19
#ifdef __cplusplus
extern "C" {
#endif
// Convert from upb_FieldType to upb_CType
UPB_INLINE upb_CType upb_FieldType_CType(upb_FieldType field_type) {
static const upb_CType c_type[] = {
kUpb_CType_Double, // kUpb_FieldType_Double
kUpb_CType_Float, // kUpb_FieldType_Float
kUpb_CType_Int64, // kUpb_FieldType_Int64
kUpb_CType_UInt64, // kUpb_FieldType_UInt64
kUpb_CType_Int32, // kUpb_FieldType_Int32
kUpb_CType_UInt64, // kUpb_FieldType_Fixed64
kUpb_CType_UInt32, // kUpb_FieldType_Fixed32
kUpb_CType_Bool, // kUpb_FieldType_Bool
kUpb_CType_String, // kUpb_FieldType_String
kUpb_CType_Message, // kUpb_FieldType_Group
kUpb_CType_Message, // kUpb_FieldType_Message
kUpb_CType_Bytes, // kUpb_FieldType_Bytes
kUpb_CType_UInt32, // kUpb_FieldType_UInt32
kUpb_CType_Enum, // kUpb_FieldType_Enum
kUpb_CType_Int32, // kUpb_FieldType_SFixed32
kUpb_CType_Int64, // kUpb_FieldType_SFixed64
kUpb_CType_Int32, // kUpb_FieldType_SInt32
kUpb_CType_Int64, // kUpb_FieldType_SInt64
};
// -1 here because the enum is one-based but the table is zero-based.
return c_type[field_type - 1];
}
UPB_INLINE bool upb_FieldType_IsPackable(upb_FieldType field_type) {
// clang-format off
const unsigned kUnpackableTypes =
(1 << kUpb_FieldType_String) |
(1 << kUpb_FieldType_Bytes) |
(1 << kUpb_FieldType_Message) |
(1 << kUpb_FieldType_Group);
// clang-format on
return (1 << field_type) & ~kUnpackableTypes;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* UPB_BASE_DESCRIPTOR_CONSTANTS_H_ */
#ifndef UPB_BASE_STRING_VIEW_H_
#define UPB_BASE_STRING_VIEW_H_
@ -829,6 +722,109 @@ void upb_Arena_SetTraceHandler(void (*initArenaTraceHandler)(const upb_Arena*,
#include <stddef.h>
#ifndef UPB_BASE_DESCRIPTOR_CONSTANTS_H_
#define UPB_BASE_DESCRIPTOR_CONSTANTS_H_
// Must be last.
// The types a field can have. Note that this list is not identical to the
// types defined in descriptor.proto, which gives INT32 and SINT32 separate
// types (we distinguish the two with the "integer encoding" enum below).
// This enum is an internal convenience only and has no meaning outside of upb.
typedef enum {
kUpb_CType_Bool = 1,
kUpb_CType_Float = 2,
kUpb_CType_Int32 = 3,
kUpb_CType_UInt32 = 4,
kUpb_CType_Enum = 5, // Enum values are int32. TODO: rename
kUpb_CType_Message = 6,
kUpb_CType_Double = 7,
kUpb_CType_Int64 = 8,
kUpb_CType_UInt64 = 9,
kUpb_CType_String = 10,
kUpb_CType_Bytes = 11
} upb_CType;
// The repeated-ness of each field; this matches descriptor.proto.
typedef enum {
kUpb_Label_Optional = 1,
kUpb_Label_Required = 2,
kUpb_Label_Repeated = 3
} upb_Label;
// Descriptor types, as defined in descriptor.proto.
typedef enum {
kUpb_FieldType_Double = 1,
kUpb_FieldType_Float = 2,
kUpb_FieldType_Int64 = 3,
kUpb_FieldType_UInt64 = 4,
kUpb_FieldType_Int32 = 5,
kUpb_FieldType_Fixed64 = 6,
kUpb_FieldType_Fixed32 = 7,
kUpb_FieldType_Bool = 8,
kUpb_FieldType_String = 9,
kUpb_FieldType_Group = 10,
kUpb_FieldType_Message = 11,
kUpb_FieldType_Bytes = 12,
kUpb_FieldType_UInt32 = 13,
kUpb_FieldType_Enum = 14,
kUpb_FieldType_SFixed32 = 15,
kUpb_FieldType_SFixed64 = 16,
kUpb_FieldType_SInt32 = 17,
kUpb_FieldType_SInt64 = 18,
} upb_FieldType;
#define kUpb_FieldType_SizeOf 19
#ifdef __cplusplus
extern "C" {
#endif
// Convert from upb_FieldType to upb_CType
UPB_INLINE upb_CType upb_FieldType_CType(upb_FieldType field_type) {
static const upb_CType c_type[] = {
kUpb_CType_Double, // kUpb_FieldType_Double
kUpb_CType_Float, // kUpb_FieldType_Float
kUpb_CType_Int64, // kUpb_FieldType_Int64
kUpb_CType_UInt64, // kUpb_FieldType_UInt64
kUpb_CType_Int32, // kUpb_FieldType_Int32
kUpb_CType_UInt64, // kUpb_FieldType_Fixed64
kUpb_CType_UInt32, // kUpb_FieldType_Fixed32
kUpb_CType_Bool, // kUpb_FieldType_Bool
kUpb_CType_String, // kUpb_FieldType_String
kUpb_CType_Message, // kUpb_FieldType_Group
kUpb_CType_Message, // kUpb_FieldType_Message
kUpb_CType_Bytes, // kUpb_FieldType_Bytes
kUpb_CType_UInt32, // kUpb_FieldType_UInt32
kUpb_CType_Enum, // kUpb_FieldType_Enum
kUpb_CType_Int32, // kUpb_FieldType_SFixed32
kUpb_CType_Int64, // kUpb_FieldType_SFixed64
kUpb_CType_Int32, // kUpb_FieldType_SInt32
kUpb_CType_Int64, // kUpb_FieldType_SInt64
};
// -1 here because the enum is one-based but the table is zero-based.
return c_type[field_type - 1];
}
UPB_INLINE bool upb_FieldType_IsPackable(upb_FieldType field_type) {
// clang-format off
const unsigned kUnpackableTypes =
(1 << kUpb_FieldType_String) |
(1 << kUpb_FieldType_Bytes) |
(1 << kUpb_FieldType_Message) |
(1 << kUpb_FieldType_Group);
// clang-format on
return (1 << field_type) & ~kUnpackableTypes;
}
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* UPB_BASE_DESCRIPTOR_CONSTANTS_H_ */
#ifndef UPB_MESSAGE_INTERNAL_ARRAY_H_
#define UPB_MESSAGE_INTERNAL_ARRAY_H_
@ -1847,6 +1843,7 @@ UPB_INLINE uint64_t upb_BigEndian64(uint64_t val) {
#ifndef UPB_MINI_TABLE_INTERNAL_EXTENSION_H_
#define UPB_MINI_TABLE_INTERNAL_EXTENSION_H_
#include <stddef.h>
#include <stdint.h>
@ -1876,6 +1873,9 @@ upb_MiniTableExtension_Number(const struct upb_MiniTableExtension* e) {
UPB_API_INLINE const struct upb_MiniTable* upb_MiniTableExtension_GetSubMessage(
const struct upb_MiniTableExtension* e) {
if (upb_MiniTableExtension_CType(e) != kUpb_CType_Message) {
return NULL;
}
return upb_MiniTableSub_Message(e->UPB_PRIVATE(sub));
}
@ -1884,6 +1884,11 @@ UPB_API_INLINE void upb_MiniTableExtension_SetSubMessage(
e->UPB_PRIVATE(sub).UPB_PRIVATE(submsg) = m;
}
UPB_INLINE upb_FieldRep UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(
const struct upb_MiniTableExtension* e) {
return UPB_PRIVATE(_upb_MiniTableField_GetRep)(&e->UPB_PRIVATE(field));
}
#ifdef __cplusplus
} /* extern "C" */
#endif
@ -2798,7 +2803,6 @@ UPB_INLINE bool UPB_PRIVATE(_upb_MiniTableField_DataIsZero)(
// const upb_MiniTableField* field,
// bool value, upb_Arena* a) {
// UPB_ASSUME(field->UPB_PRIVATE(descriptortype) == kUpb_FieldType_Bool);
// UPB_ASSUME(upb_MiniTableField_IsScalar(field));
// UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(field) ==
// kUpb_FieldRep_1Byte);
// upb_Message_SetField(msg, field, &value, a);
@ -2929,8 +2933,8 @@ UPB_API_INLINE bool upb_Message_GetBool(const struct upb_Message* msg,
const upb_MiniTableField* f,
bool default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
upb_MessageValue def;
def.bool_val = default_val;
return upb_Message_GetField(msg, f, def).bool_val;
@ -2940,8 +2944,8 @@ UPB_API_INLINE double upb_Message_GetDouble(const struct upb_Message* msg,
const upb_MiniTableField* f,
double default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.double_val = default_val;
@ -2952,8 +2956,8 @@ UPB_API_INLINE float upb_Message_GetFloat(const struct upb_Message* msg,
const upb_MiniTableField* f,
float default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.float_val = default_val;
@ -2965,8 +2969,8 @@ UPB_API_INLINE int32_t upb_Message_GetInt32(const struct upb_Message* msg,
int32_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.int32_val = default_val;
@ -2977,8 +2981,8 @@ UPB_API_INLINE int64_t upb_Message_GetInt64(const struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.int64_val = default_val;
@ -3007,6 +3011,37 @@ UPB_API_INLINE const struct upb_Map* upb_Message_GetMap(
return ret;
}
UPB_API_INLINE uintptr_t upb_Message_GetTaggedMessagePtr(
const struct upb_Message* msg, const upb_MiniTableField* f,
struct upb_Message* default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
uintptr_t tagged;
_upb_Message_GetNonExtensionField(msg, f, &default_val, &tagged);
return tagged;
}
// For internal use only; users cannot set tagged messages because only the
// parser and the message copier are allowed to directly create an empty
// message.
UPB_INLINE void UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)(
struct upb_Message* msg, const upb_MiniTableField* f,
uintptr_t sub_message) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_Message_SetBaseField(msg, f, &sub_message);
}
UPB_API_INLINE const struct upb_Message* upb_Message_GetMessage(
const struct upb_Message* msg, const upb_MiniTableField* f) {
uintptr_t tagged = upb_Message_GetTaggedMessagePtr(msg, f, NULL);
return upb_TaggedMessagePtr_GetNonEmptyMessage(tagged);
}
UPB_API_INLINE upb_Array* upb_Message_GetMutableArray(
struct upb_Message* msg, const upb_MiniTableField* f) {
UPB_PRIVATE(_upb_MiniTableField_CheckIsArray)(f);
@ -3018,6 +3053,11 @@ UPB_API_INLINE struct upb_Map* upb_Message_GetMutableMap(
return (struct upb_Map*)upb_Message_GetMap(msg, f);
}
UPB_API_INLINE struct upb_Message* upb_Message_GetMutableMessage(
struct upb_Message* msg, const upb_MiniTableField* f) {
return (struct upb_Message*)upb_Message_GetMessage(msg, f);
}
UPB_API_INLINE upb_Array* upb_Message_GetOrCreateMutableArray(
struct upb_Message* msg, const upb_MiniTableField* f, upb_Arena* arena) {
UPB_ASSERT(arena);
@ -3093,7 +3133,6 @@ upb_Message_GetString(const struct upb_Message* msg,
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue def;
def.str_val = default_val;
@ -3104,8 +3143,8 @@ UPB_API_INLINE uint32_t upb_Message_GetUInt32(const struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.uint32_val = default_val;
@ -3116,23 +3155,89 @@ UPB_API_INLINE uint64_t upb_Message_GetUInt64(const struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.uint64_val = default_val;
return upb_Message_GetField(msg, f, def).uint64_val;
}
UPB_API_INLINE bool upb_Message_SetBool(struct upb_Message* msg,
const upb_MiniTableField* f, bool value,
upb_Arena* a) {
// BaseField Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE void upb_Message_SetBaseFieldBool(struct upb_Message* msg,
const upb_MiniTableField* f,
bool value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.bool_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldDouble(struct upb_Message* msg,
const upb_MiniTableField* f,
double value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldFloat(struct upb_Message* msg,
const upb_MiniTableField* f,
float value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
int32_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldString(struct upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_String ||
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldUInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldUInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetClosedEnum(
@ -3140,55 +3245,141 @@ UPB_API_INLINE void upb_Message_SetClosedEnum(
const upb_MiniTableField* f, int32_t value) {
UPB_ASSERT(upb_MiniTableField_IsClosedEnum(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSERT(upb_MiniTableEnum_CheckValue(
upb_MiniTable_GetSubEnumTable(msg_mini_table, f), value));
upb_Message_SetBaseField(msg, f, &value);
}
// Extension Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE bool upb_Message_SetExtensionBool(
struct upb_Message* msg, const upb_MiniTableExtension* e, bool value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_1Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionDouble(
struct upb_Message* msg, const upb_MiniTableExtension* e, double value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionFloat(
struct upb_Message* msg, const upb_MiniTableExtension* e, float value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionInt32(
struct upb_Message* msg, const upb_MiniTableExtension* e, int32_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Int32 ||
upb_MiniTableExtension_CType(e) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionInt64(
struct upb_Message* msg, const upb_MiniTableExtension* e, int64_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionString(
struct upb_Message* msg, const upb_MiniTableExtension* e,
upb_StringView value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_String ||
upb_MiniTableExtension_CType(e) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_StringView);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionUInt32(
struct upb_Message* msg, const upb_MiniTableExtension* e, uint32_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionUInt64(
struct upb_Message* msg, const upb_MiniTableExtension* e, uint64_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
// Universal Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE bool upb_Message_SetBool(struct upb_Message* msg,
const upb_MiniTableField* f, bool value,
upb_Arena* a) {
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionBool(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldBool(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetDouble(struct upb_Message* msg,
const upb_MiniTableField* f,
double value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.double_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionDouble(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldDouble(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetFloat(struct upb_Message* msg,
const upb_MiniTableField* f,
float value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.float_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionFloat(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldFloat(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
int32_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.int32_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionInt32(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldInt32(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.int64_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionInt64(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldInt64(msg, f, value), true);
}
// Sets the value of a message-typed field. The mini_tables of `msg` and
// `value` must have been linked for this to work correctly.
UPB_API_INLINE void upb_Message_SetMessage(struct upb_Message* msg,
const upb_MiniTableField* f,
struct upb_Message* value) {
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(msg, f, UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(value, false));
}
// Sets the value of a `string` or `bytes` field. The bytes of the value are not
@ -3198,36 +3389,28 @@ UPB_API_INLINE bool upb_Message_SetInt64(struct upb_Message* msg,
UPB_API_INLINE bool upb_Message_SetString(struct upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_String ||
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.str_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionString(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldString(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetUInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.uint32_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionUInt32(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldUInt32(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetUInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.uint64_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionUInt64(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldUInt64(msg, f, value), true);
}
UPB_API_INLINE void upb_Message_Clear(struct upb_Message* msg,
@ -3506,41 +3689,6 @@ UPB_API_INLINE upb_Message* upb_TaggedMessagePtr_GetNonEmptyMessage(
#endif /* UPB_MINI_TABLE_TAGGED_PTR_H_ */
#ifndef UPB_MINI_TABLE_SUB_H_
#define UPB_MINI_TABLE_SUB_H_
// Must be last.
typedef union upb_MiniTableSub upb_MiniTableSub;
#ifdef __cplusplus
extern "C" {
#endif
// Constructors
UPB_API_INLINE upb_MiniTableSub
upb_MiniTableSub_FromEnum(const upb_MiniTableEnum* subenum);
UPB_API_INLINE upb_MiniTableSub
upb_MiniTableSub_FromMessage(const upb_MiniTable* submsg);
// Getters
UPB_API_INLINE const upb_MiniTableEnum* upb_MiniTableSub_Enum(
upb_MiniTableSub sub);
UPB_API_INLINE const upb_MiniTable* upb_MiniTableSub_Message(
upb_MiniTableSub sub);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* UPB_MINI_TABLE_SUB_H_ */
// Must be last.
#ifdef __cplusplus
@ -3583,6 +3731,10 @@ UPB_API_INLINE upb_MessageValue
upb_Message_GetField(const upb_Message* msg, const upb_MiniTableField* f,
upb_MessageValue default_val);
UPB_API_INLINE upb_TaggedMessagePtr upb_Message_GetTaggedMessagePtr(
const upb_Message* msg, const upb_MiniTableField* field,
upb_Message* default_val);
UPB_API_INLINE const upb_Array* upb_Message_GetArray(
const upb_Message* msg, const upb_MiniTableField* f);
@ -3609,12 +3761,18 @@ UPB_API_INLINE int64_t upb_Message_GetInt64(const upb_Message* msg,
UPB_API_INLINE const upb_Map* upb_Message_GetMap(const upb_Message* msg,
const upb_MiniTableField* f);
UPB_API_INLINE const upb_Message* upb_Message_GetMessage(
const upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Array* upb_Message_GetMutableArray(
upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Map* upb_Message_GetMutableMap(upb_Message* msg,
const upb_MiniTableField* f);
UPB_API_INLINE upb_Message* upb_Message_GetMutableMessage(
upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Array* upb_Message_GetOrCreateMutableArray(
upb_Message* msg, const upb_MiniTableField* f, upb_Arena* arena);
@ -3662,6 +3820,10 @@ UPB_API_INLINE bool upb_Message_SetInt64(upb_Message* msg,
const upb_MiniTableField* f,
int64_t value, upb_Arena* a);
UPB_API_INLINE void upb_Message_SetMessage(upb_Message* msg,
const upb_MiniTableField* f,
upb_Message* value);
UPB_API_INLINE bool upb_Message_SetString(upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value, upb_Arena* a);
@ -3674,55 +3836,6 @@ UPB_API_INLINE bool upb_Message_SetUInt64(upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value, upb_Arena* a);
UPB_API_INLINE upb_TaggedMessagePtr upb_Message_GetTaggedMessagePtr(
const upb_Message* msg, const upb_MiniTableField* field,
upb_Message* default_val) {
UPB_ASSUME(upb_MiniTableField_CType(field) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(field) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(field));
upb_TaggedMessagePtr tagged;
_upb_Message_GetNonExtensionField(msg, field, &default_val, &tagged);
return tagged;
}
UPB_API_INLINE const upb_Message* upb_Message_GetMessage(
const upb_Message* msg, const upb_MiniTableField* field) {
upb_TaggedMessagePtr tagged =
upb_Message_GetTaggedMessagePtr(msg, field, NULL);
return upb_TaggedMessagePtr_GetNonEmptyMessage(tagged);
}
UPB_API_INLINE upb_Message* upb_Message_GetMutableMessage(
upb_Message* msg, const upb_MiniTableField* field) {
return (upb_Message*)upb_Message_GetMessage(msg, field);
}
// For internal use only; users cannot set tagged messages because only the
// parser and the message copier are allowed to directly create an empty
// message.
UPB_INLINE void UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)(
struct upb_Message* msg, const upb_MiniTable* mini_table,
const upb_MiniTableField* f, upb_TaggedMessagePtr sub_message) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_Message_SetBaseField(msg, f, &sub_message);
}
// Sets the value of a message-typed field. The `mini_table` and `field`
// parameters belong to `msg`, not `sub_message`. The mini_tables of `msg` and
// `sub_message` must have been linked for this to work correctly.
UPB_API_INLINE void upb_Message_SetMessage(upb_Message* msg,
const upb_MiniTable* mini_table,
const upb_MiniTableField* field,
upb_Message* sub_message) {
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(msg, mini_table, field,
UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(sub_message, false));
}
UPB_API_INLINE void* upb_Message_ResizeArrayUninitialized(
upb_Message* msg, const upb_MiniTableField* f, size_t size,
upb_Arena* arena);
@ -3795,6 +3908,41 @@ UPB_INLINE void _upb_msg_map_set_value(void* msg, const void* val,
#define UPB_MINI_TABLE_DECODE_H_
#ifndef UPB_MINI_TABLE_SUB_H_
#define UPB_MINI_TABLE_SUB_H_
// Must be last.
typedef union upb_MiniTableSub upb_MiniTableSub;
#ifdef __cplusplus
extern "C" {
#endif
// Constructors
UPB_API_INLINE upb_MiniTableSub
upb_MiniTableSub_FromEnum(const upb_MiniTableEnum* subenum);
UPB_API_INLINE upb_MiniTableSub
upb_MiniTableSub_FromMessage(const upb_MiniTable* submsg);
// Getters
UPB_API_INLINE const upb_MiniTableEnum* upb_MiniTableSub_Enum(
upb_MiniTableSub sub);
UPB_API_INLINE const upb_MiniTable* upb_MiniTableSub_Message(
upb_MiniTableSub sub);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* UPB_MINI_TABLE_SUB_H_ */
// Export the newer headers, for legacy users. New users should include the
// more specific headers directly.
// IWYU pragma: begin_exports

View File

@ -8,7 +8,7 @@
//! Tests covering accessors for singular bool, int32, int64, and bytes fields.
use googletest::prelude::*;
use protobuf::{MutProxy, Optional};
use protobuf::Optional;
use unittest_proto::{test_all_types, TestAllTypes};
#[test]
@ -498,15 +498,13 @@ fn test_nonempty_default_string_accessors() {
#[test]
fn test_singular_msg_field() {
use test_all_types::*;
let mut msg = TestAllTypes::new();
let msg_view = msg.optional_nested_message();
// testing reading an int inside a view
assert_that!(msg_view.bb(), eq(0));
assert_that!(msg.has_optional_nested_message(), eq(false));
let mut nested_msg_mut = msg.optional_nested_message_mut();
let nested_msg_mut = msg.optional_nested_message_mut();
// test reading an int inside a mut
assert_that!(nested_msg_mut.bb(), eq(0));
@ -780,3 +778,27 @@ fn test_submsg_setter() {
assert_that!(parent.optional_nested_message().bb(), eq(7));
}
#[test]
fn test_to_owned() {
let mut m = TestAllTypes::new();
m.set_optional_int32(42);
let clone = m.as_view().to_owned();
assert_that!(clone.optional_int32(), eq(42));
// to_owned should create a new message (modifying the original shouldn't affect
// the to_owned).
m.clear_optional_int32();
assert_that!(m.has_optional_int32(), eq(false));
assert_that!(clone.has_optional_int32(), eq(true));
assert_that!(clone.optional_int32(), eq(42));
let mut submsg_mut = m.optional_nested_message_mut();
submsg_mut.set_bb(7);
let submsg_clone = submsg_mut.to_owned();
assert_that!(submsg_clone.bb(), eq(7));
assert_that!(submsg_mut.bb(), eq(7));
submsg_mut.set_bb(8);
assert_that!(submsg_clone.bb(), eq(7));
assert_that!(submsg_mut.bb(), eq(8));
}

View File

@ -142,7 +142,7 @@ struct ArenaOptions {
// This is a thread-safe implementation: multiple threads may allocate from the
// arena concurrently. Destruction is not thread-safe and the destructing
// thread must synchronize with users of the arena first.
class PROTOBUF_EXPORT PROTOBUF_ALIGNAS(8) Arena final {
class PROTOBUF_EXPORT alignas(8) Arena final {
public:
// Default constructor with sensible default options, tuned for average
// use-cases.

View File

@ -78,8 +78,7 @@ std::string UniqueFileScopeIdentifier(const Descriptor* descriptor);
// Gets the unqualified class name for the file. For each .proto file, there
// will be one Java class containing all the immutable messages and another
// Java class containing all the mutable messages.
// TODO: remove the default value after updating client code.
std::string FileClassName(const FileDescriptor* file, bool immutable = true);
std::string FileClassName(const FileDescriptor* file, bool immutable);
// Returns the file's Java package name.
std::string FileJavaPackage(const FileDescriptor* file, bool immutable,

View File

@ -39,16 +39,17 @@ const char* DefaultPackage(Options options) {
bool IsReservedName(absl::string_view name) {
static const auto& kReservedNames =
*new absl::flat_hash_set<absl::string_view>({
"abstract", "assert", "boolean", "break", "byte",
"case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "else",
"enum", "extends", "final", "finally", "float",
"for", "goto", "if", "implements", "import",
"instanceof", "int", "interface", "long", "native",
"new", "package", "private", "protected", "public",
"return", "short", "static", "strictfp", "super",
"switch", "synchronized", "this", "throw", "throws",
"transient", "try", "void", "volatile", "while",
"abstract", "assert", "boolean", "break", "byte",
"case", "catch", "char", "class", "const",
"continue", "default", "do", "double", "else",
"enum", "extends", "false", "final", "finally",
"float", "for", "goto", "if", "implements",
"import", "instanceof", "int", "interface", "long",
"native", "new", "null", "package", "private",
"protected", "public", "return", "short", "static",
"strictfp", "super", "switch", "synchronized", "this",
"throw", "throws", "transient", "true", "try",
"void", "volatile", "while",
});
return kReservedNames.contains(name);
}
@ -140,6 +141,14 @@ std::string FileJavaPackage(const FileDescriptor* file, Options options) {
return FileJavaPackage(file, true /* immutable */, options);
}
std::string JavaPackageDirectory(const FileDescriptor* file) {
return JavaPackageToDir(FileJavaPackage(file));
}
std::string FileClassName(const FileDescriptor* file) {
return FileClassName(file, /*immutable=*/true);
}
std::string CapitalizedFieldName(const FieldDescriptor* field) {
return UnderscoresToCamelCase(FieldName(field), true);
}

View File

@ -72,6 +72,20 @@ std::string ClassName(const ServiceDescriptor* descriptor);
std::string FileJavaPackage(const FileDescriptor* descriptor,
Options options = {});
// Requires:
// descriptor != NULL
//
// Returns:
// Java package directory.
std::string JavaPackageDirectory(const FileDescriptor* file);
// Requires:
// descriptor != NULL
//
// Returns:
// The unqualified Java class name.
std::string FileClassName(const FileDescriptor* file);
// Requires:
// descriptor != NULL
// Returns:

View File

@ -1758,7 +1758,7 @@ void GenerateCMessage(const Descriptor* message, io::Printer* printer) {
" const upb_OneofDef *oneof = upb_MessageDef_FindOneofByName(\n"
" intern->desc->msgdef, \"$name$\");\n"
" const upb_FieldDef *field = \n"
" upb_Message_WhichOneof(intern->msg, oneof);\n"
" upb_Message_WhichOneofByDef(intern->msg, oneof);\n"
" RETURN_STRING(field ? upb_FieldDef_Name(field) : \"\");\n"
"}\n",
"c_name", c_name, "name", oneof->name(), "camel_name",

View File

@ -37,7 +37,13 @@ class PROTOC_EXPORT Generator : public CodeGenerator {
std::string* error) const override;
uint64_t GetSupportedFeatures() const override {
return FEATURE_PROTO3_OPTIONAL;
return Feature::FEATURE_PROTO3_OPTIONAL;
}
Edition GetMinimumEdition() const override { return Edition::EDITION_PROTO2; }
Edition GetMaximumEdition() const override { return Edition::EDITION_2023; }
std::vector<const FieldDescriptor*> GetFeatureExtensions() const override {
return {};
}
private:

View File

@ -911,6 +911,10 @@ void GenerateRs(Context& ctx, const Descriptor& msg) {
$Msg::serialize$
}
pub fn to_owned(&self) -> $Msg$ {
$pb$::IntoProxied::into(*self, $pbi$::Private)
}
$accessor_fns_for_views$
}
@ -986,6 +990,10 @@ void GenerateRs(Context& ctx, const Descriptor& msg) {
$pb$::ViewProxy::as_view(self).serialize()
}
pub fn to_owned(&self) -> $Msg$ {
$pb$::ViewProxy::as_view(self).to_owned()
}
$get_upb_minitable$
$raw_arena_getter_for_msgmut$

View File

@ -620,6 +620,7 @@ DynamicMessageFactory::~DynamicMessageFactory() {
}
const Message* DynamicMessageFactory::GetPrototype(const Descriptor* type) {
ABSL_CHECK(type != nullptr);
absl::MutexLock lock(&prototypes_mutex_);
return GetPrototypeNoLock(type);
}

View File

@ -108,8 +108,8 @@ class PROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory {
// prototype, so these must be destroyed before the DynamicMessageFactory
// is destroyed.
//
// The given descriptor must outlive the returned message, and hence must
// outlive the DynamicMessageFactory.
// The given descriptor must be non-null and outlive the returned message, and
// hence must outlive the DynamicMessageFactory.
//
// The method is thread-safe.
const Message* GetPrototype(const Descriptor* type) override;

View File

@ -27,6 +27,7 @@
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "google/protobuf/map_lite_test_util.h"
#include "google/protobuf/map_lite_unittest.pb.h"
#include "google/protobuf/message_lite.h"
#include "google/protobuf/parse_context.h"
#include "google/protobuf/test_util_lite.h"
#include "google/protobuf/unittest_lite.pb.h"
@ -1325,6 +1326,92 @@ TEST(LiteBasicTest, CodedInputStreamRollback) {
}
}
// Two arbitary types
using CastType1 = protobuf_unittest::TestAllTypesLite;
using CastType2 = protobuf_unittest::TestPackedTypesLite;
TEST(LiteTest, DynamicCastToGenerated) {
CastType1 test_type_1;
MessageLite* test_type_1_pointer = &test_type_1;
EXPECT_EQ(&test_type_1,
DynamicCastToGenerated<CastType1>(test_type_1_pointer));
EXPECT_EQ(nullptr, DynamicCastToGenerated<CastType2>(test_type_1_pointer));
const MessageLite* test_type_1_pointer_const = &test_type_1;
EXPECT_EQ(&test_type_1,
DynamicCastToGenerated<const CastType1>(test_type_1_pointer_const));
EXPECT_EQ(nullptr,
DynamicCastToGenerated<const CastType2>(test_type_1_pointer_const));
MessageLite* test_type_1_pointer_nullptr = nullptr;
EXPECT_EQ(nullptr,
DynamicCastToGenerated<CastType1>(test_type_1_pointer_nullptr));
MessageLite& test_type_1_pointer_ref = test_type_1;
EXPECT_EQ(&test_type_1,
&DynamicCastToGenerated<CastType1>(test_type_1_pointer_ref));
const MessageLite& test_type_1_pointer_const_ref = test_type_1;
EXPECT_EQ(&test_type_1,
&DynamicCastToGenerated<CastType1>(test_type_1_pointer_const_ref));
}
#if GTEST_HAS_DEATH_TEST
TEST(LiteTest, DynamicCastToGeneratedInvalidReferenceType) {
CastType1 test_type_1;
const MessageLite& test_type_1_pointer_const_ref = test_type_1;
ASSERT_DEATH(DynamicCastToGenerated<CastType2>(test_type_1_pointer_const_ref),
"Cannot downcast " + test_type_1.GetTypeName() + " to " +
CastType2::default_instance().GetTypeName());
}
#endif // GTEST_HAS_DEATH_TEST
TEST(LiteTest, DownCastToGeneratedValidType) {
CastType1 test_type_1;
MessageLite* test_type_1_pointer = &test_type_1;
EXPECT_EQ(&test_type_1, DownCastToGenerated<CastType1>(test_type_1_pointer));
const MessageLite* test_type_1_pointer_const = &test_type_1;
EXPECT_EQ(&test_type_1,
DownCastToGenerated<const CastType1>(test_type_1_pointer_const));
MessageLite* test_type_1_pointer_nullptr = nullptr;
EXPECT_EQ(nullptr,
DownCastToGenerated<CastType1>(test_type_1_pointer_nullptr));
MessageLite& test_type_1_pointer_ref = test_type_1;
EXPECT_EQ(&test_type_1,
&DownCastToGenerated<CastType1>(test_type_1_pointer_ref));
const MessageLite& test_type_1_pointer_const_ref = test_type_1;
EXPECT_EQ(&test_type_1,
&DownCastToGenerated<CastType1>(test_type_1_pointer_const_ref));
}
#if GTEST_HAS_DEATH_TEST
TEST(LiteTest, DownCastToGeneratedInvalidPointerType) {
CastType1 test_type_1;
MessageLite* test_type_1_pointer = &test_type_1;
ASSERT_DEBUG_DEATH(DownCastToGenerated<CastType2>(test_type_1_pointer),
"Cannot downcast " + test_type_1.GetTypeName() + " to " +
CastType2::default_instance().GetTypeName());
}
TEST(LiteTest, DownCastToGeneratedInvalidReferenceType) {
CastType1 test_type_1;
MessageLite& test_type_1_pointer = test_type_1;
ASSERT_DEBUG_DEATH(DownCastToGenerated<CastType2>(test_type_1_pointer),
"Cannot downcast " + test_type_1.GetTypeName() + " to " +
CastType2::default_instance().GetTypeName());
}
#endif // GTEST_HAS_DEATH_TEST
} // namespace
} // namespace protobuf
} // namespace google

View File

@ -1424,90 +1424,6 @@ DECLARE_GET_REPEATED_FIELD(bool)
#undef DECLARE_GET_REPEATED_FIELD
// Tries to downcast this message to a generated message type. Returns nullptr
// if this class is not an instance of T. This works even if RTTI is disabled.
//
// This also has the effect of creating a strong reference to T that will
// prevent the linker from stripping it out at link time. This can be important
// if you are using a DynamicMessageFactory that delegates to the generated
// factory.
template <typename T>
const T* DynamicCastToGenerated(const Message* from) {
// Compile-time assert that T is a generated type that has a
// default_instance() accessor, but avoid actually calling it.
const T& (*get_default_instance)() = &T::default_instance;
(void)get_default_instance;
// Compile-time assert that T is a subclass of google::protobuf::Message.
const Message* unused = static_cast<T*>(nullptr);
(void)unused;
#if PROTOBUF_RTTI
internal::StrongReferenceToType<T>();
return dynamic_cast<const T*>(from);
#else
bool ok = from != nullptr &&
T::default_instance().GetReflection() == from->GetReflection();
return ok ? internal::DownCast<const T*>(from) : nullptr;
#endif
}
template <typename T>
T* DynamicCastToGenerated(Message* from) {
const Message* message_const = from;
return const_cast<T*>(DynamicCastToGenerated<T>(message_const));
}
// An overloaded version of DynamicCastToGenerated for downcasting references to
// base Message class. If the destination type T if the argument is not an
// instance of T and dynamic_cast returns nullptr, it terminates with an error.
template <typename T>
const T& DynamicCastToGenerated(const Message& from) {
const T* destination_message = DynamicCastToGenerated<T>(&from);
ABSL_CHECK(destination_message != nullptr)
<< "Cannot downcast " << from.GetTypeName() << " to "
<< T::default_instance().GetTypeName();
return *destination_message;
}
template <typename T>
T& DynamicCastToGenerated(Message& from) {
const Message& message_const = from;
const T& destination_message = DynamicCastToGenerated<T>(message_const);
return const_cast<T&>(destination_message);
}
// A lightweight function for downcasting base Message pointer to derived type.
// It should only be used when the caller is certain that the argument is of
// instance T and T is a type derived from base Message class.
template <typename T>
const T* DownCastToGenerated(const Message* from) {
internal::StrongReferenceToType<T>();
ABSL_DCHECK(DynamicCastToGenerated<T>(from) == from)
<< "Cannot downcast " << from->GetTypeName() << " to "
<< T::default_instance().GetTypeName();
return static_cast<const T*>(from);
}
template <typename T>
T* DownCastToGenerated(Message* from) {
const Message* message_const = from;
return const_cast<T*>(DownCastToGenerated<T>(message_const));
}
template <typename T>
const T& DownCastToGenerated(const Message& from) {
return *DownCastToGenerated<T>(&from);
}
template <typename T>
T& DownCastToGenerated(Message& from) {
const Message& message_const = from;
const T& destination_message = DownCastToGenerated<T>(message_const);
return const_cast<T&>(destination_message);
}
// Call this function to ensure that this message's reflection is linked into
// the binary:
//

View File

@ -21,6 +21,7 @@
#include <cstdint>
#include <iosfwd>
#include <string>
#include <type_traits>
#include "absl/base/attributes.h"
#include "absl/log/absl_check.h"
@ -53,6 +54,7 @@ class FastReflectionStringSetter;
class Reflection;
class Descriptor;
class AssignDescriptorsHelper;
class MessageLite;
namespace io {
@ -120,6 +122,9 @@ class PROTOBUF_EXPORT CachedSize {
#endif
};
// For MessageLite to friend.
class TypeId;
class SwapFieldHelper;
// See parse_context.h for explanation
@ -638,6 +643,15 @@ class PROTOBUF_EXPORT MessageLite {
// return a default table instead of a unique one.
virtual const ClassData* GetClassData() const = 0;
template <typename T>
static auto GetClassDataGenerated() {
// We could speed this up if needed by avoiding the function call.
// In LTO this is likely inlined, so it might not matter.
static_assert(
std::is_same<const T&, decltype(T::default_instance())>::value, "");
return T::default_instance().T::GetClassData();
}
internal::InternalMetadata _internal_metadata_;
// Return the cached size object as described by
@ -682,6 +696,7 @@ class PROTOBUF_EXPORT MessageLite {
friend class internal::LazyField;
friend class internal::SwapFieldHelper;
friend class internal::TcParser;
friend class internal::TypeId;
friend class internal::WeakFieldMap;
friend class internal::WireFormatLite;
@ -717,6 +732,32 @@ class PROTOBUF_EXPORT MessageLite {
namespace internal {
// A typeinfo equivalent for protobuf message types. Used for
// DynamicCastToGenerated.
// We might make this class public later on to have an alternative to
// `std::type_info` that works when RTTI is disabled.
class TypeId {
public:
constexpr explicit TypeId(const MessageLite::ClassData* data) : data_(data) {}
friend constexpr bool operator==(TypeId a, TypeId b) {
return a.data_ == b.data_;
}
friend constexpr bool operator!=(TypeId a, TypeId b) { return !(a == b); }
static TypeId Get(const MessageLite& msg) {
return TypeId(msg.GetClassData());
}
template <typename T>
static TypeId Get() {
return TypeId(MessageLite::GetClassDataGenerated<T>());
}
private:
const MessageLite::ClassData* data_;
};
template <bool alias>
bool MergeFromImpl(absl::string_view input, MessageLite* msg,
const internal::TcParseTableBase* tc_table,
@ -820,6 +861,83 @@ T* OnShutdownDelete(T* p) {
std::string ShortFormat(const MessageLite& message_lite);
std::string Utf8Format(const MessageLite& message_lite);
// Tries to downcast this message to a generated message type. Returns nullptr
// if this class is not an instance of T. This works even if RTTI is disabled.
//
// This also has the effect of creating a strong reference to T that will
// prevent the linker from stripping it out at link time. This can be important
// if you are using a DynamicMessageFactory that delegates to the generated
// factory.
template <typename T>
const T* DynamicCastToGenerated(const MessageLite* from) {
static_assert(std::is_base_of<MessageLite, T>::value, "");
internal::StrongReferenceToType<T>();
// We might avoid the call to T::GetClassData() altogether if T were to
// expose the class data pointer.
if (from == nullptr ||
internal::TypeId::Get<T>() != internal::TypeId::Get(*from)) {
return nullptr;
}
return static_cast<const T*>(from);
}
template <typename T>
const T* DynamicCastToGenerated(const MessageLite* from);
template <typename T>
T* DynamicCastToGenerated(MessageLite* from) {
return const_cast<T*>(
DynamicCastToGenerated<T>(static_cast<const MessageLite*>(from)));
}
// An overloaded version of DynamicCastToGenerated for downcasting references to
// base Message class. If the argument is not an instance of T, it terminates
// with an error.
template <typename T>
const T& DynamicCastToGenerated(const MessageLite& from) {
const T* destination_message = DynamicCastToGenerated<T>(&from);
ABSL_CHECK(destination_message != nullptr)
<< "Cannot downcast " << from.GetTypeName() << " to "
<< T::default_instance().GetTypeName();
return *destination_message;
}
template <typename T>
T& DynamicCastToGenerated(MessageLite& from) {
return const_cast<T&>(
DynamicCastToGenerated<T>(static_cast<const MessageLite&>(from)));
}
// A lightweight function for downcasting base MessageLite pointer to derived
// type. It should only be used when the caller is certain that the argument is
// of instance T and T is a generated message type.
template <typename T>
const T* DownCastToGenerated(const MessageLite* from) {
internal::StrongReferenceToType<T>();
ABSL_DCHECK(DynamicCastToGenerated<T>(from) == from)
<< "Cannot downcast " << from->GetTypeName() << " to "
<< T::default_instance().GetTypeName();
return static_cast<const T*>(from);
}
template <typename T>
T* DownCastToGenerated(MessageLite* from) {
return const_cast<T*>(
DownCastToGenerated<T>(static_cast<const MessageLite*>(from)));
}
template <typename T>
const T& DownCastToGenerated(const MessageLite& from) {
return *DownCastToGenerated<T>(&from);
}
template <typename T>
T& DownCastToGenerated(MessageLite& from) {
return *DownCastToGenerated<T>(&from);
}
} // namespace protobuf
} // namespace google

View File

@ -753,35 +753,35 @@ TEST(MESSAGE_TEST_NAME, InitializationErrorString) {
TEST(MESSAGE_TEST_NAME, DynamicCastToGenerated) {
UNITTEST::TestAllTypes test_all_types;
Message* test_all_types_pointer = &test_all_types;
MessageLite* test_all_types_pointer = &test_all_types;
EXPECT_EQ(&test_all_types, DynamicCastToGenerated<UNITTEST::TestAllTypes>(
test_all_types_pointer));
EXPECT_EQ(nullptr, DynamicCastToGenerated<UNITTEST::TestRequired>(
test_all_types_pointer));
const Message* test_all_types_pointer_const = &test_all_types;
const MessageLite* test_all_types_pointer_const = &test_all_types;
EXPECT_EQ(&test_all_types,
DynamicCastToGenerated<const UNITTEST::TestAllTypes>(
test_all_types_pointer_const));
EXPECT_EQ(nullptr, DynamicCastToGenerated<const UNITTEST::TestRequired>(
test_all_types_pointer_const));
Message* test_all_types_pointer_nullptr = nullptr;
MessageLite* test_all_types_pointer_nullptr = nullptr;
EXPECT_EQ(nullptr, DynamicCastToGenerated<UNITTEST::TestAllTypes>(
test_all_types_pointer_nullptr));
Message& test_all_types_pointer_ref = test_all_types;
MessageLite& test_all_types_pointer_ref = test_all_types;
EXPECT_EQ(&test_all_types, &DynamicCastToGenerated<UNITTEST::TestAllTypes>(
test_all_types_pointer_ref));
const Message& test_all_types_pointer_const_ref = test_all_types;
const MessageLite& test_all_types_pointer_const_ref = test_all_types;
EXPECT_EQ(&test_all_types, &DynamicCastToGenerated<UNITTEST::TestAllTypes>(
test_all_types_pointer_const_ref));
}
TEST(MESSAGE_TEST_NAME, DynamicCastToGeneratedInvalidReferenceType) {
UNITTEST::TestAllTypes test_all_types;
const Message& test_all_types_pointer_const_ref = test_all_types;
const MessageLite& test_all_types_pointer_const_ref = test_all_types;
ASSERT_DEATH(DynamicCastToGenerated<UNITTEST::TestRequired>(
test_all_types_pointer_const_ref),
"Cannot downcast " + test_all_types.GetTypeName() + " to " +
@ -791,23 +791,23 @@ TEST(MESSAGE_TEST_NAME, DynamicCastToGeneratedInvalidReferenceType) {
TEST(MESSAGE_TEST_NAME, DownCastToGeneratedValidType) {
UNITTEST::TestAllTypes test_all_types;
Message* test_all_types_pointer = &test_all_types;
MessageLite* test_all_types_pointer = &test_all_types;
EXPECT_EQ(&test_all_types, DownCastToGenerated<UNITTEST::TestAllTypes>(
test_all_types_pointer));
const Message* test_all_types_pointer_const = &test_all_types;
const MessageLite* test_all_types_pointer_const = &test_all_types;
EXPECT_EQ(&test_all_types, DownCastToGenerated<const UNITTEST::TestAllTypes>(
test_all_types_pointer_const));
Message* test_all_types_pointer_nullptr = nullptr;
MessageLite* test_all_types_pointer_nullptr = nullptr;
EXPECT_EQ(nullptr, DownCastToGenerated<UNITTEST::TestAllTypes>(
test_all_types_pointer_nullptr));
Message& test_all_types_pointer_ref = test_all_types;
MessageLite& test_all_types_pointer_ref = test_all_types;
EXPECT_EQ(&test_all_types, &DownCastToGenerated<UNITTEST::TestAllTypes>(
test_all_types_pointer_ref));
const Message& test_all_types_pointer_const_ref = test_all_types;
const MessageLite& test_all_types_pointer_const_ref = test_all_types;
EXPECT_EQ(&test_all_types, &DownCastToGenerated<UNITTEST::TestAllTypes>(
test_all_types_pointer_const_ref));
}
@ -815,7 +815,7 @@ TEST(MESSAGE_TEST_NAME, DownCastToGeneratedValidType) {
TEST(MESSAGE_TEST_NAME, DownCastToGeneratedInvalidPointerType) {
UNITTEST::TestAllTypes test_all_types;
Message* test_all_types_pointer = &test_all_types;
MessageLite* test_all_types_pointer = &test_all_types;
ASSERT_DEBUG_DEATH(
DownCastToGenerated<UNITTEST::TestRequired>(test_all_types_pointer),
@ -826,7 +826,7 @@ TEST(MESSAGE_TEST_NAME, DownCastToGeneratedInvalidPointerType) {
TEST(MESSAGE_TEST_NAME, DownCastToGeneratedInvalidReferenceType) {
UNITTEST::TestAllTypes test_all_types;
Message& test_all_types_pointer = test_all_types;
MessageLite& test_all_types_pointer = test_all_types;
ASSERT_DEBUG_DEATH(
DownCastToGenerated<UNITTEST::TestRequired>(test_all_types_pointer),

View File

@ -403,39 +403,6 @@ static_assert(PROTOBUF_ABSL_MIN(20230125, 3),
#error PROTOBUF_FORCE_ALLOCATION_ON_CONSTRUCTION was previously defined
#endif
// Specify memory alignment for structs, classes, etc.
// Use like:
// class PROTOBUF_ALIGNAS(16) MyClass { ... }
// PROTOBUF_ALIGNAS(16) int array[4];
//
// In most places you can use the C++11 keyword "alignas", which is preferred.
//
// But compilers have trouble mixing __attribute__((...)) syntax with
// alignas(...) syntax.
//
// Doesn't work in clang or gcc:
// struct alignas(16) __attribute__((packed)) S { char c; };
// Works in clang but not gcc:
// struct __attribute__((packed)) alignas(16) S2 { char c; };
// Works in clang and gcc:
// struct alignas(16) S3 { char c; } __attribute__((packed));
//
// There are also some attributes that must be specified *before* a class
// definition: visibility (used for exporting functions/classes) is one of
// these attributes. This means that it is not possible to use alignas() with a
// class that is marked as exported.
#ifdef PROTOBUF_ALIGNAS
#error PROTOBUF_ALIGNAS was previously defined
#endif
#if defined(_MSC_VER)
#define PROTOBUF_ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
#elif defined(__GNUC__)
#define PROTOBUF_ALIGNAS(byte_alignment) \
__attribute__((aligned(byte_alignment)))
#else
#define PROTOBUF_ALIGNAS(byte_alignment) alignas(byte_alignment)
#endif
#ifdef PROTOBUF_THREAD_LOCAL
#error PROTOBUF_THREAD_LOCAL was previously defined
#endif
@ -597,13 +564,6 @@ static_assert(PROTOBUF_ABSL_MIN(20230125, 3),
#define PROTOBUF_TSAN_DECLARE_MEMBER
#endif
#ifdef PROTOBUF_USE_TABLE_PARSER_ON_REFLECTION
#error PROTOBUF_USE_TABLE_PARSER_ON_REFLECTION was previously defined
#endif
#if !defined(PROTOBUF_TEMPORARY_DISABLE_TABLE_PARSER_ON_REFLECTION)
#define PROTOBUF_USE_TABLE_PARSER_ON_REFLECTION 1
#endif // PROTOBUF_ENABLE_FORCE_ALLOCATION_ON_CONSTRUCTION
// Note that this is performance sensitive: changing the parameters will change
// the registers used by the ABI calling convention, which subsequently affects
// register selection logic inside the function.

View File

@ -50,7 +50,6 @@
#undef PROTOBUF_ASSUME
#undef PROTOBUF_EXPORT_TEMPLATE_DECLARE
#undef PROTOBUF_EXPORT_TEMPLATE_DEFINE
#undef PROTOBUF_ALIGNAS
#undef PROTOBUF_THREAD_LOCAL
#undef PROTOBUF_CONSTINIT
#undef PROTOBUF_CONSTEXPR
@ -65,7 +64,6 @@
#undef PROTOBUF_MSAN
#undef PROTOBUF_TSAN
#undef PROTOBUF_TSAN_DECLARE_MEMBER
#undef PROTOBUF_USE_TABLE_PARSER_ON_REFLECTION
#undef PROTOBUF_BUILTIN_CONSTANT_P
#undef PROTOBUF_DESCRIPTOR_WEAK_MESSAGES_ALLOWED
#undef PROTOBUF_PREFETCH_PARSE_TABLE

View File

@ -766,6 +766,44 @@ struct WireFormat::MessageSetParser {
const Reflection* reflection;
};
static const char* HandleMessage(Message* msg, const char* ptr,
internal::ParseContext* ctx, uint64_t tag,
const Reflection* reflection,
const FieldDescriptor* field) {
Message* sub_message;
if (field->is_repeated()) {
sub_message = reflection->AddMessage(msg, field, ctx->data().factory);
} else {
sub_message = reflection->MutableMessage(msg, field, ctx->data().factory);
}
if (WireFormatLite::GetTagWireType(tag) ==
WireFormatLite::WIRETYPE_START_GROUP) {
return ctx->ParseGroup(sub_message, ptr, tag);
} else {
ABSL_DCHECK(WireFormatLite::GetTagWireType(tag) ==
WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
}
ptr = ctx->ParseMessage(sub_message, ptr);
// For map entries, if the value is an unknown enum we have to push it
// into the unknown field set and remove it from the list.
if (ptr != nullptr && field->is_map()) {
auto* value_field = field->message_type()->map_value();
auto* enum_type = value_field->enum_type();
if (enum_type != nullptr &&
!internal::cpp::HasPreservingUnknownEnumSemantics(value_field) &&
enum_type->FindValueByNumber(sub_message->GetReflection()->GetEnumValue(
*sub_message, value_field)) == nullptr) {
reflection->MutableUnknownFields(msg)->AddLengthDelimited(
field->number(), sub_message->SerializeAsString());
reflection->RemoveLast(msg, field);
}
}
return ptr;
}
const char* WireFormat::_InternalParse(Message* msg, const char* ptr,
internal::ParseContext* ctx) {
const Descriptor* descriptor = msg->GetDescriptor();
@ -995,46 +1033,9 @@ const char* WireFormat::_InternalParseAndMergeField(
return ptr;
}
case FieldDescriptor::TYPE_GROUP: {
Message* sub_message;
if (field->is_repeated()) {
sub_message = reflection->AddMessage(msg, field, ctx->data().factory);
} else {
sub_message =
reflection->MutableMessage(msg, field, ctx->data().factory);
}
return ctx->ParseGroup(sub_message, ptr, tag);
}
case FieldDescriptor::TYPE_MESSAGE: {
Message* sub_message;
if (field->is_repeated()) {
sub_message = reflection->AddMessage(msg, field, ctx->data().factory);
} else {
sub_message =
reflection->MutableMessage(msg, field, ctx->data().factory);
}
ptr = ctx->ParseMessage(sub_message, ptr);
// For map entries, if the value is an unknown enum we have to push it
// into the unknown field set and remove it from the list.
if (ptr != nullptr && field->is_map()) {
auto* value_field = field->message_type()->map_value();
auto* enum_type = value_field->enum_type();
if (enum_type != nullptr &&
!internal::cpp::HasPreservingUnknownEnumSemantics(value_field) &&
enum_type->FindValueByNumber(
sub_message->GetReflection()->GetEnumValue(
*sub_message, value_field)) == nullptr) {
reflection->MutableUnknownFields(msg)->AddLengthDelimited(
field->number(), sub_message->SerializeAsString());
reflection->RemoveLast(msg, field);
}
}
return ptr;
}
case FieldDescriptor::TYPE_MESSAGE:
case FieldDescriptor::TYPE_GROUP:
return HandleMessage(msg, ptr, ctx, tag, reflection, field);
}
// GCC 8 complains about control reaching end of non-void function here.

View File

@ -957,7 +957,7 @@ static void jsondec_field(jsondec* d, upb_Message* msg,
}
if (upb_FieldDef_RealContainingOneof(f) &&
upb_Message_WhichOneof(msg, upb_FieldDef_ContainingOneof(f))) {
upb_Message_WhichOneofByDef(msg, upb_FieldDef_ContainingOneof(f))) {
jsondec_err(d, "More than one field for this oneof.");
}

View File

@ -8,30 +8,17 @@
#ifndef UPB_MESSAGE_ACCESSORS_H_
#define UPB_MESSAGE_ACCESSORS_H_
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "upb/base/descriptor_constants.h"
#include "upb/base/string_view.h"
#include "upb/mem/arena.h"
#include "upb/message/array.h"
#include "upb/message/internal/accessors.h"
#include "upb/message/internal/array.h"
#include "upb/message/internal/map.h"
#include "upb/message/internal/message.h"
#include "upb/message/internal/tagged_ptr.h"
#include "upb/message/map.h"
#include "upb/message/message.h"
#include "upb/message/tagged_ptr.h"
#include "upb/message/value.h"
#include "upb/mini_table/enum.h"
#include "upb/mini_table/extension.h"
#include "upb/mini_table/field.h"
#include "upb/mini_table/internal/field.h"
#include "upb/mini_table/internal/message.h"
#include "upb/mini_table/message.h"
#include "upb/mini_table/sub.h"
// Must be last.
#include "upb/port/def.inc"
@ -76,6 +63,10 @@ UPB_API_INLINE upb_MessageValue
upb_Message_GetField(const upb_Message* msg, const upb_MiniTableField* f,
upb_MessageValue default_val);
UPB_API_INLINE upb_TaggedMessagePtr upb_Message_GetTaggedMessagePtr(
const upb_Message* msg, const upb_MiniTableField* field,
upb_Message* default_val);
UPB_API_INLINE const upb_Array* upb_Message_GetArray(
const upb_Message* msg, const upb_MiniTableField* f);
@ -102,12 +93,18 @@ UPB_API_INLINE int64_t upb_Message_GetInt64(const upb_Message* msg,
UPB_API_INLINE const upb_Map* upb_Message_GetMap(const upb_Message* msg,
const upb_MiniTableField* f);
UPB_API_INLINE const upb_Message* upb_Message_GetMessage(
const upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Array* upb_Message_GetMutableArray(
upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Map* upb_Message_GetMutableMap(upb_Message* msg,
const upb_MiniTableField* f);
UPB_API_INLINE upb_Message* upb_Message_GetMutableMessage(
upb_Message* msg, const upb_MiniTableField* f);
UPB_API_INLINE upb_Array* upb_Message_GetOrCreateMutableArray(
upb_Message* msg, const upb_MiniTableField* f, upb_Arena* arena);
@ -155,6 +152,10 @@ UPB_API_INLINE bool upb_Message_SetInt64(upb_Message* msg,
const upb_MiniTableField* f,
int64_t value, upb_Arena* a);
UPB_API_INLINE void upb_Message_SetMessage(upb_Message* msg,
const upb_MiniTableField* f,
upb_Message* value);
UPB_API_INLINE bool upb_Message_SetString(upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value, upb_Arena* a);
@ -167,55 +168,6 @@ UPB_API_INLINE bool upb_Message_SetUInt64(upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value, upb_Arena* a);
UPB_API_INLINE upb_TaggedMessagePtr upb_Message_GetTaggedMessagePtr(
const upb_Message* msg, const upb_MiniTableField* field,
upb_Message* default_val) {
UPB_ASSUME(upb_MiniTableField_CType(field) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(field) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(field));
upb_TaggedMessagePtr tagged;
_upb_Message_GetNonExtensionField(msg, field, &default_val, &tagged);
return tagged;
}
UPB_API_INLINE const upb_Message* upb_Message_GetMessage(
const upb_Message* msg, const upb_MiniTableField* field) {
upb_TaggedMessagePtr tagged =
upb_Message_GetTaggedMessagePtr(msg, field, NULL);
return upb_TaggedMessagePtr_GetNonEmptyMessage(tagged);
}
UPB_API_INLINE upb_Message* upb_Message_GetMutableMessage(
upb_Message* msg, const upb_MiniTableField* field) {
return (upb_Message*)upb_Message_GetMessage(msg, field);
}
// For internal use only; users cannot set tagged messages because only the
// parser and the message copier are allowed to directly create an empty
// message.
UPB_INLINE void UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)(
struct upb_Message* msg, const upb_MiniTable* mini_table,
const upb_MiniTableField* f, upb_TaggedMessagePtr sub_message) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_Message_SetBaseField(msg, f, &sub_message);
}
// Sets the value of a message-typed field. The `mini_table` and `field`
// parameters belong to `msg`, not `sub_message`. The mini_tables of `msg` and
// `sub_message` must have been linked for this to work correctly.
UPB_API_INLINE void upb_Message_SetMessage(upb_Message* msg,
const upb_MiniTable* mini_table,
const upb_MiniTableField* field,
upb_Message* sub_message) {
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(msg, mini_table, field,
UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(sub_message, false));
}
UPB_API_INLINE void* upb_Message_ResizeArrayUninitialized(
upb_Message* msg, const upb_MiniTableField* f, size_t size,
upb_Arena* arena);

View File

@ -329,10 +329,8 @@ TEST(GeneratedCode, SubMessage) {
arena));
upb_Message_SetInt32(new_nested_message, nested_message_a_field, 123,
nullptr);
upb_Message_SetMessage(
UPB_UPCAST(msg),
&protobuf_0test_0messages__proto2__TestAllTypesProto2_msg_init,
optional_message_field, new_nested_message);
upb_Message_SetMessage(UPB_UPCAST(msg), optional_message_field,
new_nested_message);
upb_Message* mutable_message = upb_Message_GetOrCreateMutableMessage(
UPB_UPCAST(msg),

View File

@ -215,7 +215,7 @@ upb_Message* _upb_Message_Copy(upb_Message* dst, const upb_Message* src,
return NULL;
}
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(dst, mini_table, field,
(dst, field,
UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(dst_sub_message,
is_empty));
}

View File

@ -108,10 +108,8 @@ TEST(GeneratedCode, DeepCloneMessageSubMessage) {
source_arena);
protobuf_test_messages_proto2_TestAllTypesProto2_NestedMessage_set_a(
nested, kTestNestedInt32);
upb_Message_SetMessage(
UPB_UPCAST(msg),
&protobuf_0test_0messages__proto2__TestAllTypesProto2_msg_init,
nested_message_field, UPB_UPCAST(nested));
upb_Message_SetMessage(UPB_UPCAST(msg), nested_message_field,
UPB_UPCAST(nested));
upb_Arena* arena = upb_Arena_New();
protobuf_test_messages_proto2_TestAllTypesProto2* clone =
(protobuf_test_messages_proto2_TestAllTypesProto2*)upb_Message_DeepClone(

View File

@ -220,7 +220,6 @@ UPB_INLINE bool UPB_PRIVATE(_upb_MiniTableField_DataIsZero)(
// const upb_MiniTableField* field,
// bool value, upb_Arena* a) {
// UPB_ASSUME(field->UPB_PRIVATE(descriptortype) == kUpb_FieldType_Bool);
// UPB_ASSUME(upb_MiniTableField_IsScalar(field));
// UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(field) ==
// kUpb_FieldRep_1Byte);
// upb_Message_SetField(msg, field, &value, a);
@ -351,8 +350,8 @@ UPB_API_INLINE bool upb_Message_GetBool(const struct upb_Message* msg,
const upb_MiniTableField* f,
bool default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
upb_MessageValue def;
def.bool_val = default_val;
return upb_Message_GetField(msg, f, def).bool_val;
@ -362,8 +361,8 @@ UPB_API_INLINE double upb_Message_GetDouble(const struct upb_Message* msg,
const upb_MiniTableField* f,
double default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.double_val = default_val;
@ -374,8 +373,8 @@ UPB_API_INLINE float upb_Message_GetFloat(const struct upb_Message* msg,
const upb_MiniTableField* f,
float default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.float_val = default_val;
@ -387,8 +386,8 @@ UPB_API_INLINE int32_t upb_Message_GetInt32(const struct upb_Message* msg,
int32_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.int32_val = default_val;
@ -399,8 +398,8 @@ UPB_API_INLINE int64_t upb_Message_GetInt64(const struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.int64_val = default_val;
@ -429,6 +428,37 @@ UPB_API_INLINE const struct upb_Map* upb_Message_GetMap(
return ret;
}
UPB_API_INLINE uintptr_t upb_Message_GetTaggedMessagePtr(
const struct upb_Message* msg, const upb_MiniTableField* f,
struct upb_Message* default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
uintptr_t tagged;
_upb_Message_GetNonExtensionField(msg, f, &default_val, &tagged);
return tagged;
}
// For internal use only; users cannot set tagged messages because only the
// parser and the message copier are allowed to directly create an empty
// message.
UPB_INLINE void UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)(
struct upb_Message* msg, const upb_MiniTableField* f,
uintptr_t sub_message) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Message);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
UPB_SIZE(kUpb_FieldRep_4Byte, kUpb_FieldRep_8Byte));
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_Message_SetBaseField(msg, f, &sub_message);
}
UPB_API_INLINE const struct upb_Message* upb_Message_GetMessage(
const struct upb_Message* msg, const upb_MiniTableField* f) {
uintptr_t tagged = upb_Message_GetTaggedMessagePtr(msg, f, NULL);
return upb_TaggedMessagePtr_GetNonEmptyMessage(tagged);
}
UPB_API_INLINE upb_Array* upb_Message_GetMutableArray(
struct upb_Message* msg, const upb_MiniTableField* f) {
UPB_PRIVATE(_upb_MiniTableField_CheckIsArray)(f);
@ -440,6 +470,11 @@ UPB_API_INLINE struct upb_Map* upb_Message_GetMutableMap(
return (struct upb_Map*)upb_Message_GetMap(msg, f);
}
UPB_API_INLINE struct upb_Message* upb_Message_GetMutableMessage(
struct upb_Message* msg, const upb_MiniTableField* f) {
return (struct upb_Message*)upb_Message_GetMessage(msg, f);
}
UPB_API_INLINE upb_Array* upb_Message_GetOrCreateMutableArray(
struct upb_Message* msg, const upb_MiniTableField* f, upb_Arena* arena) {
UPB_ASSERT(arena);
@ -515,7 +550,6 @@ upb_Message_GetString(const struct upb_Message* msg,
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue def;
def.str_val = default_val;
@ -526,8 +560,8 @@ UPB_API_INLINE uint32_t upb_Message_GetUInt32(const struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_MessageValue def;
def.uint32_val = default_val;
@ -538,23 +572,89 @@ UPB_API_INLINE uint64_t upb_Message_GetUInt64(const struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t default_val) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_MessageValue def;
def.uint64_val = default_val;
return upb_Message_GetField(msg, f, def).uint64_val;
}
UPB_API_INLINE bool upb_Message_SetBool(struct upb_Message* msg,
const upb_MiniTableField* f, bool value,
upb_Arena* a) {
// BaseField Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE void upb_Message_SetBaseFieldBool(struct upb_Message* msg,
const upb_MiniTableField* f,
bool value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.bool_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_1Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldDouble(struct upb_Message* msg,
const upb_MiniTableField* f,
double value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldFloat(struct upb_Message* msg,
const upb_MiniTableField* f,
float value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
int32_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldString(struct upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_String ||
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldUInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetBaseFieldUInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
upb_Message_SetBaseField(msg, f, &value);
}
UPB_API_INLINE void upb_Message_SetClosedEnum(
@ -562,55 +662,141 @@ UPB_API_INLINE void upb_Message_SetClosedEnum(
const upb_MiniTableField* f, int32_t value) {
UPB_ASSERT(upb_MiniTableField_IsClosedEnum(f));
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
UPB_ASSERT(upb_MiniTableEnum_CheckValue(
upb_MiniTable_GetSubEnumTable(msg_mini_table, f), value));
upb_Message_SetBaseField(msg, f, &value);
}
// Extension Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE bool upb_Message_SetExtensionBool(
struct upb_Message* msg, const upb_MiniTableExtension* e, bool value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Bool);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_1Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionDouble(
struct upb_Message* msg, const upb_MiniTableExtension* e, double value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionFloat(
struct upb_Message* msg, const upb_MiniTableExtension* e, float value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionInt32(
struct upb_Message* msg, const upb_MiniTableExtension* e, int32_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Int32 ||
upb_MiniTableExtension_CType(e) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionInt64(
struct upb_Message* msg, const upb_MiniTableExtension* e, int64_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionString(
struct upb_Message* msg, const upb_MiniTableExtension* e,
upb_StringView value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_String ||
upb_MiniTableExtension_CType(e) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_StringView);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionUInt32(
struct upb_Message* msg, const upb_MiniTableExtension* e, uint32_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_4Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
UPB_API_INLINE bool upb_Message_SetExtensionUInt64(
struct upb_Message* msg, const upb_MiniTableExtension* e, uint64_t value,
upb_Arena* a) {
UPB_ASSUME(upb_MiniTableExtension_CType(e) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(e) ==
kUpb_FieldRep_8Byte);
return upb_Message_SetExtension(msg, e, &value, a);
}
// Universal Setters ///////////////////////////////////////////////////////////
UPB_API_INLINE bool upb_Message_SetBool(struct upb_Message* msg,
const upb_MiniTableField* f, bool value,
upb_Arena* a) {
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionBool(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldBool(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetDouble(struct upb_Message* msg,
const upb_MiniTableField* f,
double value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Double);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.double_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionDouble(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldDouble(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetFloat(struct upb_Message* msg,
const upb_MiniTableField* f,
float value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Float);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.float_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionFloat(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldFloat(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
int32_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int32 ||
upb_MiniTableField_CType(f) == kUpb_CType_Enum);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.int32_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionInt32(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldInt32(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
int64_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_Int64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.int64_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionInt64(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldInt64(msg, f, value), true);
}
// Sets the value of a message-typed field. The mini_tables of `msg` and
// `value` must have been linked for this to work correctly.
UPB_API_INLINE void upb_Message_SetMessage(struct upb_Message* msg,
const upb_MiniTableField* f,
struct upb_Message* value) {
UPB_PRIVATE(_upb_Message_SetTaggedMessagePtr)
(msg, f, UPB_PRIVATE(_upb_TaggedMessagePtr_Pack)(value, false));
}
// Sets the value of a `string` or `bytes` field. The bytes of the value are not
@ -620,36 +806,28 @@ UPB_API_INLINE bool upb_Message_SetInt64(struct upb_Message* msg,
UPB_API_INLINE bool upb_Message_SetString(struct upb_Message* msg,
const upb_MiniTableField* f,
upb_StringView value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_String ||
upb_MiniTableField_CType(f) == kUpb_CType_Bytes);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) ==
kUpb_FieldRep_StringView);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.str_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionString(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldString(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetUInt32(struct upb_Message* msg,
const upb_MiniTableField* f,
uint32_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt32);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_4Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.uint32_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionUInt32(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldUInt32(msg, f, value), true);
}
UPB_API_INLINE bool upb_Message_SetUInt64(struct upb_Message* msg,
const upb_MiniTableField* f,
uint64_t value, upb_Arena* a) {
UPB_ASSUME(upb_MiniTableField_CType(f) == kUpb_CType_UInt64);
UPB_ASSUME(UPB_PRIVATE(_upb_MiniTableField_GetRep)(f) == kUpb_FieldRep_8Byte);
UPB_ASSUME(upb_MiniTableField_IsScalar(f));
upb_MessageValue val;
val.uint64_val = value;
return UPB_PRIVATE(_upb_Message_SetField)(msg, f, val, a);
return upb_MiniTableField_IsExtension(f)
? upb_Message_SetExtensionUInt64(
msg, (const upb_MiniTableExtension*)f, value, a)
: (upb_Message_SetBaseFieldUInt64(msg, f, value), true);
}
UPB_API_INLINE void upb_Message_Clear(struct upb_Message* msg,

View File

@ -188,7 +188,7 @@ upb_DecodeStatus upb_Message_PromoteMessage(upb_Message* parent,
upb_Message_PromoteOne(&tagged, sub_table, decode_options, arena);
if (ret == kUpb_DecodeStatus_Ok) {
*promoted = upb_TaggedMessagePtr_GetNonEmptyMessage(tagged);
upb_Message_SetMessage(parent, mini_table, field, *promoted);
upb_Message_SetMessage(parent, field, *promoted);
}
return ret;
}
@ -280,7 +280,7 @@ upb_UnknownToMessageRet upb_MiniTable_PromoteUnknownToMessage(
if (is_oneof) {
UPB_PRIVATE(_upb_Message_SetOneofCase)(msg, field);
}
upb_Message_SetMessage(msg, mini_table, field, message);
upb_Message_SetMessage(msg, field, message);
ret.message = message;
}
return ret;

View File

@ -8,6 +8,7 @@
#ifndef UPB_MINI_TABLE_INTERNAL_EXTENSION_H_
#define UPB_MINI_TABLE_INTERNAL_EXTENSION_H_
#include <stddef.h>
#include <stdint.h>
#include "upb/base/descriptor_constants.h"
@ -41,6 +42,9 @@ upb_MiniTableExtension_Number(const struct upb_MiniTableExtension* e) {
UPB_API_INLINE const struct upb_MiniTable* upb_MiniTableExtension_GetSubMessage(
const struct upb_MiniTableExtension* e) {
if (upb_MiniTableExtension_CType(e) != kUpb_CType_Message) {
return NULL;
}
return upb_MiniTableSub_Message(e->UPB_PRIVATE(sub));
}
@ -49,6 +53,11 @@ UPB_API_INLINE void upb_MiniTableExtension_SetSubMessage(
e->UPB_PRIVATE(sub).UPB_PRIVATE(submsg) = m;
}
UPB_INLINE upb_FieldRep UPB_PRIVATE(_upb_MiniTableExtension_GetRep)(
const struct upb_MiniTableExtension* e) {
return UPB_PRIVATE(_upb_MiniTableField_GetRep)(&e->UPB_PRIVATE(field));
}
#ifdef __cplusplus
} /* extern "C" */
#endif

View File

@ -41,8 +41,8 @@ bool upb_Message_HasFieldByDef(const upb_Message* msg, const upb_FieldDef* f) {
}
}
const upb_FieldDef* upb_Message_WhichOneof(const upb_Message* msg,
const upb_OneofDef* o) {
const upb_FieldDef* upb_Message_WhichOneofByDef(const upb_Message* msg,
const upb_OneofDef* o) {
const upb_FieldDef* f = upb_OneofDef_Field(o, 0);
if (upb_OneofDef_IsSynthetic(o)) {
UPB_ASSERT(upb_OneofDef_FieldCount(o) == 1);
@ -56,6 +56,14 @@ const upb_FieldDef* upb_Message_WhichOneof(const upb_Message* msg,
}
}
const upb_MiniTableField* upb_Message_WhichOneof(const upb_Message* msg,
const upb_OneofDef* o) {
const upb_FieldDef* f = upb_OneofDef_Field(o, 0);
// Question for Haberman: should we do anything if synthetic?
// if (upb_OneofDef_IsSynthetic(o)) {...}
return upb_FieldDef_MiniTable(f);
}
upb_MessageValue upb_Message_GetFieldByDef(const upb_Message* msg,
const upb_FieldDef* f) {
upb_MessageValue default_val = upb_FieldDef_Default(f);

View File

@ -30,8 +30,11 @@ UPB_API upb_MutableMessageValue upb_Message_Mutable(upb_Message* msg,
upb_Arena* a);
// Returns the field that is set in the oneof, or NULL if none are set.
UPB_API const upb_FieldDef* upb_Message_WhichOneof(const upb_Message* msg,
const upb_OneofDef* o);
UPB_API const upb_FieldDef* upb_Message_WhichOneofByDef(const upb_Message* msg,
const upb_OneofDef* o);
UPB_API const upb_MiniTableField* upb_Message_WhichOneOf(const upb_Message* msg,
const upb_OneofDef* o);
// Clear all data and unknown fields.
void upb_Message_ClearByDef(upb_Message* msg, const upb_MessageDef* m);