MCPcopy Create free account
hub / github.com/clockworklabs/SpacetimeDB / get_or_insert

Method get_or_insert

crates/data-structures/src/small_map.rs:70–90  ·  view source on GitHub ↗

Returns either the existing value for `key` or inserts into `key` using `or_insert`.

(&mut self, key: K, or_insert: impl FnOnce() -> V)

Source from the content-addressed store, hash-verified

68 /// Returns either the existing value for `key`
69 /// or inserts into `key` using `or_insert`.
70 pub fn get_or_insert(&mut self, key: K, or_insert: impl FnOnce() -> V) -> &mut V {
71 // Possibly convert to large map first.
72 self.maybe_convert_to_large();
73
74 match self {
75 Self::Small(list) => {
76 if let Some(idx) = Self::key_pos(list, &key) {
77 // SAFETY: `idx` was given by `key_pos`, so it must be in-bounds.
78 let (_, val) = unsafe { list.get_unchecked_mut(idx) };
79 return val;
80 }
81
82 list.push((key, or_insert()));
83 let last = list.last_mut();
84 // SAFETY: just inserted one element so `list` cannot be empty.
85 let (_, val) = unsafe { last.unwrap_unchecked() };
86 val
87 }
88 Self::Large(map) => map.entry(key).or_insert_with(or_insert),
89 }
90 }
91
92 #[inline]
93 fn maybe_convert_to_large(&mut self) {

Calls 3

entryMethod · 0.80
pushMethod · 0.45

Tested by

no test coverage detected