1use crate::{Entry, OccupiedEntry, VacantEntry};
2use core::mem;
3
4impl<'a, K: PartialEq, V, const N: usize> Entry<'a, K, V, N> {
5 pub fn or_insert(
6 self,
7 default: V,
8 ) -> &'a mut V {
9 match self {
10 Entry::Occupied(entry) => entry.into_mut(),
11 Entry::Vacant(entry) => entry.insert(default),
12 }
13 }
14
15 pub fn or_insert_with<F: FnOnce() -> V>(
16 self,
17 default: F,
18 ) -> &'a mut V {
19 match self {
20 Entry::Occupied(entry) => entry.into_mut(),
21 Entry::Vacant(entry) => entry.insert(default()),
22 }
23 }
24
25 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(
26 self,
27 default: F,
28 ) -> &'a mut V {
29 match self {
30 Entry::Occupied(entry) => entry.into_mut(),
31 Entry::Vacant(entry) => {
32 let value = default(entry.key());
33 entry.insert(value)
34 }
35 }
36 }
37
38 pub fn key(&self) -> &K {
39 match self {
40 Entry::Occupied(entry) => entry.key(),
41 Entry::Vacant(entry) => entry.key(),
42 }
43 }
44
45 #[must_use]
46 pub fn and_modify<F>(
47 self,
48 f: F,
49 ) -> Self
50 where
51 F: FnOnce(&mut V),
52 {
53 match self {
54 Entry::Occupied(mut entry) => {
55 f(entry.get_mut());
56 Entry::Occupied(entry)
57 }
58 Entry::Vacant(entry) => Entry::Vacant(entry),
59 }
60 }
61}
62
63impl<'a, K: PartialEq, V: Default, const N: usize> Entry<'a, K, V, N> {
64 pub fn or_default(self) -> &'a mut V {
65 match self {
66 Entry::Occupied(entry) => entry.into_mut(),
67 Entry::Vacant(entry) => entry.insert(V::default()),
68 }
69 }
70}
71
72impl<'a, K: PartialEq, V, const N: usize> OccupiedEntry<'a, K, V, N> {
73 #[must_use]
74 pub fn key(&self) -> &K {
75 &self.table.item_ref(self.index).0
76 }
77
78 #[must_use]
79 pub fn remove_entry(self) -> (K, V) {
80 self.table.remove_index_read(self.index)
81 }
82
83 #[must_use]
84 pub fn get(&self) -> &V {
85 &self.table.item_ref(self.index).1
86 }
87
88 pub fn get_mut(&mut self) -> &mut V {
89 self.table.item_mut(self.index)
90 }
91
92 #[must_use]
93 pub fn into_mut(self) -> &'a mut V {
94 self.table.item_mut(self.index)
95 }
96
97 pub fn insert(
98 &mut self,
99 value: V,
100 ) -> V {
101 mem::replace(self.get_mut(), value)
102 }
103
104 #[must_use]
105 pub fn remove(self) -> V {
106 self.table.remove_index_read(self.index).1
107 }
108}
109
110impl<'a, K: PartialEq, V, const N: usize> VacantEntry<'a, K, V, N> {
111 pub const fn key(&self) -> &K {
112 &self.key
113 }
114
115 pub fn into_key(self) -> K {
116 self.key
117 }
118
119 pub fn insert(
120 self,
121 value: V,
122 ) -> &'a mut V {
123 let (index, _) = self.table.insert_i(self.key, value);
124 self.table.item_mut(index)
125 }
126}