Skip to main content

google_protobuf/upb_kernel/
map.rs

1use super::*;
2
3/// Returns a static empty MapView.
4pub fn empty_map<K, V>() -> MapView<'static, K, V>
5where
6    K: MapKey,
7    V: MapValue,
8{
9    // TODO: Consider creating a static empty map in C.
10
11    // Use `<bool, bool>` for a shared empty map for all map types.
12    //
13    // This relies on an implicit contract with UPB that it is OK to use an empty
14    // Map<bool, bool> as an empty map of all other types. The only const
15    // function on `upb_Map` that will care about the size of key or value is
16    // `get()` where it will hash the appropriate number of bytes of the
17    // provided `upb_MessageValue`, and that bool being the smallest type in the
18    // union means it will happen to work for all possible key types.
19    //
20    // If we used a larger key, then UPB would hash more bytes of the key than Rust
21    // initialized.
22    static EMPTY_MAP_VIEW: OnceLock<Map<bool, bool>> = OnceLock::new();
23
24    // SAFETY:
25    // - The map is empty and never mutated.
26    // - The value type is never used.
27    // - The size of the key type is used when `get()` computes the hash of the key.
28    //   The map is empty, therefore it doesn't matter what hash is computed, but we
29    //   have to use `bool` type as the smallest key possible (otherwise UPB would
30    //   read more bytes than Rust allocated).
31    unsafe {
32        MapView::from_raw(Private, EMPTY_MAP_VIEW.get_or_init(Map::new).as_view().as_raw(Private))
33    }
34}
35
36impl<'msg, K: ?Sized, V: ?Sized> MapMut<'msg, K, V> {
37    // Returns a `RawArena` which is live for at least `'msg`
38    #[doc(hidden)]
39    pub fn raw_arena(&mut self, _private: Private) -> RawArena {
40        self.inner.arena.raw()
41    }
42
43    // Returns an `Arena` which is live for at least `'msg`
44    #[doc(hidden)]
45    pub fn arena(&self, _private: Private) -> &'msg Arena {
46        self.inner.arena
47    }
48}
49
50#[derive(Debug)]
51#[doc(hidden)]
52pub struct InnerMap {
53    pub(crate) raw: RawMap,
54    arena: Arena,
55}
56
57impl InnerMap {
58    pub fn new(raw: RawMap, arena: Arena) -> Self {
59        Self { raw, arena }
60    }
61
62    pub fn as_mut(&mut self) -> InnerMapMut<'_> {
63        InnerMapMut { raw: self.raw, arena: &self.arena }
64    }
65}
66
67#[derive(Clone, Copy, Debug)]
68#[doc(hidden)]
69pub struct InnerMapMut<'msg> {
70    pub(crate) raw: RawMap,
71    arena: &'msg Arena,
72}
73
74#[doc(hidden)]
75impl<'msg> InnerMapMut<'msg> {
76    pub fn new(raw: RawMap, arena: &'msg Arena) -> Self {
77        InnerMapMut { raw, arena }
78    }
79
80    #[doc(hidden)]
81    pub fn as_raw(&self) -> RawMap {
82        self.raw
83    }
84
85    pub fn arena(&mut self) -> &Arena {
86        self.arena
87    }
88
89    #[doc(hidden)]
90    pub fn raw_arena(&mut self) -> RawArena {
91        self.arena.raw()
92    }
93}
94
95#[doc(hidden)]
96pub struct RawMapIter {
97    // TODO: Replace this `RawMap` with the const type.
98    map: RawMap,
99    iter: usize,
100}
101
102impl RawMapIter {
103    pub fn new(map: RawMap) -> Self {
104        RawMapIter { map, iter: UPB_MAP_BEGIN }
105    }
106
107    /// # Safety
108    /// - `self.map` must be valid, and remain valid while the return value is
109    ///   in use.
110    pub unsafe fn next_unchecked(&mut self) -> Option<(upb_MessageValue, upb_MessageValue)> {
111        let mut key = MaybeUninit::uninit();
112        let mut value = MaybeUninit::uninit();
113        // SAFETY: the `map` is valid as promised by the caller
114        unsafe { upb_Map_Next(self.map, key.as_mut_ptr(), value.as_mut_ptr(), &mut self.iter) }
115            // SAFETY: if upb_Map_Next returns true, then key and value have been populated.
116            .then(|| unsafe { (key.assume_init(), value.assume_init()) })
117    }
118}
119
120impl<MessageType> MapValue for MessageType
121where
122    Self: Proxied + EntityType + UpbTypeConversions<<Self as EntityType>::Tag>,
123{
124    fn map_new<K: MapKey>(_private: Private) -> Map<K, Self> {
125        let arena = Arena::new();
126        let raw = unsafe { upb_Map_New(arena.raw(), K::upb_type(), Self::upb_type()) };
127
128        Map::from_inner(Private, InnerMap::new(raw, arena))
129    }
130
131    unsafe fn map_free<K: MapKey>(_private: Private, _map: &mut Map<K, Self>) {
132        // No-op: the memory will be dropped by the arena.
133    }
134
135    fn map_clear<K: MapKey>(_private: Private, mut map: MapMut<K, Self>) {
136        unsafe {
137            upb_Map_Clear(map.as_raw(Private));
138        }
139    }
140
141    fn map_len<K: MapKey>(_private: Private, map: MapView<K, Self>) -> usize {
142        unsafe { upb_Map_Size(map.as_raw(Private)) }
143    }
144
145    fn map_insert<K: MapKey>(
146        _private: Private,
147        mut map: MapMut<K, Self>,
148        key: View<'_, K>,
149        value: impl IntoProxied<Self>,
150    ) -> bool {
151        let arena = map.inner(Private).raw_arena();
152        let insert_status = unsafe {
153            upb_Map_Insert(
154                map.as_raw(Private),
155                K::to_message_value(key),
156                Self::into_message_value_fuse_if_required(arena, value.into_proxied(Private)),
157                arena,
158            )
159        };
160        match insert_status {
161            upb::MapInsertStatus::Inserted => true,
162            upb::MapInsertStatus::Replaced => false,
163            upb::MapInsertStatus::OutOfMemory => {
164                panic!("map insert failed (alloc should be infallible)")
165            }
166        }
167    }
168
169    fn map_get<'a, K: MapKey>(
170        _private: Private,
171        map: MapView<'a, K, Self>,
172        key: View<'_, K>,
173    ) -> Option<View<'a, Self>> {
174        let mut val = MaybeUninit::uninit();
175        let found =
176            unsafe { upb_Map_Get(map.as_raw(Private), K::to_message_value(key), val.as_mut_ptr()) };
177        if !found {
178            return None;
179        }
180        Some(unsafe { Self::from_message_value(val.assume_init()) })
181    }
182
183    fn map_get_mut<'a, K: MapKey>(
184        _private: Private,
185        mut map: MapMut<'a, K, Self>,
186        key: View<'_, K>,
187    ) -> Option<Mut<'a, Self>>
188    where
189        Self: Message,
190    {
191        // SAFETY: The map is valid as promised by the caller.
192        let val = unsafe { upb_Map_GetMutable(map.as_raw(Private), K::to_message_value(key)) };
193        // SAFETY: The lifetime of the MapMut is guaranteed to outlive the returned Mut.
194        NonNull::new(val).map(|msg| unsafe { Self::from_message_mut(msg, map.arena(Private)) })
195    }
196
197    fn map_remove<K: MapKey>(
198        _private: Private,
199        mut map: MapMut<K, Self>,
200        key: View<'_, K>,
201    ) -> bool {
202        unsafe { upb_Map_Delete(map.as_raw(Private), K::to_message_value(key), ptr::null_mut()) }
203    }
204    fn map_iter<K: MapKey>(_private: Private, map: MapView<K, Self>) -> MapIter<K, Self> {
205        // SAFETY: MapView<'_,..>> guarantees its RawMap outlives '_.
206        unsafe { MapIter::from_raw(Private, RawMapIter::new(map.as_raw(Private))) }
207    }
208
209    fn map_iter_next<'a, K: MapKey>(
210        _private: Private,
211        iter: &mut MapIter<'a, K, Self>,
212    ) -> Option<(View<'a, K>, View<'a, Self>)> {
213        // SAFETY: MapIter<'a, ..> guarantees its RawMapIter outlives 'a.
214        unsafe { iter.as_raw_mut(Private).next_unchecked() }
215            // SAFETY: MapIter<K, V> returns key and values message values
216            //         with the variants for K and V active.
217            .map(|(k, v)| unsafe { (K::from_message_value(k), Self::from_message_value(v)) })
218    }
219}