deferred-map 0.4.0

High-performance generational arena using handle-based deferred insertion with O(1) operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::fmt;
use std::mem::ManuallyDrop;

/// Internal slot storage using union for memory optimization
///
/// When occupied, stores the value; when vacant, stores the next free slot index.
///
/// Slot 内部存储,使用 union 优化内存
///
/// 占用时存储值,空闲时存储下一个空闲 slot 的索引
pub(crate) union SlotUnion<T> {
    pub(crate) value: ManuallyDrop<T>,
    pub(crate) next_free: u32,
}

/// Slot stores the actual value and version information
///
/// Version uses lowest 2 bits for state (0b00=vacant, 0b01=reserved, 0b11=occupied)
/// and upper 30 bits for generation counter.
///
/// Slot 存储实际的值和 version 信息
///
/// version 的最低 2 位表示状态(0b00=空闲, 0b01=预留, 0b11=占用)
/// 高 30 位为代数计数器
pub(crate) struct Slot<T> {
    pub(crate) u: SlotUnion<T>,
    pub(crate) version: crate::Version, // Low 2 bits: state, High 30 bits: generation | 低2位:状态,高30位:代数
}

/// Safe API to read slot content
///
/// 安全的 API 来读取 slot
pub(crate) enum SlotContent<'a, T: 'a> {
    /// Occupied slot with value
    ///
    /// 占用 slot 的值
    Occupied(&'a T),

    /// Vacant slot with next free index
    ///
    /// 空闲 slot 的索引
    Vacant(&'a u32),

    /// Retired slot that cannot be reused
    ///
    /// 已退休且不能复用的 slot
    Retired,
}

/// Safe API to read mutable slot content
///
/// 安全的 API 来读取可变 slot
pub(crate) enum SlotContentMut<'a, T: 'a> {
    /// Occupied slot with mutable reference
    ///
    /// 占用 slot 的可变引用
    OccupiedMut(&'a mut T),

    /// Non-occupied slot
    ///
    /// 非占用 slot
    VacantMut,
}

use self::SlotContent::{Occupied, Retired, Vacant};
use self::SlotContentMut::{OccupiedMut, VacantMut};

impl<T> Slot<T> {
    /// Get the state bits (lowest 2 bits of version)
    ///
    /// 获取状态位(version 的最低 2 位)
    #[inline(always)]
    #[allow(unused)]
    pub(crate) fn is_vacant(&self) -> bool {
        self.version.is_vacant()
    }

    /// Check if slot is reserved (state bits == 0b01)
    ///
    /// 检查 slot 是否已预留(状态位 == 0b01)
    #[inline(always)]
    pub(crate) fn is_reserved(&self) -> bool {
        self.version.is_reserved()
    }

    /// Check if slot is occupied (state bits == 0b11)
    ///
    /// 检查 slot 是否被占用(状态位 == 0b11)
    #[inline(always)]
    pub(crate) fn is_occupied(&self) -> bool {
        self.version.is_occupied()
    }

    /// Get the generation from version (excludes state bits)
    ///
    /// 从 version 中获取 generation(不包含状态位)
    #[inline(always)]
    pub(crate) fn generation(&self) -> crate::Generation {
        self.version.generation()
    }

    /// Safely get slot content
    ///
    /// Only returns content for Vacant (next_free) or Occupied (value) states.
    /// Reserved and retired states do not expose union contents.
    ///
    /// 安全地获取 slot 内容
    ///
    /// 只返回 Vacant (next_free) 或 Occupied (value) 状态的内容
    /// Reserved 和 retired 状态不会暴露 union 内容
    #[inline(always)]
    pub(crate) fn get<'a>(&'a self) -> SlotContent<'a, T> {
        unsafe {
            if self.is_occupied() {
                Occupied(&*self.u.value)
            } else if self.version.is_retired() {
                Retired
            } else {
                // Reserved stores no meaningful union value.
                // reserved 不保存有意义的 union 值。
                Vacant(&self.u.next_free)
            }
        }
    }

    /// Safely get mutable slot content
    ///
    /// Only returns content for Vacant (next_free) or Occupied (value) states.
    /// Reserved and retired states are treated as non-occupied for safety.
    ///
    /// 安全地获取 slot 可变内容
    ///
    /// 只返回 Vacant (next_free) 或 Occupied (value) 状态的内容
    /// Reserved 和 retired 状态出于安全考虑视为非 occupied
    #[inline(always)]
    pub(crate) fn get_mut<'a>(&'a mut self) -> SlotContentMut<'a, T> {
        unsafe {
            if self.is_occupied() {
                OccupiedMut(&mut *self.u.value)
            } else {
                VacantMut
            }
        }
    }
}

