Add .to_owned(&self)->Msg functions to MsgMut and MsgView

PiperOrigin-RevId: 631686314
pull/16770/head
Protobuf Team Bot 2024-05-08 00:48:25 -07:00 committed by Copybara-Service
parent 6afb130dca
commit d8329b68e4
2 changed files with 34 additions and 4 deletions

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

@ -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$