deferred_map/secondary.rs
1use crate::utils::{decode_key, encode_key, unlikely};
2use std::fmt;
3
4/// Internal slot storage for SecondaryMap.
5///
6/// Stores the value and the generation it belongs to.
7///
8/// SecondaryMap 的内部 slot 存储。
9/// 存储值及其所属的代数(generation)。
10#[derive(Clone, Debug)]
11struct Slot<T> {
12 value: T,
13 generation: u32,
14}
15
16/// A secondary map that associates data with keys from a `DeferredMap`.
17///
18/// `SecondaryMap` allows you to store additional information for each key in a `DeferredMap`.
19/// It is separate from the primary map and does not affect the primary map's memory layout.
20///
21/// Key Features:
22/// - **Sparse Storage**: Efficiently handles cases where not all keys in the primary map have associated data.
23/// - **Generation Checking**: Automatically validates compatibility with the primary map's keys.
24/// Stale keys (from older generations) will be ignored or overwritten as appropriate.
25/// - **Automatic Expansion**: The map automatically grows to accommodate keys with larger indices.
26///
27///
28/// 一个辅助映射(SecondaryMap),用于将数据与 `DeferredMap` 的 Key 关联。
29///
30/// `SecondaryMap` 允许你为 `DeferredMap` 中的每个 Key 存储额外信息。
31/// 它与主映射分离,不影响主映射的内存布局。
32///
33/// 主要特性:
34/// - **稀疏存储**:高效处理主映射中并非所有 Key 都有关联数据的情况。
35/// - **代数检查**:自动验证与主映射 Key 的兼容性。过期的 Key(来自旧代数)将被忽略或覆盖。
36/// - **自动扩展**:映射会自动增长以适应具有更大索引的 Key。
37///
38/// # Examples (示例)
39///
40/// ```
41/// use deferred_map::{DeferredMap, SecondaryMap};
42///
43/// let mut map = DeferredMap::new();
44/// let handle = map.allocate_handle();
45/// let key = handle.key();
46/// map.insert(handle, "Primary Value");
47///
48/// let mut sec_map = SecondaryMap::new();
49/// sec_map.insert(key, 100);
50///
51/// assert_eq!(sec_map.get(key), Some(&100));
52/// ```
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54#[derive(Clone)]
55pub struct SecondaryMap<T> {
56 // We use Option to represent presence.
57 // None means no value associated with this index for the stored generation.
58 // Even if Some is present, we must check generation matching.
59 slots: Vec<Option<Slot<T>>>,
60 num_elems: usize,
61}
62
63impl<T> Default for SecondaryMap<T> {
64 fn default() -> Self {
65 Self::new()
66 }
67}
68
69impl<T> SecondaryMap<T> {
70 /// Create a new empty SecondaryMap
71 ///
72 /// 创建一个新的空 SecondaryMap
73 #[inline]
74 pub fn new() -> Self {
75 Self {
76 slots: Vec::new(),
77 num_elems: 0,
78 }
79 }
80
81 /// Create a SecondaryMap with specified capacity
82 ///
83 /// 创建一个指定容量的 SecondaryMap
84 #[inline]
85 pub fn with_capacity(capacity: usize) -> Self {
86 Self {
87 slots: Vec::with_capacity(capacity),
88 num_elems: 0,
89 }
90 }
91
92 /// Insert a value for a specific key
93 ///
94 /// If the key belongs to an older generation than what is currently stored, the insertion is ignored.
95 /// If the key is newer, it overwrites the existing value.
96 ///
97 /// 为特定 Key 插入值
98 ///
99 /// 如果 Key 的代数(generation)老于当前存储的代数,插入将被忽略。
100 /// 如果 Key 是新的,它将覆盖现有值。
101 ///
102 /// # Returns
103 /// - `Some(old_value)` if a value existed for the EXACT same key (same index and generation).
104 /// - `None` otherwise.
105 pub fn insert(&mut self, key: u64, value: T) -> Option<T> {
106 let (index, generation) = decode_key(key);
107 let index = index as usize;
108
109 // Ensure we have enough slots
110 // 确保有足够的 slot
111 if index >= self.slots.len() {
112 let required_additional = index - self.slots.len() + 1;
113 self.slots.reserve(required_additional);
114 self.slots.resize_with(index + 1, || None);
115 }
116
117 let slot_opt = unsafe { self.slots.get_unchecked_mut(index) };
118
119 match slot_opt {
120 Some(slot) => {
121 if slot.generation == generation {
122 // Exact match, replace value
123 // 完全匹配,替换值
124 Some(std::mem::replace(&mut slot.value, value))
125 } else if slot.generation < generation {
126 // Stale slot (older generation), overwrite with new data
127 // 槽位过期(旧代数),用新数据覆盖
128 // Note: We don't return the old value because it belongs to a different entity (older gen)
129 *slot = Slot { value, generation };
130 None
131 } else {
132 // Incoming key is older than stored data, ignore insert
133 // 传入的 Key 比存储的数据旧,忽略插入
134 None
135 }
136 }
137 None => {
138 // Empty slot, insert new
139 // 空槽位,插入新值
140 *slot_opt = Some(Slot { value, generation });
141 self.num_elems += 1;
142 None
143 }
144 }
145 }
146
147 /// Remove value by key
148 ///
149 /// Only removes if both index and generation match.
150 ///
151 /// 通过 Key 移除值
152 ///
153 /// 仅当索引和代数都匹配时才移除。
154 pub fn remove(&mut self, key: u64) -> Option<T> {
155 let (index, generation) = decode_key(key);
156 let index = index as usize;
157
158 if unlikely(index >= self.slots.len()) {
159 return None;
160 }
161
162 let slot_opt = unsafe { self.slots.get_unchecked_mut(index) };
163
164 if let Some(slot) = slot_opt {
165 if slot.generation == generation {
166 self.num_elems -= 1;
167 return slot_opt.take().map(|s| s.value);
168 }
169 }
170
171 None
172 }
173
174 /// Get reference to value by key
175 ///
176 /// 通过 Key 获取值的引用
177 #[inline]
178 pub fn get(&self, key: u64) -> Option<&T> {
179 let (index, generation) = decode_key(key);
180 let index = index as usize;
181
182 if unlikely(index >= self.slots.len()) {
183 return None;
184 }
185
186 // SAFETY: Bounds checked above
187 match unsafe { self.slots.get_unchecked(index) } {
188 Some(slot) if slot.generation == generation => Some(&slot.value),
189 _ => None,
190 }
191 }
192
193 /// Get mutable reference to value by key
194 ///
195 /// 通过 Key 获取值的可变引用
196 #[inline]
197 pub fn get_mut(&mut self, key: u64) -> Option<&mut T> {
198 let (index, generation) = decode_key(key);
199 let index = index as usize;
200
201 if unlikely(index >= self.slots.len()) {
202 return None;
203 }
204
205 // SAFETY: Bounds checked above
206 match unsafe { self.slots.get_unchecked_mut(index) } {
207 Some(slot) if slot.generation == generation => Some(&mut slot.value),
208 _ => None,
209 }
210 }
211
212 /// Check if key exists
213 ///
214 /// 检查 Key 是否存在
215 #[inline]
216 pub fn contains_key(&self, key: u64) -> bool {
217 self.get(key).is_some()
218 }
219
220 /// Return the number of elements
221 ///
222 /// 返回元素数量
223 #[inline]
224 pub fn len(&self) -> usize {
225 self.num_elems
226 }
227
228 /// Check if empty
229 ///
230 /// 检查是否为空
231 #[inline]
232 pub fn is_empty(&self) -> bool {
233 self.num_elems == 0
234 }
235
236 /// Capacity of the underlying vector
237 ///
238 /// 底层 vector 的容量
239 #[inline]
240 pub fn capacity(&self) -> usize {
241 self.slots.capacity()
242 }
243
244 /// Clear all elements
245 ///
246 /// Does not deallocate memory, but clears validity.
247 ///
248 /// 清空所有元素
249 /// 不会释放内存,但会清除有效性。
250 pub fn clear(&mut self) {
251 self.slots.clear();
252 self.num_elems = 0;
253 }
254
255 /// Retains only the elements specified by the predicate.
256 ///
257 /// 只保留满足谓词的元素。
258 pub fn retain<F>(&mut self, mut f: F)
259 where
260 F: FnMut(u64, &mut T) -> bool,
261 {
262 for (index, slot_opt) in self.slots.iter_mut().enumerate() {
263 if let Some(slot) = slot_opt {
264 let key = encode_key(index as u32, slot.generation);
265 if !f(key, &mut slot.value) {
266 *slot_opt = None;
267 self.num_elems -= 1;
268 }
269 }
270 }
271 }
272
273 /// Iterator over all (key, value) pairs
274 ///
275 /// 遍历所有 (key, value) 对的迭代器
276 pub fn iter(&self) -> impl Iterator<Item = (u64, &T)> {
277 self.slots
278 .iter()
279 .enumerate()
280 .filter_map(|(index, slot_opt)| {
281 slot_opt.as_ref().map(|slot| {
282 let key = encode_key(index as u32, slot.generation);
283 (key, &slot.value)
284 })
285 })
286 }
287
288 /// Mutable iterator over all (key, value) pairs
289 ///
290 /// 遍历所有 (key, value) 对的可变迭代器
291 pub fn iter_mut(&mut self) -> impl Iterator<Item = (u64, &mut T)> {
292 self.slots
293 .iter_mut()
294 .enumerate()
295 .filter_map(|(index, slot_opt)| {
296 slot_opt.as_mut().map(|slot| {
297 let key = encode_key(index as u32, slot.generation);
298 (key, &mut slot.value)
299 })
300 })
301 }
302}
303
304impl<T: fmt::Debug> fmt::Debug for SecondaryMap<T> {
305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306 f.debug_map().entries(self.iter()).finish()
307 }
308}