impl<T> Drop for Slot<T> {
    #[inline]
    fn drop(&mut self) {
        if std::mem::needs_drop::<T>() && self.is_occupied() {
            // Only drop value when occupied
            // 只有在占用状态时才 drop 值
            unsafe {
                ManuallyDrop::drop(&mut self.u.value);
            }
        }
    }
}

impl<T: Clone> Clone for Slot<T> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            u: match self.get() {
                Occupied(value) => SlotUnion {
                    value: ManuallyDrop::new(value.clone()),
                },
                Vacant(&next_free) => SlotUnion { next_free },
                Retired => SlotUnion { next_free: 0 },
            },
            version: self.version,
        }
    }

    #[inline]
    fn clone_from(&mut self, source: &Self) {
        match source.get() {
            Occupied(source_value) => {
                if self.is_occupied() {
                    if let OccupiedMut(self_value) = self.get_mut() {
                        self_value.clone_from(source_value);
                    }
                } else {
                    self.u = SlotUnion {
                        value: ManuallyDrop::new(source_value.clone()),
                    };
                }
            }
            Vacant(&next_free) => {
                if self.is_occupied() {
                    // Make the slot non-occupied before dropping the old value so a
                    // panicking destructor cannot be run again by `Slot::drop`.
                    let old_value = unsafe { ManuallyDrop::take(&mut self.u.value) };
                    self.u = SlotUnion { next_free };
                    self.version = source.version;
                    drop(old_value);
                    return;
                }

                self.u = SlotUnion { next_free };
            }
            Retired => {
                if self.is_occupied() {
                    // Make the slot non-occupied before dropping the old value so a
                    // panicking destructor cannot be run again by `Slot::drop`.
                    let old_value = unsafe { ManuallyDrop::take(&mut self.u.value) };
                    self.u = SlotUnion { next_free: 0 };
                    self.version = source.version;
                    drop(old_value);
                    return;
                }

                self.u = SlotUnion { next_free: 0 };
            }
        }
        self.version = source.version;
    }
}

impl<T: fmt::Debug> fmt::Debug for Slot<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let mut builder = fmt.debug_struct("Slot");
        builder.field("version", &self.version);
        match self.get() {
            Occupied(value) => builder.field("value", value).finish(),
            Vacant(next_free) => builder.field("next_free", next_free).finish(),
            Retired => builder.field("retired", &true).finish(),
        }
    }
}

#[cfg(test)]
mod clone_tests {
    use super::*;
    use std::sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    };

    struct DropCounter(Arc<AtomicUsize>);

    impl Clone for DropCounter {
        fn clone(&self) -> Self {
            Self(self.0.clone())
        }
    }

    impl Drop for DropCounter {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }
    }

    #[test]
    fn clone_from_drops_occupied_target_before_overwriting_state() {
        let drop_count = Arc::new(AtomicUsize::new(0));
        let occupied_version = crate::Version::new(crate::Generation::MIN, 0b11).unwrap();
        let vacant_version = crate::Version::new(crate::Generation::MIN, 0b00).unwrap();
        let mut target = Slot {
            u: SlotUnion {
                value: ManuallyDrop::new(DropCounter(drop_count.clone())),
            },
            version: occupied_version,
        };
        let source = Slot {
            u: SlotUnion { next_free: 7 },
            version: vacant_version,
        };

        target.clone_from(&source);

        assert!(target.is_vacant());
        assert_eq!(drop_count.load(Ordering::SeqCst), 1);
        unsafe {
            assert_eq!(target.u.next_free, 7);
        }

        drop(target);
        drop(source);
        assert_eq!(drop_count.load(Ordering::SeqCst), 1);
    }
}

