Fix Rust Proto cpp-kernel map insertion behavior to better match Rust's std::HashMap and the upb-kernel behavior of "insert replaces the old value"

PiperOrigin-RevId: 616934577
pull/16216/head
Protobuf Team Bot 2024-03-18 13:43:53 -07:00 committed by Copybara-Service
parent 5d136e1b4d
commit 1dbed2138c
2 changed files with 17 additions and 0 deletions

View File

@ -86,6 +86,9 @@ struct PtrAndLen {
bool __rust_proto_thunk__Map_##rust_key_ty##_##rust_value_ty##_insert( \
google::protobuf::Map<key_ty, value_ty>* m, ffi_key_ty key, ffi_value_ty value) { \
auto iter_and_inserted = m->try_emplace(to_cpp_key, to_cpp_value); \
if (!iter_and_inserted.second) { \
iter_and_inserted.first->second = to_cpp_value; \
} \
return iter_and_inserted.second; \
} \
bool __rust_proto_thunk__Map_##rust_key_ty##_##rust_value_ty##_get( \

View File

@ -528,6 +528,20 @@ mod tests {
);
}
#[test]
fn test_overwrite_insert() {
let mut map: Map<i32, ProtoStr> = Map::new();
let mut map_mut = map.as_mut();
assert!(map_mut.insert(0, "fizz"));
// insert should return false when the key is already present
assert!(!map_mut.insert(0, "buzz"));
assert_that!(
map.as_mut().iter().collect::<Vec<_>>(),
unordered_elements_are![eq((0, ProtoStr::from_str("buzz"))),]
);
}
#[test]
fn test_all_maps_can_be_constructed() {
macro_rules! gen_proto_values {