mirror_mirror/
map.rs

1use alloc::boxed::Box;
2use core::fmt;
3
4use crate::iter::PairIterMut;
5use crate::Reflect;
6
7/// A reflected map type.
8///
9/// Note this is only implemented for [`BTreeMap`] and _not_ [`HashMap`] due to technical
10/// limitations.
11///
12/// [`BTreeMap`]: alloc::collections::BTreeMap
13/// [`HashMap`]: std::collections::HashMap
14// HashMap isn't supported because we need a `Value` variant for map values. The most obvious
15// choice is `enum Value { Map(HashMap<Value, Value>) }`. However now `Value` is used as the key in
16// a `HashMap` so it most implement `Hash + Eq` but it can't since it contains a `HashMap` which
17// doesn't implement `Hash + Eq`, because there is no stable iteration order.
18pub trait Map: Reflect {
19    fn get(&self, key: &dyn Reflect) -> Option<&dyn Reflect>;
20
21    fn get_mut(&mut self, key: &dyn Reflect) -> Option<&mut dyn Reflect>;
22
23    fn insert(&mut self, key: &dyn Reflect, value: &dyn Reflect) -> Option<Box<dyn Reflect>>;
24
25    fn remove(&mut self, key: &dyn Reflect) -> Option<Box<dyn Reflect>>;
26
27    fn len(&self) -> usize;
28
29    fn is_empty(&self) -> bool;
30
31    fn iter(&self) -> Iter<'_>;
32
33    fn iter_mut(&mut self) -> PairIterMut<'_, dyn Reflect>;
34}
35
36impl fmt::Debug for dyn Map {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        self.as_reflect().debug(f)
39    }
40}
41
42pub type Iter<'a> = Box<dyn Iterator<Item = (&'a dyn Reflect, &'a dyn Reflect)> + 'a>;