#[cfg(feature = "serde")]
impl<T: serde::Serialize> serde::Serialize for Slot<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("Slot", 2)?;
        state.serialize_field("version", &self.version)?;

        #[derive(serde::Serialize)]
        enum SlotInner<'a, T> {
            Occupied(&'a T),
            Vacant(u32),
            Reserved,
            Retired,
        }

        let inner = if self.is_occupied() {
            unsafe { SlotInner::Occupied(&*self.u.value) }
        } else if self.is_reserved() {
            SlotInner::Reserved
        } else if self.version.is_retired() {
            SlotInner::Retired
        } else {
            unsafe { SlotInner::Vacant(self.u.next_free) }
        };

        state.serialize_field("inner", &inner)?;
        state.end()
    }
}

#[cfg(feature = "serde")]
impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for Slot<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        struct SlotHelper<T> {
            version: crate::Version,
            inner: SlotInnerOwned<T>,
        }

        #[derive(serde::Deserialize)]
        enum SlotInnerOwned<T> {
            Occupied(T),
            Vacant(u32),
            Reserved,
            Retired,
        }

        let helper = SlotHelper::<T>::deserialize(deserializer)?;

        let state_bits = helper.version.state();
        match (&helper.inner, state_bits) {
            (SlotInnerOwned::Occupied(_), 0b11) => {}
            (SlotInnerOwned::Vacant(_), 0b00) => {}
            (SlotInnerOwned::Reserved, 0b01) => {}
            (SlotInnerOwned::Retired, 0b10) => {}
            _ => {
                return Err(serde::de::Error::custom(
                    "Slot version and content mismatch",
                ));
            }
        }

        let u = match helper.inner {
            SlotInnerOwned::Occupied(val) => SlotUnion {
                value: ManuallyDrop::new(val),
            },
            SlotInnerOwned::Vacant(next) => SlotUnion { next_free: next },
            SlotInnerOwned::Reserved => SlotUnion { next_free: 0 },
            SlotInnerOwned::Retired => SlotUnion { next_free: 0 },
        };

        Ok(Slot {
            u,
            version: helper.version,
        })
    }
}

#[cfg(all(test, feature = "serde"))]
mod tests {
    use super::*;

    #[test]
    fn test_slot_occupied_serde() {
        let slot = Slot {
            u: SlotUnion {
                value: ManuallyDrop::new(42),
            },
            version: crate::Version::new(crate::Generation::MIN, 0b11).unwrap(),
        };

        let serialized = serde_json::to_string(&slot).expect("Failed to serialize");
        let deserialized: Slot<i32> =
            serde_json::from_str(&serialized).expect("Failed to deserialize");

        assert!(deserialized.is_occupied());
        assert_eq!(deserialized.generation().get(), 1);
        if let Occupied(val) = deserialized.get() {
            assert_eq!(*val, 42);
        } else {
            panic!("Expected Occupied");
        }
    }

    #[test]
    fn test_slot_vacant_serde() {
        let slot: Slot<i32> = Slot {
            u: SlotUnion { next_free: 10 },
            version: crate::Version::new(crate::Generation::new(2).unwrap(), 0b00).unwrap(),
        };

        let serialized = serde_json::to_string(&slot).expect("Failed to serialize");
        let deserialized: Slot<i32> =
            serde_json::from_str(&serialized).expect("Failed to deserialize");

        assert!(deserialized.is_vacant());
        assert_eq!(deserialized.generation().get(), 2);
        if let Vacant(next) = deserialized.get() {
            assert_eq!(*next, 10);
        } else {
            panic!("Expected Vacant");
        }
    }

    #[test]
    fn test_slot_reserved_serde() {
        let slot: Slot<i32> = Slot {
            u: SlotUnion { next_free: 0 },
            version: crate::Version::new(crate::Generation::new(3).unwrap(), 0b01).unwrap(),
        };

        let serialized = serde_json::to_string(&slot).expect("Failed to serialize");
        let deserialized: Slot<i32> =
            serde_json::from_str(&serialized).expect("Failed to deserialize");

        assert!(deserialized.is_reserved());
        assert_eq!(deserialized.generation().get(), 3);
    }

    #[test]
    fn test_slot_retired_serde() {
        let slot: Slot<i32> = Slot {
            u: SlotUnion { next_free: 0 },
            version: crate::Version::new(crate::Generation::MAX, 0b10).unwrap(),
        };

        let serialized = serde_json::to_string(&slot).expect("Failed to serialize");
        let deserialized: Slot<i32> =
            serde_json::from_str(&serialized).expect("Failed to deserialize");

        assert!(deserialized.version.is_retired());
        assert_eq!(deserialized.generation(), crate::Generation::MAX);
    }
}