1use core::fmt::{self, Debug};
2use std::{
3 hash::{BuildHasher, Hash, RandomState},
4 ops::{Index, IndexMut},
5};
6
7use hashbrown::HashTable;
8use indexmap::Equivalent;
9
10use crate::{EntityId, EntityPartVec};
11
12pub trait EntityKey {
13 type KeyType: core::hash::Hash + Eq + ?Sized;
14 fn key(&self) -> &Self::KeyType;
15}
16
17impl EntityKey for String {
18 type KeyType = String;
19 fn key(&self) -> &Self::KeyType {
20 self
21 }
22}
23
24#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Debug)]
25pub struct DuplicateKeyError;
26
27impl core::fmt::Display for DuplicateKeyError {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 write!(f, "duplicate key error")
30 }
31}
32
33impl core::error::Error for DuplicateKeyError {}
34
35#[derive(Clone)]
36pub struct EntityPartMap<I: EntityId, V: EntityKey, RS: BuildHasher = RandomState> {
37 items: EntityPartVec<I, V>,
38 table: HashTable<I>,
39 h: RS,
40}
41
42impl<I: EntityId, V: EntityKey> EntityPartMap<I, V, RandomState> {
43 pub fn new() -> Self {
44 Self::with_hasher(Default::default())
45 }
46
47 pub fn with_capacity(n: usize) -> Self {
48 Self::with_capacity_and_hasher(n, Default::default())
49 }
50}
51
52impl<I: EntityId, V: EntityKey, RS: BuildHasher> EntityPartMap<I, V, RS> {
53 pub fn with_hasher(h: RS) -> Self {
54 Self {
55 items: Default::default(),
56 table: Default::default(),
57 h,
58 }
59 }
60
61 pub fn with_capacity_and_hasher(n: usize, h: RS) -> Self {
62 Self {
63 items: EntityPartVec::with_capacity(n),
64 table: HashTable::with_capacity(n),
65 h,
66 }
67 }
68
69 pub fn clear(&mut self) {
70 self.items.clear();
71 self.table.clear();
72 }
73
74 pub fn is_empty(&self) -> bool {
75 self.iter().next().is_none()
76 }
77
78 pub fn get<Q>(&self, key: &Q) -> Option<(I, &V)>
79 where
80 Q: ?Sized + Hash + Equivalent<V::KeyType>,
81 {
82 self.table
83 .find(self.h.hash_one(key), |&id| {
84 key.equivalent(self.items[id].key())
85 })
86 .map(|&id| (id, &self.items[id]))
87 }
88
89 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<(I, &mut V)>
90 where
91 Q: ?Sized + Hash + Equivalent<V::KeyType>,
92 {
93 self.table
94 .find(self.h.hash_one(key), |&id| {
95 key.equivalent(self.items[id].key())
96 })
97 .map(|&id| (id, &mut self.items[id]))
98 }
99
100 pub fn get_id(&self, id: I) -> Option<&V> {
101 self.items.get(id)
102 }
103
104 pub fn get_mut_id(&mut self, id: I) -> Option<&mut V> {
105 self.items.get_mut(id)
106 }
107
108 pub fn contains_id(&self, id: I) -> bool {
109 self.items.contains_id(id)
110 }
111
112 pub fn contains_key<Q>(&self, key: &Q) -> bool
113 where
114 Q: ?Sized + Hash + Equivalent<V::KeyType>,
115 {
116 self.get(key).is_some()
117 }
118
119 pub fn insert(&mut self, id: I, v: V) -> Result<(), DuplicateKeyError> {
120 let h = self.h.hash_one(v.key());
121 if let Some(&cur_id) = self
122 .table
123 .find(h, |&cur_id| v.key() == self.items[cur_id].key())
124 {
125 if id == cur_id {
126 self.items.insert(id, v);
127 Ok(())
128 } else {
129 Err(DuplicateKeyError)
130 }
131 } else if let Some(cur_item) = self.items.get(id) {
132 if cur_item.key() == v.key() {
133 self.items.insert(id, v);
134 } else {
135 let entry = self
137 .table
138 .find_entry(self.h.hash_one(cur_item.key()), |&cur_id| cur_id == id)
139 .unwrap();
140 entry.remove();
141 self.items.insert(id, v);
142 self.table
143 .insert_unique(h, id, |&id| self.h.hash_one(self.items[id].key()));
144 }
145 Ok(())
146 } else {
147 self.items.insert(id, v);
148 self.table
149 .insert_unique(h, id, |&id| self.h.hash_one(self.items[id].key()));
150 Ok(())
151 }
152 }
153
154 pub fn remove(&mut self, id: I) -> Option<V> {
155 let res = self.items.remove(id)?;
156 let entry = self
157 .table
158 .find_entry(self.h.hash_one(res.key()), |&cur_id| cur_id == id)
159 .unwrap();
160 entry.remove();
161 Some(res)
162 }
163
164 pub fn iter(&self) -> crate::part::Iter<'_, I, V> {
165 self.items.iter()
166 }
167
168 pub fn iter_mut(&mut self) -> crate::part::IterMut<'_, I, V> {
169 self.items.iter_mut()
170 }
171
172 pub fn ids(&self) -> crate::part::Ids<'_, I, V> {
173 self.items.ids()
174 }
175
176 pub fn into_ids(self) -> crate::part::IntoIds<I, V> {
177 self.items.into_ids()
178 }
179
180 pub fn values(&self) -> crate::part::Values<'_, I, V> {
181 self.items.values()
182 }
183
184 pub fn values_mut(&mut self) -> crate::part::ValuesMut<'_, I, V> {
185 self.items.values_mut()
186 }
187
188 pub fn into_values(self) -> crate::part::IntoValues<I, V> {
189 self.items.into_values()
190 }
191
192 pub fn map<O>(&self, f: impl FnMut(I, &V) -> O) -> EntityPartVec<I, O> {
193 self.items.map(f)
194 }
195
196 pub fn map_values<O>(&self, f: impl FnMut(&V) -> O) -> EntityPartVec<I, O> {
197 self.items.map_values(f)
198 }
199}
200
201impl<I: EntityId, V: EntityKey> Default for EntityPartMap<I, V, RandomState> {
202 fn default() -> Self {
203 Self::new()
204 }
205}
206
207impl<I, V, RS> Debug for EntityPartMap<I, V, RS>
208where
209 I: EntityId,
210 V: EntityKey + Debug,
211 RS: BuildHasher,
212{
213 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
214 fmt.debug_map().entries(self.iter()).finish()
215 }
216}
217
218impl<I, V, RS, RS2> PartialEq<EntityPartMap<I, V, RS2>> for EntityPartMap<I, V, RS>
219where
220 I: EntityId,
221 V: EntityKey + PartialEq,
222 RS: BuildHasher,
223 RS2: BuildHasher,
224{
225 fn eq(&self, other: &EntityPartMap<I, V, RS2>) -> bool {
226 self.items.eq(&other.items)
227 }
228}
229
230impl<I, V, RS> Eq for EntityPartMap<I, V, RS>
231where
232 I: EntityId,
233 V: EntityKey + Eq,
234 RS: BuildHasher,
235{
236}
237
238impl<I: EntityId, V: EntityKey, RS: BuildHasher> IntoIterator for EntityPartMap<I, V, RS> {
239 type Item = (I, V);
240 type IntoIter = crate::part::IntoIter<I, V>;
241 fn into_iter(self) -> Self::IntoIter {
242 self.items.into_iter()
243 }
244}
245
246impl<'a, I: EntityId, V: EntityKey, RS: BuildHasher> IntoIterator for &'a EntityPartMap<I, V, RS> {
247 type Item = (I, &'a V);
248 type IntoIter = crate::part::Iter<'a, I, V>;
249 fn into_iter(self) -> Self::IntoIter {
250 self.iter()
251 }
252}
253
254impl<'a, I: EntityId, V: EntityKey, RS: BuildHasher> IntoIterator
255 for &'a mut EntityPartMap<I, V, RS>
256{
257 type Item = (I, &'a mut V);
258 type IntoIter = crate::part::IterMut<'a, I, V>;
259 fn into_iter(self) -> Self::IntoIter {
260 self.iter_mut()
261 }
262}
263
264impl<I: EntityId, V: EntityKey, RS: BuildHasher> Index<I> for EntityPartMap<I, V, RS> {
265 type Output = V;
266 fn index(&self, index: I) -> &V {
267 &self.items[index]
268 }
269}
270
271impl<I: EntityId, V: EntityKey, RS: BuildHasher> IndexMut<I> for EntityPartMap<I, V, RS> {
272 fn index_mut(&mut self, index: I) -> &mut V {
273 &mut self.items[index]
274 }
275}
276
277#[cfg(feature = "bincode")]
278mod bincode;