Skip to main content

google_protobuf/
map.rs

1// Protocol Buffers - Google's data interchange format
2// Copyright 2023 Google LLC.  All rights reserved.
3//
4// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file or at
6// https://developers.google.com/open-source/licenses/bsd
7
8use crate::{
9    __internal::runtime::{InnerMap, InnerMapMut, RawMap, RawMapIter},
10    __internal::{Private, SealedInternal},
11    AsMut, AsView, IntoMut, IntoProxied, IntoView, Message, Mut, MutProxied, Proxied, Singular,
12    View,
13};
14use std::marker::PhantomData;
15
16/// A trait implemented by types which are allowed as keys in maps.
17/// This is all types for fields except for repeated, maps, bytes, messages, enums and floating point types.
18#[doc(inline)]
19pub use crate::__internal::runtime::MapKey;
20
21/// A trait implemented by types which are allowed as values in maps, which is all Singular types.
22/// This trait is distinct from `Singular` only because of the generic `K: MapKey`.
23pub trait MapValue: Singular + SealedInternal {
24    #[doc(hidden)]
25    fn map_new<K: MapKey>(_: Private) -> Map<K, Self>;
26
27    /// # Safety
28    /// - After `map_free`, no other methods on the input are safe to call.
29    #[doc(hidden)]
30    unsafe fn map_free<K: MapKey>(_: Private, map: &mut Map<K, Self>);
31
32    #[doc(hidden)]
33    fn map_clear<K: MapKey>(_: Private, map: MapMut<K, Self>);
34
35    #[doc(hidden)]
36    fn map_len<K: MapKey>(_: Private, map: MapView<K, Self>) -> usize;
37
38    #[doc(hidden)]
39    fn map_insert<K: MapKey>(
40        _: Private,
41        map: MapMut<K, Self>,
42        key: View<'_, K>,
43        value: impl IntoProxied<Self>,
44    ) -> bool;
45
46    #[doc(hidden)]
47    fn map_get<'a, K: MapKey>(
48        _: Private,
49        map: MapView<'a, K, Self>,
50        key: View<'_, K>,
51    ) -> Option<View<'a, Self>>;
52
53    #[doc(hidden)]
54    fn map_get_mut<'a, K: MapKey>(
55        _: Private,
56        map: MapMut<'a, K, Self>,
57        key: View<'_, K>,
58    ) -> Option<Mut<'a, Self>>
59    where
60        Self: Message;
61
62    #[doc(hidden)]
63    fn map_remove<K: MapKey>(_: Private, map: MapMut<K, Self>, key: View<'_, K>) -> bool;
64
65    #[doc(hidden)]
66    fn map_iter<K: MapKey>(_: Private, map: MapView<K, Self>) -> MapIter<K, Self>;
67
68    #[doc(hidden)]
69    fn map_iter_next<'a, K: MapKey>(
70        _: Private,
71        iter: &mut MapIter<'a, K, Self>,
72    ) -> Option<(View<'a, K>, View<'a, Self>)>;
73}
74
75pub struct Map<K: MapKey, V: MapValue> {
76    inner: InnerMap,
77    _phantom: PhantomData<(PhantomData<K>, PhantomData<V>)>,
78}
79
80// SAFETY: `Map` is Sync because it does not implement interior mutability.
81unsafe impl<K: MapKey, V: MapValue> Sync for Map<K, V> {}
82
83// SAFETY: `Map` is Send because it's not bound to a specific thread e.g.
84// it does not use thread-local data or similar.
85unsafe impl<K: MapKey, V: MapValue> Send for Map<K, V> {}
86
87impl<K: MapKey, V: MapValue> SealedInternal for Map<K, V> {}
88
89impl<K: MapKey, V: MapValue> Map<K, V> {
90    #[inline]
91    pub fn new() -> Self {
92        V::map_new(Private)
93    }
94
95    #[inline]
96    pub fn as_mut(&mut self) -> MapMut<'_, K, V> {
97        MapMut { inner: self.inner.as_mut(), _phantom: PhantomData }
98    }
99
100    #[inline]
101    pub fn as_view(&self) -> MapView<'_, K, V> {
102        MapView { raw: self.inner.raw, _phantom: PhantomData }
103    }
104
105    #[doc(hidden)]
106    #[inline]
107    pub fn from_inner(_: Private, inner: InnerMap) -> Self {
108        Self { inner, _phantom: PhantomData }
109    }
110
111    #[doc(hidden)]
112    #[inline]
113    pub fn as_raw(&self, _: Private) -> RawMap {
114        self.inner.raw
115    }
116}
117
118impl<K: MapKey, V: MapValue> Default for Map<K, V> {
119    fn default() -> Self {
120        Map::new()
121    }
122}
123
124impl<K: MapKey, V: MapValue> Drop for Map<K, V> {
125    fn drop(&mut self) {
126        // SAFETY:
127        // - `drop` is only called once.
128        // - 'map_free` is only called here.
129        unsafe { V::map_free(Private, self) }
130    }
131}
132
133impl<K: MapKey, V: MapValue> Proxied for Map<K, V> {
134    type View<'msg> = MapView<'msg, K, V>;
135}
136
137impl<K: MapKey, V: MapValue> AsView for Map<K, V> {
138    type Proxied = Self;
139
140    fn as_view(&self) -> MapView<'_, K, V> {
141        self.as_view()
142    }
143}
144
145impl<K: MapKey, V: MapValue> MutProxied for Map<K, V> {
146    type Mut<'msg> = MapMut<'msg, K, V>;
147}
148
149impl<K: MapKey, V: MapValue> AsMut for Map<K, V> {
150    type MutProxied = Self;
151
152    fn as_mut(&mut self) -> MapMut<'_, K, V> {
153        self.as_mut()
154    }
155}
156
157impl<'msg, K, KView, V, VView, I> IntoProxied<Map<K, V>> for I
158where
159    I: Iterator<Item = (KView, VView)>,
160    K: MapKey,
161    V: MapValue,
162    KView: Into<View<'msg, K>>,
163    VView: IntoProxied<V>,
164{
165    fn into_proxied(self, _: Private) -> Map<K, V> {
166        let mut m = Map::<K, V>::new();
167        m.as_mut().extend(self);
168        m
169    }
170}
171
172/// A view of a map field.
173///
174/// This is a proxy type that is conceptually similar to a `&Map<K, V>`
175#[repr(transparent)]
176pub struct MapView<'msg, K: ?Sized, V: ?Sized> {
177    raw: RawMap,
178    _phantom: PhantomData<(&'msg K, &'msg V)>,
179}
180
181impl<'msg, K: ?Sized, V: ?Sized> Copy for MapView<'msg, K, V> {}
182impl<'msg, K: ?Sized, V: ?Sized> Clone for MapView<'msg, K, V> {
183    fn clone(&self) -> Self {
184        *self
185    }
186}
187
188unsafe impl<'msg, K: ?Sized, V: ?Sized> Sync for MapView<'msg, K, V> {}
189unsafe impl<'msg, K: ?Sized, V: ?Sized> Send for MapView<'msg, K, V> {}
190
191impl<'msg, K: ?Sized, V: ?Sized> std::fmt::Debug for MapView<'msg, K, V> {
192    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193        f.debug_tuple("MapView")
194            .field(&std::any::type_name::<K>())
195            .field(&std::any::type_name::<V>())
196            .finish()
197    }
198}
199
200impl<'msg, K: MapKey, V: MapValue> SealedInternal for MapView<'msg, K, V> {}
201
202#[doc(hidden)]
203impl<'msg, K: ?Sized, V: ?Sized> MapView<'msg, K, V> {
204    #[doc(hidden)]
205    pub fn as_raw(&self, _: Private) -> RawMap {
206        self.raw
207    }
208
209    /// # Safety
210    /// - `raw` must be valid to read from for `'msg`.
211    #[doc(hidden)]
212    pub unsafe fn from_raw(_: Private, raw: RawMap) -> Self {
213        Self { raw, _phantom: PhantomData }
214    }
215}
216
217impl<'msg, K: MapKey, V: MapValue> MapView<'msg, K, V> {
218    #[inline]
219    pub fn get<'a>(self, key: impl Into<View<'a, K>>) -> Option<View<'msg, V>>
220    where
221        K: 'a,
222    {
223        V::map_get(Private, self, key.into())
224    }
225
226    #[inline]
227    pub fn len(self) -> usize {
228        V::map_len(Private, self)
229    }
230
231    #[inline]
232    pub fn is_empty(self) -> bool {
233        self.len() == 0
234    }
235
236    #[inline]
237    pub fn contains_key<'a>(self, key: impl Into<View<'a, K>>) -> bool
238    where
239        K: 'a,
240    {
241        self.get(key).is_some()
242    }
243
244    /// Returns an iterator visiting all key-value pairs in arbitrary order.
245    ///
246    /// The iterator element type is `(View<K>, View<V>)`.
247    /// This is an alias for `<Self as IntoIterator>::into_iter`.
248    pub fn iter(self) -> MapIter<'msg, K, V> {
249        self.into_iter()
250    }
251
252    /// Returns an iterator visiting all keys in arbitrary order.
253    ///
254    /// The iterator element type is `View<K>`.
255    pub fn keys(self) -> impl Iterator<Item = View<'msg, K>> + 'msg {
256        self.into_iter().map(|(k, _)| k)
257    }
258
259    /// Returns an iterator visiting all values in arbitrary order.
260    ///
261    /// The iterator element type is `View<V>`.
262    pub fn values(self) -> impl Iterator<Item = View<'msg, V>> + 'msg {
263        self.into_iter().map(|(_, v)| v)
264    }
265}
266
267impl<'msg, K: MapKey, V: MapValue> AsView for MapView<'msg, K, V> {
268    type Proxied = Map<K, V>;
269
270    fn as_view(&self) -> MapView<'_, K, V> {
271        *self
272    }
273}
274
275impl<'msg, K: MapKey, V: MapValue> IntoView<'msg> for MapView<'msg, K, V> {
276    fn into_view<'shorter>(self) -> MapView<'shorter, K, V>
277    where
278        'msg: 'shorter,
279    {
280        MapView { raw: self.raw, _phantom: PhantomData }
281    }
282}
283
284impl<'msg, K: MapKey, V: MapValue> IntoProxied<Map<K, V>> for MapView<'msg, K, V>
285where
286    View<'msg, V>: IntoProxied<V>,
287{
288    fn into_proxied(self, _: Private) -> Map<K, V> {
289        let mut m = Map::<K, V>::new();
290        m.as_mut().copy_from(self);
291        m
292    }
293}
294
295/// A mutable proxy of a map field.
296///
297/// This is a proxy type that is conceptually similar to a `&mut Map<K, V>`
298pub struct MapMut<'msg, K: ?Sized, V: ?Sized> {
299    pub(crate) inner: InnerMapMut<'msg>,
300    _phantom: PhantomData<(&'msg mut K, &'msg mut V)>,
301}
302
303impl<'msg, K: ?Sized, V: ?Sized> MapMut<'msg, K, V> {
304    #[doc(hidden)]
305    pub fn inner(&self, _: Private) -> InnerMapMut<'_> {
306        self.inner
307    }
308}
309
310unsafe impl<'msg, K: ?Sized, V: ?Sized> Sync for MapMut<'msg, K, V> {}
311
312impl<'msg, K: ?Sized, V: ?Sized> std::fmt::Debug for MapMut<'msg, K, V> {
313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314        f.debug_tuple("MapMut")
315            .field(&std::any::type_name::<K>())
316            .field(&std::any::type_name::<V>())
317            .finish()
318    }
319}
320
321impl<'msg, K: MapKey, V: MapValue> SealedInternal for MapMut<'msg, K, V> {}
322
323impl<'msg, K: MapKey, V: MapValue> AsView for MapMut<'msg, K, V> {
324    type Proxied = Map<K, V>;
325
326    fn as_view(&self) -> MapView<'_, K, V> {
327        MapView { raw: self.inner.raw, _phantom: PhantomData }
328    }
329}
330
331impl<'msg, K: MapKey, V: MapValue> IntoView<'msg> for MapMut<'msg, K, V> {
332    fn into_view<'shorter>(self) -> MapView<'shorter, K, V>
333    where
334        'msg: 'shorter,
335    {
336        MapView { raw: self.inner.raw, _phantom: PhantomData }
337    }
338}
339
340impl<'msg, K: MapKey, V: MapValue> AsMut for MapMut<'msg, K, V> {
341    type MutProxied = Map<K, V>;
342
343    fn as_mut(&mut self) -> MapMut<'_, K, V> {
344        MapMut { inner: self.inner, _phantom: PhantomData }
345    }
346}
347
348impl<'msg, K: MapKey, V: MapValue> IntoMut<'msg> for MapMut<'msg, K, V> {
349    fn into_mut<'shorter>(self) -> MapMut<'shorter, K, V>
350    where
351        'msg: 'shorter,
352    {
353        MapMut { inner: self.inner, _phantom: PhantomData }
354    }
355}
356
357#[doc(hidden)]
358impl<'msg, K: ?Sized, V: ?Sized> MapMut<'msg, K, V> {
359    /// # Safety
360    /// - `inner` must be valid to read and write from for `'msg`.
361    #[doc(hidden)]
362    pub unsafe fn from_inner(_: Private, inner: InnerMapMut<'msg>) -> Self {
363        Self { inner, _phantom: PhantomData }
364    }
365
366    #[doc(hidden)]
367    pub fn as_raw(&mut self, _: Private) -> RawMap {
368        self.inner.raw
369    }
370}
371
372impl<'msg, K: MapKey, V: MapValue> MapMut<'msg, K, V> {
373    #[inline]
374    pub fn len(&self) -> usize {
375        self.as_view().len()
376    }
377
378    #[inline]
379    pub fn is_empty(&self) -> bool {
380        self.len() == 0
381    }
382
383    #[inline]
384    pub fn contains_key<'a>(&self, key: impl Into<View<'a, K>>) -> bool
385    where
386        K: 'a,
387    {
388        self.as_view().contains_key(key)
389    }
390
391    /// Adds a key-value pair to the map.
392    ///
393    /// Returns `true` if the entry was newly inserted.
394    #[inline]
395    pub fn insert<'a>(&mut self, key: impl Into<View<'a, K>>, value: impl IntoProxied<V>) -> bool {
396        V::map_insert(Private, self.as_mut(), key.into(), value)
397    }
398
399    #[inline]
400    pub fn remove<'a>(&mut self, key: impl Into<View<'a, K>>) -> bool {
401        V::map_remove(Private, self.as_mut(), key.into())
402    }
403
404    #[inline]
405    pub fn clear(&mut self) {
406        V::map_clear(Private, self.as_mut())
407    }
408
409    #[inline]
410    pub fn get<'a>(&self, key: impl Into<View<'a, K>>) -> Option<View<'_, V>> {
411        V::map_get(Private, self.as_view(), key.into())
412    }
413
414    #[inline]
415    pub fn get_mut<'a>(&mut self, key: impl Into<View<'a, K>>) -> Option<Mut<'_, V>>
416    where
417        V: Message,
418    {
419        V::map_get_mut(Private, self.as_mut(), key.into())
420    }
421
422    pub fn copy_from<'a>(
423        &mut self,
424        src: impl IntoIterator<Item = (impl Into<View<'a, K>>, impl IntoProxied<V>)>,
425    ) {
426        //TODO
427        self.clear();
428        for (k, v) in src.into_iter() {
429            self.insert(k, v);
430        }
431    }
432
433    /// Returns an iterator visiting all key-value pairs in arbitrary order.
434    ///
435    /// The iterator element type is `(View<K>, View<V>)`.
436    #[inline]
437    pub fn iter(&self) -> MapIter<'_, K, V> {
438        self.into_iter()
439    }
440
441    /// Returns an iterator visiting all keys in arbitrary order.
442    ///
443    /// The iterator element type is `View<K>`.
444    #[inline]
445    pub fn keys(&self) -> impl Iterator<Item = View<'_, K>> + '_ {
446        self.as_view().keys()
447    }
448
449    /// Returns an iterator visiting all values in arbitrary order.
450    ///
451    /// The iterator element type is `View<V>`.
452    #[inline]
453    pub fn values(&self) -> impl Iterator<Item = View<'_, V>> + '_ {
454        self.as_view().values()
455    }
456}
457
458impl<'msg, K: MapKey, V: MapValue> IntoProxied<Map<K, V>> for MapMut<'msg, K, V>
459where
460    View<'msg, V>: IntoProxied<V>,
461{
462    fn into_proxied(self, _: Private) -> Map<K, V> {
463        self.into_view().into_proxied(Private)
464    }
465}
466
467impl<'msg, 'k, KView, VView, K, V> Extend<(KView, VView)> for MapMut<'msg, K, V>
468where
469    K: MapKey,
470    V: MapValue,
471    KView: Into<View<'k, K>>,
472    VView: IntoProxied<V>,
473{
474    fn extend<T: IntoIterator<Item = (KView, VView)>>(&mut self, iter: T) {
475        for (k, v) in iter.into_iter() {
476            self.insert(k, v);
477        }
478    }
479}
480
481/// An iterator visiting all key-value pairs in arbitrary order.
482///
483/// The iterator element type is `(View<Key>, View<Value>)`.
484pub struct MapIter<'msg, K: ?Sized, V: ?Sized> {
485    raw: RawMapIter,
486    _phantom: PhantomData<(&'msg K, &'msg V)>,
487}
488
489impl<'msg, K: ?Sized, V: ?Sized> MapIter<'msg, K, V> {
490    /// # Safety
491    /// - `raw` must be a valid instance of the raw iterator for `'msg`.
492    /// - The untyped `raw` iterator must be for a map of `K,V`.
493    /// - The backing map must be live and unmodified for `'msg`.
494    #[doc(hidden)]
495    pub unsafe fn from_raw(_: Private, raw: RawMapIter) -> Self {
496        Self { raw, _phantom: PhantomData }
497    }
498
499    #[doc(hidden)]
500    pub fn as_raw_mut(&mut self, _: Private) -> &mut RawMapIter {
501        &mut self.raw
502    }
503}
504
505impl<'msg, K: MapKey, V: MapValue> Iterator for MapIter<'msg, K, V> {
506    type Item = (View<'msg, K>, View<'msg, V>);
507
508    fn next(&mut self) -> Option<Self::Item> {
509        V::map_iter_next(Private, self)
510    }
511}
512
513impl<'msg, K: MapKey, V: MapValue> IntoIterator for MapView<'msg, K, V> {
514    type IntoIter = MapIter<'msg, K, V>;
515    type Item = (View<'msg, K>, View<'msg, V>);
516
517    fn into_iter(self) -> MapIter<'msg, K, V> {
518        V::map_iter(Private, self)
519    }
520}
521
522impl<'msg, K: MapKey, V: MapValue> IntoIterator for &'msg Map<K, V> {
523    type IntoIter = MapIter<'msg, K, V>;
524    type Item = (View<'msg, K>, View<'msg, V>);
525
526    fn into_iter(self) -> MapIter<'msg, K, V> {
527        self.as_view().into_iter()
528    }
529}
530
531impl<'a, 'msg, K: MapKey, V: MapValue> IntoIterator for &'a MapView<'msg, K, V>
532where
533    'msg: 'a,
534{
535    type IntoIter = MapIter<'msg, K, V>;
536    type Item = (View<'msg, K>, View<'msg, V>);
537
538    fn into_iter(self) -> MapIter<'msg, K, V> {
539        (*self).into_iter()
540    }
541}
542
543impl<'a, 'msg, K: MapKey, V: MapValue> IntoIterator for &'a MapMut<'msg, K, V>
544where
545    'msg: 'a,
546{
547    type IntoIter = MapIter<'a, K, V>;
548    // The View's are valid for 'a instead of 'msg.
549    // This is because the mutator may mutate past 'a but before 'msg expires.
550    type Item = (View<'a, K>, View<'a, V>);
551
552    fn into_iter(self) -> MapIter<'a, K, V> {
553        self.as_view().into_iter()
554    }
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560    use crate::{ProtoBytes, ProtoStr, ProtoString};
561    use googletest::prelude::*;
562
563    #[gtest]
564    fn test_proxied_scalar() {
565        let mut map: Map<i32, i64> = Map::new();
566        let mut map_mut = map.as_mut();
567        map_mut.insert(1, 2);
568        assert_that!(map_mut.get(1), eq(Some(2)));
569
570        let map_view_1 = map_mut.as_view();
571        assert_that!(map_view_1.len(), eq(1));
572        assert_that!(map_view_1.get(1), eq(Some(2)));
573
574        map_mut.insert(3, 4);
575
576        let map_view_2 = map_mut.into_view();
577        assert_that!(map_view_2.len(), eq(2));
578        assert_that!(map_view_2.get(3), eq(Some(4)));
579
580        {
581            let map_view_3 = map_view_2.as_view();
582            assert_that!(map_view_3.is_empty(), eq(false));
583        }
584
585        let map_view_4 = map_view_2.into_view();
586        assert_that!(map_view_4.is_empty(), eq(false));
587    }
588
589    #[gtest]
590    fn test_proxied_str() {
591        let mut map: Map<ProtoString, ProtoString> = Map::new();
592        let mut map_mut = map.as_mut();
593        map_mut.insert("a", "b");
594
595        let map_view_1 = map_mut.as_view();
596        assert_that!(map_view_1.len(), eq(1));
597        assert_that!(map_view_1.get("a").unwrap(), eq("b"));
598
599        map_mut.insert("c", "d");
600
601        let map_view_2 = map_mut.into_view();
602        assert_that!(map_view_2.len(), eq(2));
603        assert_that!(map_view_2.get("c").unwrap(), eq("d"));
604
605        {
606            let map_view_3 = map_view_2.as_view();
607            assert_that!(map_view_3.is_empty(), eq(false));
608        }
609
610        let map_view_4 = map_view_2.into_view();
611        assert_that!(map_view_4.is_empty(), eq(false));
612    }
613
614    #[gtest]
615    fn test_proxied_iter() {
616        let mut map: Map<i32, ProtoString> = Map::new();
617        let mut map_mut = map.as_mut();
618        map_mut.insert(15, "fizzbuzz");
619        map_mut.insert(5, "buzz");
620        map_mut.insert(3, "fizz");
621
622        // ProtoStr::from_str is necessary below because
623        // https://doc.rust-lang.org/std/primitive.tuple.html#impl-PartialEq-for-(T,)
624        // only compares where the types are the same, even when the tuple types can
625        // compare with each other.
626        // googletest-rust matchers also do not currently implement Clone.
627        assert_that!(
628            map.as_view().iter().collect::<Vec<_>>(),
629            unordered_elements_are![
630                eq(&(3, ProtoStr::from_str("fizz"))),
631                eq(&(5, ProtoStr::from_str("buzz"))),
632                eq(&(15, ProtoStr::from_str("fizzbuzz")))
633            ]
634        );
635        assert_that!(
636            map.as_view(),
637            unordered_elements_are![
638                eq((3, ProtoStr::from_str("fizz"))),
639                eq((5, ProtoStr::from_str("buzz"))),
640                eq((15, ProtoStr::from_str("fizzbuzz")))
641            ]
642        );
643        assert_that!(
644            map.as_mut().iter().collect::<Vec<_>>(),
645            unordered_elements_are![
646                eq(&(3, ProtoStr::from_str("fizz"))),
647                eq(&(5, ProtoStr::from_str("buzz"))),
648                eq(&(15, ProtoStr::from_str("fizzbuzz")))
649            ]
650        );
651        assert_that!(
652            map.as_mut(),
653            unordered_elements_are![
654                eq((3, ProtoStr::from_str("fizz"))),
655                eq((5, ProtoStr::from_str("buzz"))),
656                eq((15, ProtoStr::from_str("fizzbuzz")))
657            ]
658        );
659    }
660
661    #[gtest]
662    fn test_overwrite_insert() {
663        let mut map: Map<i32, ProtoString> = Map::new();
664        let mut map_mut = map.as_mut();
665        assert!(map_mut.insert(0, "fizz"));
666        // insert should return false when the key is already present
667        assert!(!map_mut.insert(0, "buzz"));
668        assert_that!(map.as_mut(), unordered_elements_are![eq((0, ProtoStr::from_str("buzz"))),]);
669    }
670
671    #[gtest]
672    fn test_extend() {
673        let mut map: Map<i32, ProtoString> = Map::new();
674        let mut map_mut = map.as_mut();
675
676        map_mut.extend([(0, ""); 0]);
677        assert_that!(map_mut.len(), eq(0));
678
679        map_mut.extend([(0, "fizz"), (1, "buzz"), (2, "fizzbuzz")]);
680
681        assert_that!(
682            map.as_view(),
683            unordered_elements_are![
684                eq((0, ProtoStr::from_str("fizz"))),
685                eq((1, ProtoStr::from_str("buzz"))),
686                eq((2, ProtoStr::from_str("fizzbuzz")))
687            ]
688        );
689
690        let mut map_2: Map<i32, ProtoString> = Map::new();
691        let mut map_2_mut = map_2.as_mut();
692        map_2_mut.extend([(2, "bing"), (3, "bong")]);
693
694        let mut map_mut = map.as_mut();
695        map_mut.extend(&map_2);
696
697        assert_that!(
698            map.as_view(),
699            unordered_elements_are![
700                eq((0, ProtoStr::from_str("fizz"))),
701                eq((1, ProtoStr::from_str("buzz"))),
702                eq((2, ProtoStr::from_str("bing"))),
703                eq((3, ProtoStr::from_str("bong")))
704            ]
705        );
706    }
707
708    #[gtest]
709    fn test_copy_from() {
710        let mut map: Map<i32, ProtoString> = Map::new();
711        let mut map_mut = map.as_mut();
712        map_mut.copy_from([(0, "fizz"), (1, "buzz"), (2, "fizzbuzz")]);
713
714        assert_that!(
715            map.as_view(),
716            unordered_elements_are![
717                eq((0, ProtoStr::from_str("fizz"))),
718                eq((1, ProtoStr::from_str("buzz"))),
719                eq((2, ProtoStr::from_str("fizzbuzz")))
720            ]
721        );
722
723        let mut map_2: Map<i32, ProtoString> = Map::new();
724        let mut map_2_mut = map_2.as_mut();
725        map_2_mut.copy_from([(2, "bing"), (3, "bong")]);
726
727        let mut map_mut = map.as_mut();
728        map_mut.copy_from(&map_2);
729
730        assert_that!(
731            map.as_view(),
732            unordered_elements_are![
733                eq((2, ProtoStr::from_str("bing"))),
734                eq((3, ProtoStr::from_str("bong")))
735            ]
736        );
737    }
738
739    #[gtest]
740    fn test_all_maps_can_be_constructed() {
741        macro_rules! gen_proto_values {
742            ($key_t:ty, $($value_t:ty),*) => {
743                $(
744                    let map = Map::<$key_t, $value_t>::new();
745                    assert_that!(map.as_view().len(), eq(0));
746                )*
747            }
748        }
749
750        macro_rules! gen_proto_keys {
751            ($($key_t:ty),*) => {
752                $(
753                    gen_proto_values!($key_t, f32, f64, i32, u32, i64, bool, ProtoString, ProtoBytes);
754                )*
755            }
756        }
757
758        gen_proto_keys!(i32, u32, i64, u64, bool, ProtoString);
759    }
760
761    #[gtest]
762    fn test_dbg() {
763        let mut map = Map::<i32, f64>::new();
764        assert_that!(format!("{:?}", map.as_view()), eq("MapView(\"i32\", \"f64\")"));
765        assert_that!(format!("{:?}", map.as_mut()), eq("MapMut(\"i32\", \"f64\")"));
766    }
767    #[gtest]
768    fn test_contains_key() {
769        let mut map = Map::<i32, f64>::new();
770        let mut map_mut = map.as_mut();
771        assert!(!map_mut.contains_key(42));
772        assert!(!map_mut.as_view().contains_key(42));
773
774        map_mut.insert(42, 1.0);
775        assert!(map_mut.contains_key(42));
776        assert!(map_mut.as_view().contains_key(42));
777    }
778}