Implement _opt for messages

Add convenience _opt for singular message fields.
Users can detect if the message is set or unset, and unwrap via into_inner.

PiperOrigin-RevId: 602749065
pull/15600/head
Hong Shin 1 year ago committed by Copybara-Service
parent f4511fda5a
commit 7e1316ca81
  1. 8
      rust/test/shared/BUILD
  2. 20
      rust/test/shared/accessors_test.rs
  3. 1
      rust/test/shared/simple_nested_test.rs
  4. 13
      src/google/protobuf/compiler/rust/accessors/singular_message.cc

@ -363,11 +363,15 @@ rust_test(
rust_test(
name = "simple_nested_cpp_test",
srcs = ["simple_nested_test.rs"],
aliases = {
"//rust:protobuf_cpp": "protobuf",
},
tags = [
# TODO: Enable testing on arm once we support sanitizers for Rust on Arm.
"not_build:arm",
],
deps = [
"//rust:protobuf_cpp",
"//rust/test:nested_cc_rust_proto",
"@crate_index//:googletest",
],
@ -376,11 +380,15 @@ rust_test(
rust_test(
name = "simple_nested_upb_test",
srcs = ["simple_nested_test.rs"],
aliases = {
"//rust:protobuf_upb": "protobuf",
},
tags = [
# TODO: Enable testing on arm once we support sanitizers for Rust on Arm.
"not_build:arm",
],
deps = [
"//rust:protobuf_upb",
"//rust/test:nested_upb_rust_proto",
"@crate_index//:googletest",
],

@ -680,6 +680,26 @@ fn test_singular_msg_field() {
assert_that!(msg_mut.bb(), eq(0));
}
#[test]
fn test_message_opt() {
let msg = TestAllTypes::new();
let opt: Optional<
unittest_proto::TestAllTypes_::NestedMessageView<'_>,
unittest_proto::TestAllTypes_::NestedMessageView<'_>,
> = msg.optional_nested_message_opt();
assert_that!(opt.is_set(), eq(false));
assert_that!(opt.into_inner().bb(), eq(0));
}
#[test]
fn test_message_opt_set() {
let mut msg = TestAllTypes::new();
//let opt = msg.optional_nested_message_mut().or_default();
//assert_that!(opt.is_set(), eq(false));
//todo: check for set after prereq cl
//assert_that!(opt.into_inner().bb(), eq(0));
}
#[test]
fn test_optional_nested_enum_accessors() {
use TestAllTypes_::NestedEnum;

@ -10,6 +10,7 @@ use nested_proto::Outer_::InnerMut;
use nested_proto::Outer_::InnerView;
use nested_proto::Outer_::Inner_::InnerEnum;
use nested_proto::*;
use protobuf::Optional;
#[test]
fn test_deeply_nested_message() {

@ -89,6 +89,18 @@ void SingularMessage::InMsgImpl(Context& ctx, const FieldDescriptor& field,
}
)rs");
}},
{"getter_opt",
[&] {
ctx.Emit({}, R"rs(
pub fn $field$_opt($view_self$) ->
$pb$::Optional<$msg_type$View<$view_lifetime$>> {
let view = self.$field$();
$pb$::Optional::new(view, unsafe {
$hazzer_thunk$(self.raw_msg())
})
}
)rs");
}},
{"clearer",
[&] {
if (accessor_case == AccessorCase::VIEW) {
@ -102,6 +114,7 @@ void SingularMessage::InMsgImpl(Context& ctx, const FieldDescriptor& field,
R"rs(
$getter$
$getter_mut$
$getter_opt$
$clearer$
)rs");
}

Loading…
Cancel
Save