Skip to main content

deferred_map/
secondary.rs

1use crate::utils::unlikely;
2use crate::{DeferredMap, Key, identity::MapToken};
3use std::{collections::TryReserveError, error::Error, fmt};
4
5/// Errors returned when a `SecondaryMap` rejects an insertion.
6#[derive(Debug)]
7pub enum SecondaryMapInsertError {
8    /// Index 0 is reserved for the primary map's sentinel slot.
9    SentinelIndex,
10    /// The key index cannot be represented as a valid slot length.
11    IndexOutOfRange { index: u32 },
12    /// The backing slot vector could not reserve the requested capacity.
13    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/// Errors returned when a `SecondaryMap` cannot bind to a primary map.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum SecondaryMapBindError {
35    /// The serialized secondary data belongs to another primary map.
36    AssociationMismatch,
37    /// The secondary map is already bound to another runtime map instance.
38    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/// 存储值及其所属的代数(generation)。
55/// Internal slot storage for SecondaryMap.
56///
57/// Stores the value and the generation it belongs to.
58///
59/// SecondaryMap 的内部 slot 存储。
60/// 存储值及其所属的代数(generation)。
61#[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/// A secondary map that associates data with keys from a `DeferredMap`.
81///
82/// `SecondaryMap` allows you to store additional information for each key in a `DeferredMap`.
83/// It is separate from the primary map and does not affect the primary map's memory layout.
84///
85/// Key Features:
86/// - **Sparse Storage**: Efficiently handles cases where not all keys in the primary map have associated data.
87/// - **Generation Checking**: Automatically validates compatibility with the primary map's keys.
88///   Stale keys (from older generations) will be ignored or overwritten as appropriate.
89/// - **Automatic Expansion**: The map automatically grows to accommodate keys with larger indices.
90///
91///
92/// 一个辅助映射(SecondaryMap),用于将数据与 `DeferredMap` 的 Key 关联。
93///
94/// `SecondaryMap` 允许你为 `DeferredMap` 中的每个 Key 存储额外信息。
95/// 它与主映射分离,不影响主映射的内存布局。
96///
97/// 主要特性:
98/// - **稀疏存储**:高效处理主映射中并非所有 Key 都有关联数据的情况。
99/// - **代数检查**:自动验证与主映射 Key 的兼容性。过期的 Key(来自旧代数)将被忽略或覆盖。
100/// - **自动扩展**:映射会自动增长以适应具有更大索引的 Key。
101///
102/// # Examples (示例)
103///
104/// ```
105/// use deferred_map::{DeferredMap, SecondaryMap};
106///
107/// let mut map = DeferredMap::new();
108/// let handle = map.alloc();
109/// let key = handle.key();
110/// map.insert(handle, "Primary Value");
111///
112/// let mut sec_map = SecondaryMap::new();
113/// sec_map.bind_to(&map).expect("secondary map binding should succeed");
114/// sec_map.insert(key, 100).expect("secondary map insertion should succeed");
115///
116/// assert_eq!(sec_map.get(key), Some(&100));
117/// ```
118#[derive(Clone)]
119pub struct SecondaryMap<T, K: Key = crate::DefaultKey> {
120    // We use Option to represent presence.
121    // None means no value associated with this index for the stored generation.
122    // Even if Some is present, we must check generation matching.
123    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    /// Create a new empty SecondaryMap
138    ///
139    /// 创建一个新的空 SecondaryMap
140    #[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    /// Create a SecondaryMap with specified capacity
152    ///
153    /// 创建一个指定容量的 SecondaryMap
154    #[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    /// Bind this map to a primary `DeferredMap`.
166    ///
167    /// A map created by serde is detached because runtime identity is not
168    /// persisted. Bind it to the corresponding primary map before reading,
169    /// mutating, or inserting values.
170    ///
171    /// The persisted association token is checked before the runtime identity
172    /// is attached. A mismatch leaves this `SecondaryMap` unchanged.
173    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    /// Insert a value for a specific key
207    ///
208    /// The map must be bound to a primary `DeferredMap` before insertion. If
209    /// the key belongs to an older generation than what is currently stored,
210    /// the insertion is ignored. If the key is newer, it overwrites the
211    /// existing value.
212    ///
213    /// 为特定 Key 插入值
214    ///
215    /// 如果 Key 的代数(generation)老于当前存储的代数,插入将被忽略。
216    /// 如果 Key 是新的,它将覆盖现有值。
217    ///
218    /// # Returns
219    /// - `Ok(Some(old_value))` if a value existed for the EXACT same key
220    ///   (same index and generation).
221    /// - `Ok(None)` otherwise.
222    ///
223    /// # Errors
224    /// Returns [`SecondaryMapInsertError`] if the key uses the primary map's
225    /// sentinel index, cannot be represented as a slot length, or the backing
226    /// vector cannot reserve enough capacity.
227    ///
228    /// # Panics
229    /// Panics if the map has not been bound to a primary `DeferredMap`, or if
230    /// `key` was created by a different primary map instance.
231    ///
232    /// 如果 map 尚未绑定到主 `DeferredMap`,或 `key` 来自另一个主 map 实例,
233    /// 则会 panic。
234    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        // Ensure we have enough slots
257        // 确保有足够的 slot
258        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                    // Exact match, replace value
272                    // 完全匹配,替换值
273                    Ok(Some(std::mem::replace(&mut slot.value, value)))
274                } else if slot.generation() < generation {
275                    // Stale slot (older generation), overwrite with new data
276                    // 槽位过期(旧代数),用新数据覆盖
277                    // Note: We don't return the old value because it belongs to a different entity (older gen)
278                    let old_slot = slot_opt.replace(Slot::new(value, generation));
279                    drop(old_slot);
280                    Ok(None)
281                } else {
282                    // Incoming key is older than stored data, ignore insert
283                    // 传入的 Key 比存储的数据旧,忽略插入
284                    Ok(None)
285                }
286            }
287            None => {
288                // Empty slot, insert new
289                // 空槽位,插入新值
290                *slot_opt = Some(Slot::new(value, generation));
291                self.num_elems += 1;
292                Ok(None)
293            }
294        }
295    }
296
297    /// Remove value by key
298    ///
299    /// Only removes if both index and generation match.
300    ///
301    /// 通过 Key 移除值
302    ///
303    /// 仅当索引和代数都匹配时才移除。
304    ///
305    /// # Panics
306    /// Panics if this non-empty map has not been bound to a primary map, or if
307    /// `key` was created by a different primary map instance.
308    ///
309    /// 如果非空 map 尚未绑定到主 map,或 `key` 来自另一个主 map 实例,则会 panic。
310    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    /// Get reference to value by key
340    ///
341    /// 通过 Key 获取值的引用
342    ///
343    /// # Panics
344    /// Panics if this non-empty map has not been bound to a primary map, or if
345    /// `key` was created by a different primary map instance.
346    ///
347    /// 如果非空 map 尚未绑定到主 map,或 `key` 来自另一个主 map 实例,则会 panic。
348    #[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        // SAFETY: Bounds checked above
367        match unsafe { self.slots.get_unchecked(index) } {
368            Some(slot) if slot.generation() == generation => Some(&slot.value),
369            _ => None,
370        }
371    }
372
373    /// Get mutable reference to value by key
374    ///
375    /// 通过 Key 获取值的可变引用
376    ///
377    /// # Panics
378    /// Panics if this non-empty map has not been bound to a primary map, or if
379    /// `key` was created by a different primary map instance.
380    ///
381    /// 如果非空 map 尚未绑定到主 map,或 `key` 来自另一个主 map 实例,则会 panic。
382    #[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        // SAFETY: Bounds checked above
401        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    /// Check if key exists
408    ///
409    /// 检查 Key 是否存在
410    ///
411    /// # Panics
412    /// Panics if this non-empty map has not been bound to a primary map, or if
413    /// `key` was created by a different primary map instance.
414    ///
415    /// 如果非空 map 尚未绑定到主 map,或 `key` 来自另一个主 map 实例,则会 panic。
416    #[inline]
417    pub fn contains_key(&self, key: K) -> bool {
418        self.get(key).is_some()
419    }
420
421    /// Return the number of elements
422    ///
423    /// 返回元素数量
424    #[inline]
425    pub fn len(&self) -> usize {
426        self.num_elems
427    }
428
429    /// Check if empty
430    ///
431    /// 检查是否为空
432    #[inline]
433    pub fn is_empty(&self) -> bool {
434        self.num_elems == 0
435    }
436
437    /// Capacity of the underlying vector
438    ///
439    /// 底层 vector 的容量
440    #[inline]
441    pub fn capacity(&self) -> usize {
442        self.slots.capacity()
443    }
444
445    /// Clear all elements
446    ///
447    /// Does not deallocate memory, but clears validity.
448    ///
449    /// 清空所有元素
450    /// 不会释放内存,但会清除有效性。
451    pub fn clear(&mut self) {
452        self.num_elems = 0;
453        self.map_id = None;
454        self.association_token = None;
455
456        // Drain removes the slots from the map before their values are dropped.
457        // This keeps the empty, unbound state valid if a destructor panics.
458        let slots = self.slots.drain(..);
459        drop(slots);
460    }
461
462    /// Retains only the elements specified by the predicate.
463    ///
464    /// 只保留满足谓词的元素。
465    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    /// Iterator over all (key, value) pairs
488    ///
489    /// 遍历所有 (key, value) 对的迭代器
490    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    /// Mutable iterator over all (key, value) pairs
504    ///
505    /// 遍历所有 (key, value) 对的可变迭代器
506    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        // Slot<u32> layout:
632        // value: u32 (4 bytes)
633        // value: u32 (4 bytes)
634        // generation_p1: Generation (4 bytes)
635        // Total: 8 bytes
636        // Option<Slot<u32>>: Should be 8 bytes because strict NonZeroU32 allows 0 to be None.
637        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        // Slot<u64> layout:
645        // value: u64 (8 bytes)
646        // generation: Generation (4 bytes)
647        // padding: 4 bytes
648        // Total: 16 bytes. Alignment 8.
649        // Option<Slot<u64>>: Should use the niche in generation.
650        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}