facet_reflect/peek/
map.rs

1use facet_core::{MapDef, PtrMut};
2
3use crate::ReflectError;
4
5use super::Peek;
6
7/// Iterator over key-value pairs in a `PeekMap`
8pub struct PeekMapIter<'mem, 'facet> {
9    map: PeekMap<'mem, 'facet>,
10    iter: PtrMut,
11}
12
13impl<'mem, 'facet> Iterator for PeekMapIter<'mem, 'facet> {
14    type Item = (Peek<'mem, 'facet>, Peek<'mem, 'facet>);
15
16    #[inline]
17    fn next(&mut self) -> Option<Self::Item> {
18        unsafe {
19            let next = (self.map.def.vtable.iter_vtable.next)(self.iter);
20            next.map(|(key_ptr, value_ptr)| {
21                (
22                    Peek::unchecked_new(key_ptr, self.map.def.k()),
23                    Peek::unchecked_new(value_ptr, self.map.def.v()),
24                )
25            })
26        }
27    }
28}
29
30impl<'mem, 'facet> Drop for PeekMapIter<'mem, 'facet> {
31    #[inline]
32    fn drop(&mut self) {
33        unsafe { (self.map.def.vtable.iter_vtable.dealloc)(self.iter) }
34    }
35}
36
37impl<'mem, 'facet> IntoIterator for &'mem PeekMap<'mem, 'facet> {
38    type Item = (Peek<'mem, 'facet>, Peek<'mem, 'facet>);
39    type IntoIter = PeekMapIter<'mem, 'facet>;
40
41    #[inline]
42    fn into_iter(self) -> Self::IntoIter {
43        self.iter()
44    }
45}
46
47/// Lets you read from a map (implements read-only [`facet_core::MapVTable`] proxies)
48#[derive(Clone, Copy)]
49pub struct PeekMap<'mem, 'facet> {
50    value: Peek<'mem, 'facet>,
51
52    def: MapDef,
53}
54
55impl<'mem, 'facet> core::fmt::Debug for PeekMap<'mem, 'facet> {
56    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
57        f.debug_struct("PeekMap").finish_non_exhaustive()
58    }
59}
60
61impl<'mem, 'facet> PeekMap<'mem, 'facet> {
62    /// Constructor
63    ///
64    /// # Safety
65    ///
66    /// The caller must ensure that `def` contains valid vtable function pointers that:
67    /// - Correctly implement the map operations for the actual type
68    /// - Do not cause undefined behavior when called
69    /// - Return pointers within valid memory bounds
70    /// - Match the key and value types specified in `def.k()` and `def.v()`
71    ///
72    /// Violating these requirements can lead to memory safety issues.
73    #[inline]
74    pub unsafe fn new(value: Peek<'mem, 'facet>, def: MapDef) -> Self {
75        Self { value, def }
76    }
77
78    /// Get the number of entries in the map
79    #[inline]
80    pub fn len(&self) -> usize {
81        unsafe { (self.def.vtable.len)(self.value.data()) }
82    }
83
84    /// Returns true if the map is empty
85    #[inline]
86    pub fn is_empty(&self) -> bool {
87        self.len() == 0
88    }
89
90    /// Check if the map contains a key
91    #[inline]
92    pub fn contains_key(&self, key: &impl facet_core::Facet<'facet>) -> Result<bool, ReflectError> {
93        self.contains_key_peek(Peek::new(key))
94    }
95
96    /// Get a value from the map for the given key
97    #[inline]
98    pub fn get<'k>(
99        &self,
100        key: &'k impl facet_core::Facet<'facet>,
101    ) -> Result<Option<Peek<'mem, 'facet>>, ReflectError> {
102        self.get_peek(Peek::new(key))
103    }
104
105    /// Check if the map contains a key
106    #[inline]
107    pub fn contains_key_peek(&self, key: Peek<'_, 'facet>) -> Result<bool, ReflectError> {
108        if self.def.k() == key.shape {
109            return Ok(unsafe { (self.def.vtable.contains_key)(self.value.data(), key.data()) });
110        }
111
112        Err(ReflectError::WrongShape {
113            expected: self.def.k(),
114            actual: key.shape,
115        })
116    }
117
118    /// Get a value from the map for the given key
119    #[inline]
120    pub fn get_peek(
121        &self,
122        key: Peek<'_, 'facet>,
123    ) -> Result<Option<Peek<'mem, 'facet>>, ReflectError> {
124        if self.def.k() == key.shape {
125            return Ok(unsafe {
126                let Some(value_ptr) =
127                    (self.def.vtable.get_value_ptr)(self.value.data(), key.data())
128                else {
129                    return Ok(None);
130                };
131                Some(Peek::unchecked_new(value_ptr, self.def.v()))
132            });
133        }
134
135        Err(ReflectError::WrongShape {
136            expected: self.def.k(),
137            actual: key.shape,
138        })
139    }
140
141    /// Returns an iterator over the key-value pairs in the map
142    #[inline]
143    pub fn iter(self) -> PeekMapIter<'mem, 'facet> {
144        let iter_init_with_value_fn = self.def.vtable.iter_vtable.init_with_value.unwrap();
145        let iter = unsafe { iter_init_with_value_fn(self.value.data()) };
146        PeekMapIter { map: self, iter }
147    }
148
149    /// Def getter
150    #[inline]
151    pub fn def(&self) -> MapDef {
152        self.def
153    }
154}