Returns either the existing value for `key` or inserts into `key` using `or_insert`.
(&mut self, key: K, or_insert: impl FnOnce() -> V)
| 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) { |
no test coverage detected