From 7c4d89e1153a1d5a64a55154f0beb7f91cd0d558 Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Tue, 19 Mar 2024 10:31:27 -0700 Subject: [PATCH] Implement Map::copy_from and implement the Extend trait for Maps PiperOrigin-RevId: 617218421 --- rust/map.rs | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 90 insertions(+), 2 deletions(-) diff --git a/rust/map.rs b/rust/map.rs index 383c76b12a..4d80d1ea78 100644 --- a/rust/map.rs +++ b/rust/map.rs @@ -314,8 +314,18 @@ where V::map_get(self.as_view(), key.into()) } - pub fn copy_from(&mut self, _src: MapView<'_, K, V>) { - todo!("implement b/28530933"); + pub fn copy_from<'a, 'b>( + &mut self, + src: impl IntoIterator>, impl Into>)>, + ) where + K: 'a, + V: 'b, + { + //TODO + self.clear(); + for (k, v) in src.into_iter() { + self.insert(k, v); + } } /// Returns an iterator visiting all key-value pairs in arbitrary order. @@ -432,6 +442,20 @@ where } } +impl<'msg, 'k, 'v, KView, VView, K, V> Extend<(KView, VView)> for MapMut<'msg, K, V> +where + K: Proxied + ?Sized + 'msg + 'k, + V: ProxiedInMapValue + ?Sized + 'msg + 'v, + KView: Into>, + VView: Into>, +{ + fn extend>(&mut self, iter: T) { + for (k, v) in iter.into_iter() { + self.insert(k, v); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -542,6 +566,70 @@ mod tests { ); } + #[test] + fn test_extend() { + let mut map: Map = Map::new(); + let mut map_mut = map.as_mut(); + map_mut.extend([(0, "fizz"), (1, "buzz"), (2, "fizzbuzz")]); + + assert_that!( + map.as_view().into_iter().collect::>(), + unordered_elements_are![ + eq((0, ProtoStr::from_str("fizz"))), + eq((1, ProtoStr::from_str("buzz"))), + eq((2, ProtoStr::from_str("fizzbuzz"))) + ] + ); + + let mut map_2: Map = Map::new(); + let mut map_2_mut = map_2.as_mut(); + map_2_mut.extend([(2, "bing"), (3, "bong")]); + + let mut map_mut = map.as_mut(); + map_mut.extend(&map_2); + + assert_that!( + map.as_view().into_iter().collect::>(), + unordered_elements_are![ + eq((0, ProtoStr::from_str("fizz"))), + eq((1, ProtoStr::from_str("buzz"))), + eq((2, ProtoStr::from_str("bing"))), + eq((3, ProtoStr::from_str("bong"))) + ] + ); + } + + #[test] + fn test_copy_from() { + let mut map: Map = Map::new(); + let mut map_mut = map.as_mut(); + map_mut.copy_from([(0, "fizz"), (1, "buzz"), (2, "fizzbuzz")]); + + assert_that!( + map.as_view().into_iter().collect::>(), + unordered_elements_are![ + eq((0, ProtoStr::from_str("fizz"))), + eq((1, ProtoStr::from_str("buzz"))), + eq((2, ProtoStr::from_str("fizzbuzz"))) + ] + ); + + let mut map_2: Map = Map::new(); + let mut map_2_mut = map_2.as_mut(); + map_2_mut.copy_from([(2, "bing"), (3, "bong")]); + + let mut map_mut = map.as_mut(); + map_mut.copy_from(&map_2); + + assert_that!( + map.as_view().into_iter().collect::>(), + unordered_elements_are![ + eq((2, ProtoStr::from_str("bing"))), + eq((3, ProtoStr::from_str("bong"))) + ] + ); + } + #[test] fn test_all_maps_can_be_constructed() { macro_rules! gen_proto_values {