1use crate::utils::unlikely;
2use crate::{DeferredMap, Key, identity::MapToken};
3use std::{collections::TryReserveError, error::Error, fmt};
4
5#[derive(Debug)]
7pub enum SecondaryMapInsertError {
8 SentinelIndex,
10 IndexOutOfRange { index: u32 },
12 Allocation(TryReserveError),
14}
15
16impl fmt::Display for SecondaryMapInsertError {
17 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18 match self {
19 Self::SentinelIndex => {
20 f.write_str("SecondaryMap key index 0 is reserved for the primary map sentinel")
21 }
22 Self::IndexOutOfRange { index } => {
23 write!(f, "SecondaryMap key index {index} is out of range")
24 }
25 Self::Allocation(_) => f.write_str("failed to reserve SecondaryMap storage"),
26 }
27 }
28}
29
30impl Error for SecondaryMapInsertError {}
31
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum SecondaryMapBindError {
35 AssociationMismatch,
37 AlreadyBoundToAnotherMap,
39}
40
41impl fmt::Display for SecondaryMapBindError {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 match self {
44 Self::AssociationMismatch => f.write_str("SecondaryMap belongs to another primary map"),
45 Self::AlreadyBoundToAnotherMap => {
46 f.write_str("SecondaryMap is already bound to another map instance")
47 }
48 }
49 }
50}
51
52impl Error for SecondaryMapBindError {}
53
54#[derive(Clone, Debug)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub(crate) struct Slot<T> {
64 value: T,
65 generation: crate::Generation,
66}
67
68impl<T> Slot<T> {
69 #[inline(always)]
70 fn new(value: T, generation: crate::Generation) -> Self {
71 Self { value, generation }
72 }
73
74 #[inline(always)]
75 fn generation(&self) -> crate::Generation {
76 self.generation
77 }
78}
79
80#[derive(Clone)]
119pub struct SecondaryMap<T, K: Key = crate::DefaultKey> {
120 slots: Vec<Option<Slot<T>>>,
124 num_elems: usize,
125 map_id: Option<u64>,
126 association_token: Option<MapToken>,
127 _marker: std::marker::PhantomData<K>,
128}
129
130impl<T, K: Key> Default for SecondaryMap<T, K> {
131 fn default() -> Self {
132 Self::new()
133 }
134}
135
136impl<T, K: Key> SecondaryMap<T, K> {
137 #[inline]
141 pub fn new() -> Self {
142 Self {
143 slots: Vec::new(),
144 num_elems: 0,
145 map_id: None,
146 association_token: None,
147 _marker: std::marker::PhantomData,
148 }
149 }
150
151 #[inline]
155 pub fn with_capacity(capacity: usize) -> Self {
156 Self {
157 slots: Vec::with_capacity(capacity),
158 num_elems: 0,
159 map_id: None,
160 association_token: None,
161 _marker: std::marker::PhantomData,
162 }
163 }
164
165 pub fn bind_to<M>(&mut self, map: &DeferredMap<M, K>) -> Result<(), SecondaryMapBindError> {
174 let map_id = map.map_id();
175 if let Some(current_id) = self.map_id
176 && current_id != map_id
177 {
178 return Err(SecondaryMapBindError::AlreadyBoundToAnotherMap);
179 }
180
181 if let Some(current_token) = self.association_token
182 && current_token != map.association_token()
183 {
184 return Err(SecondaryMapBindError::AssociationMismatch);
185 }
186
187 self.association_token = Some(map.association_token());
188 self.map_id = Some(map_id);
189 Ok(())
190 }
191
192 #[inline]
193 fn map_id_for_keys(&self) -> u64 {
194 match self.map_id {
195 Some(map_id) => map_id,
196 None => {
197 assert_eq!(
198 self.num_elems, 0,
199 "SecondaryMap must be bound to a DeferredMap before use"
200 );
201 0
202 }
203 }
204 }
205
206 pub fn insert(&mut self, key: K, value: T) -> Result<Option<T>, SecondaryMapInsertError> {
235 let map_id = self
236 .map_id
237 .expect("SecondaryMap must be bound to a DeferredMap before inserting");
238 assert_eq!(
239 map_id,
240 key.map_id(),
241 "Key used with wrong map instance in SecondaryMap"
242 );
243
244 let raw_index = key.index();
245 if raw_index == 0 {
246 return Err(SecondaryMapInsertError::SentinelIndex);
247 }
248
249 let generation = key.generation();
250 let index = usize::try_from(raw_index)
251 .map_err(|_| SecondaryMapInsertError::IndexOutOfRange { index: raw_index })?;
252 let required_len = index
253 .checked_add(1)
254 .ok_or(SecondaryMapInsertError::IndexOutOfRange { index: raw_index })?;
255
256 if required_len > self.slots.len() {
259 let required_additional = required_len - self.slots.len();
260 self.slots
261 .try_reserve(required_additional)
262 .map_err(SecondaryMapInsertError::Allocation)?;
263 self.slots.resize_with(required_len, || None);
264 }
265
266 let slot_opt = &mut self.slots[index];
267
268 match slot_opt {
269 Some(slot) => {
270 if slot.generation() == generation {
271 Ok(Some(std::mem::replace(&mut slot.value, value)))
274 } else if slot.generation() < generation {
275 let old_slot = slot_opt.replace(Slot::new(value, generation));
279 drop(old_slot);
280 Ok(None)
281 } else {
282 Ok(None)
285 }
286 }
287 None => {
288 *slot_opt = Some(Slot::new(value, generation));
291 self.num_elems += 1;
292 Ok(None)
293 }
294 }
295 }
296
297 pub fn remove(&mut self, key: K) -> Option<T> {
311 let map_id = self.map_id_for_keys();
312 self.map_id?;
313 assert_eq!(
314 map_id,
315 key.map_id(),
316 "Key used with wrong map instance in SecondaryMap"
317 );
318
319 let index = key.index();
320 let generation = key.generation();
321 let index = index as usize;
322
323 if unlikely(index >= self.slots.len()) {
324 return None;
325 }
326
327 let slot_opt = unsafe { self.slots.get_unchecked_mut(index) };
328
329 if let Some(slot) = slot_opt
330 && slot.generation() == generation
331 {
332 self.num_elems -= 1;
333 return slot_opt.take().map(|s| s.value);
334 }
335
336 None
337 }
338
339 #[inline]
349 pub fn get(&self, key: K) -> Option<&T> {
350 let map_id = self.map_id_for_keys();
351 self.map_id?;
352 assert_eq!(
353 map_id,
354 key.map_id(),
355 "Key used with wrong map instance in SecondaryMap"
356 );
357
358 let index = key.index();
359 let generation = key.generation();
360 let index = index as usize;
361
362 if unlikely(index >= self.slots.len()) {
363 return None;
364 }
365
366 match unsafe { self.slots.get_unchecked(index) } {
368 Some(slot) if slot.generation() == generation => Some(&slot.value),
369 _ => None,
370 }
371 }
372
373 #[inline]
383 pub fn get_mut(&mut self, key: K) -> Option<&mut T> {
384 let map_id = self.map_id_for_keys();
385 self.map_id?;
386 assert_eq!(
387 map_id,
388 key.map_id(),
389 "Key used with wrong map instance in SecondaryMap"
390 );
391
392 let index = key.index();
393 let generation = key.generation();
394 let index = index as usize;
395
396 if unlikely(index >= self.slots.len()) {
397 return None;
398 }
399
400 match unsafe { self.slots.get_unchecked_mut(index) } {
402 Some(slot) if slot.generation() == generation => Some(&mut slot.value),
403 _ => None,
404 }
405 }
406
407 #[inline]
417 pub fn contains_key(&self, key: K) -> bool {
418 self.get(key).is_some()
419 }
420
421 #[inline]
425 pub fn len(&self) -> usize {
426 self.num_elems
427 }
428
429 #[inline]
433 pub fn is_empty(&self) -> bool {
434 self.num_elems == 0
435 }
436
437 #[inline]
441 pub fn capacity(&self) -> usize {
442 self.slots.capacity()
443 }
444
445 pub fn clear(&mut self) {
452 self.num_elems = 0;
453 self.map_id = None;
454 self.association_token = None;
455
456 let slots = self.slots.drain(..);
459 drop(slots);
460 }
461
462 pub fn retain<F>(&mut self, mut f: F)
466 where
467 F: FnMut(K, &mut T) -> bool,
468 {
469 let map_id = self.map_id_for_keys();
470 for (index, slot_opt) in self.slots.iter_mut().enumerate() {
471 if let Some(slot) = slot_opt {
472 let key = K::from_parts(index as u32, slot.generation, map_id);
473
474 if !f(key, &mut slot.value) {
475 let slot = slot_opt
476 .take()
477 .expect("SecondaryMap slot disappeared during retain");
478 self.num_elems -= 1;
479
480 let Slot { value, .. } = slot;
481 drop(value);
482 }
483 }
484 }
485 }
486
487 pub fn iter(&self) -> impl Iterator<Item = (K, &T)> {
491 let map_id = self.map_id_for_keys();
492 self.slots
493 .iter()
494 .enumerate()
495 .filter_map(move |(index, slot_opt)| {
496 slot_opt.as_ref().map(|slot| {
497 let key = K::from_parts(index as u32, slot.generation, map_id);
498 (key, &slot.value)
499 })
500 })
501 }
502
503 pub fn iter_mut(&mut self) -> impl Iterator<Item = (K, &mut T)> {
507 let map_id = self.map_id_for_keys();
508
509 self.slots
510 .iter_mut()
511 .enumerate()
512 .filter_map(move |(index, slot_opt)| {
513 slot_opt.as_mut().map(|slot| {
514 let key = K::from_parts(index as u32, slot.generation, map_id);
515 (key, &mut slot.value)
516 })
517 })
518 }
519}
520
521#[cfg(feature = "serde")]
522#[derive(serde::Serialize, serde::Deserialize)]
523#[serde(tag = "state", content = "token", rename_all = "snake_case")]
524enum SecondaryMapBinding {
525 Unbound,
526 Bound(MapToken),
527}
528
529#[cfg(feature = "serde")]
530impl<T: serde::Serialize, K: Key> serde::Serialize for SecondaryMap<T, K> {
531 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
532 where
533 S: serde::Serializer,
534 {
535 #[derive(serde::Serialize)]
536 struct SecondaryMapSerializeHelper<'a, T> {
537 slots: &'a [Option<Slot<T>>],
538 num_elems: u64,
539 binding: SecondaryMapBinding,
540 }
541
542 let helper = SecondaryMapSerializeHelper {
543 slots: &self.slots,
544 num_elems: self.num_elems as u64,
545 binding: match self.association_token {
546 Some(token) => SecondaryMapBinding::Bound(token),
547 None => SecondaryMapBinding::Unbound,
548 },
549 };
550 serde::Serialize::serialize(&helper, serializer)
551 }
552}
553
554#[cfg(feature = "serde")]
555impl<'de, T: serde::Deserialize<'de>, K: Key> serde::Deserialize<'de> for SecondaryMap<T, K> {
556 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
557 where
558 D: serde::Deserializer<'de>,
559 {
560 #[derive(serde::Deserialize)]
561 #[serde(deny_unknown_fields)]
562 struct SecondaryMapDeserializeHelper<T> {
563 slots: Vec<Option<Slot<T>>>,
564 num_elems: u64,
565 binding: SecondaryMapBinding,
566 }
567
568 let helper =
569 <SecondaryMapDeserializeHelper<T> as serde::Deserialize>::deserialize(deserializer)?;
570 let actual_num_elems = helper
571 .slots
572 .iter()
573 .try_fold(0_usize, |count, slot| {
574 if slot.is_some() {
575 count.checked_add(1)
576 } else {
577 Some(count)
578 }
579 })
580 .ok_or_else(|| serde::de::Error::custom("SecondaryMap element count overflow"))?;
581
582 if helper.slots.first().is_some_and(Option::is_some) {
583 return Err(serde::de::Error::custom(
584 "SecondaryMap cannot contain the primary map sentinel index",
585 ));
586 }
587
588 let serialized_num_elems = usize::try_from(helper.num_elems).map_err(|_| {
589 serde::de::Error::custom("SecondaryMap element count exceeds platform limits")
590 })?;
591
592 if serialized_num_elems != actual_num_elems {
593 return Err(serde::de::Error::custom(
594 "SecondaryMap element count does not match occupied slots",
595 ));
596 }
597
598 let association_token = match helper.binding {
599 SecondaryMapBinding::Unbound if actual_num_elems != 0 => {
600 return Err(serde::de::Error::custom(
601 "non-empty SecondaryMap must contain an association token",
602 ));
603 }
604 SecondaryMapBinding::Unbound => None,
605 SecondaryMapBinding::Bound(token) => Some(token),
606 };
607
608 Ok(Self {
609 slots: helper.slots,
610 num_elems: actual_num_elems,
611 map_id: None,
612 association_token,
613 _marker: std::marker::PhantomData,
614 })
615 }
616}
617
618impl<T: fmt::Debug> fmt::Debug for SecondaryMap<T> {
619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 f.debug_map().entries(self.iter()).finish()
621 }
622}
623
624#[cfg(test)]
625mod tests {
626 use super::*;
627 use std::mem::size_of;
628
629 #[test]
630 fn test_slot_niche_optimization() {
631 assert_eq!(size_of::<Slot<u32>>(), 8);
638 assert_eq!(
639 size_of::<Option<Slot<u32>>>(),
640 8,
641 "Niche optimization failed for Slot<u32>"
642 );
643
644 assert_eq!(size_of::<Slot<u64>>(), 16);
651 assert_eq!(
652 size_of::<Option<Slot<u64>>>(),
653 16,
654 "Niche optimization failed for Slot<u64>"
655 );
656 }
657}