Skip to main content

paged_collections/
id_alloc.rs

1//! [`IdAllocator`]: hands out generational [`Id`]s and recycles freed ones.
2//!
3//! An [`Id`] is a 32-bit slot index plus a generation. Freeing an id makes
4//! its index available again, and the next id at that index gets the next
5//! generation, so a stale copy of the freed id never matches a live one.
6//! [`Id`] implements [`Key`], so ids work directly as keys of the other
7//! collections, where all generations of an index share one slot.
8//!
9//! | Operation | Cost |
10//! |---|---|
11//! | [`alloc`](IdAllocator::alloc), [`free`](IdAllocator::free) | amortized O(1) |
12//! | [`is_alive`](IdAllocator::is_alive), [`occupant`](IdAllocator::occupant) | O(1) |
13//! | [`iter`](IdAllocator::iter), [`retain`](IdAllocator::retain), [`clear`](IdAllocator::clear) | O([`index_bound`](IdAllocator::index_bound)) |
14//!
15//! Freed indices are reused before new ones are issued, last freed first.
16//! [`index_bound`](IdAllocator::index_bound) is therefore at most the peak
17//! number of live ids plus the number of retired indices, which keeps the
18//! paged indices of the collections compact.
19//!
20//! Each index issues at most [`MAX_GENERATION`] ids. When an id with the
21//! last generation is freed, its index is *retired*: it is never issued
22//! again, so generations never wrap.
23//!
24//! # Scope of the stale-id guarantee
25//!
26//! A freed id is never alive again *within one allocation history*. Ids
27//! carry no allocator identity: two allocators issue equal ids, and each
28//! accepts the other's. Restoring an earlier state (assigning an older
29//! clone, or deserializing an older snapshot) rolls generations back, so ids
30//! freed after that state become alive again.
31//!
32//! The module exists only on 32- and 64-bit targets, where a `u32` index
33//! converts to `usize` without loss.
34//!
35//! ```
36//! use paged_collections::id_alloc::{Id, IdAllocator};
37//! use paged_collections::sparse_map::PagedSparseMap;
38//!
39//! let mut ids = IdAllocator::new();
40//! let mut names: PagedSparseMap<Id, &str> = PagedSparseMap::new();
41//!
42//! let a = ids.alloc();
43//! names.insert(a, "a");
44//! assert!(ids.free(a));
45//!
46//! // The index is reused with a new generation; the stale id is not found.
47//! let b = ids.alloc();
48//! assert_eq!(b.index(), a.index());
49//! assert_ne!(b, a);
50//! assert!(!ids.is_alive(a));
51//! assert_eq!(names.get(b), None);
52//! ```
53
54use alloc::collections::TryReserveError;
55use alloc::vec::Vec;
56use core::fmt;
57use core::iter::{Enumerate, FusedIterator};
58use core::num::NonZeroU32;
59
60use crate::key::{DirectKey, Key};
61
62/// The largest generation an allocator issues, 2³¹. An index whose id of
63/// this generation is freed is retired. [`Id::new`] accepts larger
64/// generations, but no allocator considers such an id alive.
65pub const MAX_GENERATION: u32 = 1 << 31;
66
67/// The number of indices an allocator can issue: indices are
68/// `0..MAX_INDICES`, so [`IdAllocator::index_bound`] fits in a `u32`.
69pub const MAX_INDICES: u32 = u32::MAX;
70
71/// A generational id: a slot index and a generation.
72///
73/// Ids order by index, then generation. [`to_bits`](Id::to_bits) packs one
74/// into a `u64` (generation in the high half), for storage or for passing
75/// across an FFI boundary.
76///
77/// # Layout
78///
79/// An `Id` has size 8 and alignment 8 (at least the alignment of `u64` on
80/// every target), and its bytes are exactly those of
81/// [`to_bits`](Id::to_bits) in native byte order. FFI
82/// code may therefore view a `[Id]` as a `[u64]` of bits without copying.
83/// (The reverse is not sound: a `u64` with a zero high half is not an `Id`.)
84#[derive(Clone, Copy, PartialEq, Eq, Hash)]
85#[repr(C, align(8))]
86pub struct Id {
87    // Field order follows the byte order, so the high half of the native
88    // `u64` holds the generation.
89    #[cfg(target_endian = "little")]
90    index: u32,
91    generation: NonZeroU32,
92    #[cfg(target_endian = "big")]
93    index: u32,
94}
95
96const _: () = assert!(core::mem::size_of::<Id>() == 8 && core::mem::align_of::<Id>() == 8);
97
98impl Ord for Id {
99    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
100        (self.index, self.generation).cmp(&(other.index, other.generation))
101    }
102}
103
104impl PartialOrd for Id {
105    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
106        Some(self.cmp(other))
107    }
108}
109
110impl Id {
111    /// An id from its parts. An allocator treats it as alive only if it
112    /// currently has a live id with this index and generation (see the
113    /// [module docs](crate::id_alloc) on the scope of that check).
114    #[inline]
115    pub const fn new(index: u32, generation: NonZeroU32) -> Self {
116        Self { index, generation }
117    }
118
119    /// The slot index.
120    #[inline]
121    pub const fn index(self) -> u32 {
122        self.index
123    }
124
125    /// The generation, starting at 1 for the first id at an index.
126    #[inline]
127    pub const fn generation(self) -> NonZeroU32 {
128        self.generation
129    }
130
131    /// Packs the id as `generation << 32 | index`. Never zero.
132    #[inline]
133    pub const fn to_bits(self) -> u64 {
134        ((self.generation.get() as u64) << 32) | self.index as u64
135    }
136
137    /// Unpacks [`to_bits`](Id::to_bits); `None` if the generation half is
138    /// zero.
139    #[inline]
140    pub const fn from_bits(bits: u64) -> Option<Self> {
141        match NonZeroU32::new((bits >> 32) as u32) {
142            Some(generation) => Some(Self {
143                index: bits as u32,
144                generation,
145            }),
146            None => None,
147        }
148    }
149}
150
151impl fmt::Debug for Id {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(f, "Id({}v{})", self.index, self.generation)
154    }
155}
156
157impl Key for Id {
158    #[inline]
159    fn index(self) -> usize {
160        self.index as usize
161    }
162}
163
164/// A direct map stores only the generation; its `NonZeroU32` niche keeps
165/// `Option<(NonZeroU32, V)>` as small as `(u32, V)`.
166impl DirectKey for Id {
167    type Tag = NonZeroU32;
168
169    #[inline]
170    fn tag(self) -> NonZeroU32 {
171        self.generation
172    }
173
174    #[inline]
175    fn from_parts(index: usize, generation: NonZeroU32) -> Self {
176        // `index` came from an `Id`, so it fits in `u32`.
177        Self::new(index as u32, generation)
178    }
179}
180
181// Each index has a *version* that encodes its state:
182//
183// - 0: retired, never issued again;
184// - odd `v`: live, holding generation `v / 2 + 1`;
185// - even `v > 0`: vacant and in the free list; the next generation is
186//   `v / 2 + 1`.
187//
188// New indices start at version 1 (generation 1). Freeing adds 1, reusing
189// adds 1, so generation `g` is live at version `2g - 1`. Freeing the live
190// version `u32::MAX` (generation 2^31) would overflow, so the index is
191// retired instead.
192
193/// The generation that a live (odd) version holds.
194#[inline]
195pub(crate) fn generation_of(version: u32) -> NonZeroU32 {
196    debug_assert!(version % 2 == 1);
197    NonZeroU32::MIN.saturating_add(version >> 1)
198}
199
200/// The version at which `generation` is live, or `None` above
201/// [`MAX_GENERATION`].
202#[inline]
203pub(crate) fn live_version(generation: NonZeroU32) -> Option<u32> {
204    (generation.get() - 1).checked_mul(2).map(|v| v | 1)
205}
206
207/// Hands out generational [`Id`]s and recycles freed ones.
208///
209/// Invariants:
210///
211/// - `versions.len() <= MAX_INDICES`;
212/// - `free` holds every vacant (even, non-zero version) index exactly once,
213///   and nothing else;
214/// - `len` is the number of live (odd version) indices.
215///
216/// Equality compares the full state, including the order of the free list,
217/// so equal allocators issue the same ids from then on.
218#[derive(Clone, Default, PartialEq, Eq)]
219pub struct IdAllocator {
220    versions: Vec<u32>,
221    free: Vec<u32>,
222    len: usize,
223}
224
225impl IdAllocator {
226    /// An empty allocator. Does not allocate.
227    #[inline]
228    pub const fn new() -> Self {
229        Self {
230            versions: Vec::new(),
231            free: Vec::new(),
232            len: 0,
233        }
234    }
235
236    /// An empty allocator with room for `capacity` indices.
237    pub fn with_capacity(capacity: usize) -> Self {
238        Self {
239            versions: Vec::with_capacity(capacity),
240            free: Vec::new(),
241            len: 0,
242        }
243    }
244
245    /// Number of live ids.
246    #[inline]
247    pub fn len(&self) -> usize {
248        self.len
249    }
250
251    /// Whether no id is live.
252    #[inline]
253    pub fn is_empty(&self) -> bool {
254        self.len == 0
255    }
256
257    /// One past the largest index ever issued: every live, vacant or retired
258    /// index is below it.
259    #[inline]
260    pub fn index_bound(&self) -> usize {
261        self.versions.len()
262    }
263
264    /// Number of freed indices waiting to be reused.
265    #[inline]
266    pub fn free_len(&self) -> usize {
267        self.free.len()
268    }
269
270    /// Number of retired indices, which are never issued again.
271    #[inline]
272    pub fn retired_len(&self) -> usize {
273        self.versions.len() - self.len - self.free.len()
274    }
275
276    /// Reserves room so that the next `additional` allocations do not
277    /// reallocate.
278    ///
279    /// # Panics
280    ///
281    /// Panics if the new capacity overflows `isize::MAX` bytes.
282    pub fn reserve(&mut self, additional: usize) {
283        self.versions
284            .reserve(additional.saturating_sub(self.free.len()));
285    }
286
287    /// Like [`reserve`](IdAllocator::reserve), but returns an error instead
288    /// of panicking or aborting.
289    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
290        self.versions
291            .try_reserve(additional.saturating_sub(self.free.len()))
292    }
293
294    /// Issues an id: the most recently freed index with its next
295    /// generation, or else a new index with generation 1.
296    ///
297    /// # Panics
298    ///
299    /// Panics if all [`MAX_INDICES`] indices are live or retired. See
300    /// [`try_alloc`](IdAllocator::try_alloc).
301    #[doc(alias = "allocate")]
302    pub fn alloc(&mut self) -> Id {
303        match self.try_alloc() {
304            Some(id) => id,
305            None => panic!("IdAllocator: all {MAX_INDICES} indices are live or retired"),
306        }
307    }
308
309    /// Like [`alloc`](IdAllocator::alloc), but `None` if all indices are
310    /// live or retired.
311    #[doc(alias = "try_allocate")]
312    pub fn try_alloc(&mut self) -> Option<Id> {
313        if let Some(index) = self.free.pop() {
314            let version = &mut self.versions[index as usize];
315            debug_assert!(*version != 0 && *version % 2 == 0);
316            // A vacant version is even, so at most `u32::MAX - 1`.
317            *version += 1;
318            self.len += 1;
319            return Some(Id {
320                index,
321                generation: generation_of(*version),
322            });
323        }
324        let index = u32::try_from(self.versions.len())
325            .ok()
326            .filter(|&i| i < MAX_INDICES)?;
327        // Push first: if it panics, nothing has changed.
328        self.versions.push(1);
329        self.len += 1;
330        Some(Id {
331            index,
332            generation: NonZeroU32::MIN,
333        })
334    }
335
336    /// Whether `id` is live: issued by this allocator and not freed since.
337    #[doc(alias = "is_live")]
338    #[inline]
339    pub fn is_alive(&self, id: Id) -> bool {
340        live_version(id.generation)
341            .is_some_and(|v| self.versions.get(id.index as usize) == Some(&v))
342    }
343
344    /// The live id at `index`, if any.
345    #[inline]
346    pub fn occupant(&self, index: u32) -> Option<Id> {
347        let version = *self.versions.get(index as usize)?;
348        (version % 2 == 1).then(|| Id {
349            index,
350            generation: generation_of(version),
351        })
352    }
353
354    /// Frees `id`. Returns `false`, and changes nothing, if `id` is not
355    /// live (already freed, never issued, or another generation).
356    pub fn free(&mut self, id: Id) -> bool {
357        if !self.is_alive(id) {
358            return false;
359        }
360        self.free_live(id.index);
361        true
362    }
363
364    /// Frees the live index `index`, retiring it after its last generation.
365    fn free_live(&mut self, index: u32) {
366        let version = self.versions[index as usize];
367        debug_assert!(version % 2 == 1);
368        match version.checked_add(1) {
369            Some(vacant) => {
370                // Push first: if it panics, nothing has changed.
371                self.free.push(index);
372                self.versions[index as usize] = vacant;
373            }
374            None => self.versions[index as usize] = 0,
375        }
376        self.len -= 1;
377    }
378
379    /// Frees every live id for which `keep` returns `false`, visiting ids in
380    /// index order. If `keep` panics, the ids already visited stay freed or
381    /// kept and the allocator stays consistent.
382    pub fn retain(&mut self, mut keep: impl FnMut(Id) -> bool) {
383        for i in 0..self.versions.len() {
384            let version = self.versions[i];
385            if version % 2 == 1 {
386                // `i < versions.len() <= MAX_INDICES`, so it fits.
387                let index = i as u32;
388                if !keep(Id {
389                    index,
390                    generation: generation_of(version),
391                }) {
392                    self.free_live(index);
393                }
394            }
395        }
396    }
397
398    /// Frees every live id. Indices keep their generations, so ids issued
399    /// before stay dead.
400    pub fn clear(&mut self) {
401        self.retain(|_| false);
402    }
403
404    /// Shrinks the buffers to fit. Indices are never forgotten, because
405    /// reissuing one from generation 1 could revive stale ids.
406    pub fn shrink_to_fit(&mut self) {
407        self.versions.shrink_to_fit();
408        self.free.shrink_to_fit();
409    }
410
411    /// The raw state: the per-index versions and the free list, in the
412    /// order indices are reused (last entry first). Together with
413    /// [`try_from_raw_parts`](IdAllocator::try_from_raw_parts) this
414    /// round-trips an allocator exactly, for formats other than serde.
415    ///
416    /// A version is `0` for a retired index, odd (`2g - 1`) for a live index
417    /// of generation `g`, and even and non-zero (`2g`) for a vacant index
418    /// whose last generation was `g`.
419    #[inline]
420    pub fn raw_parts(&self) -> (&[u32], &[u32]) {
421        (&self.versions, &self.free)
422    }
423
424    /// Rebuilds an allocator from [`raw_parts`](IdAllocator::raw_parts),
425    /// validating them: at most [`MAX_INDICES`] versions, and a free list
426    /// holding every vacant index exactly once and nothing else. Memory is
427    /// linear in the input size.
428    pub fn try_from_raw_parts(versions: Vec<u32>, free: Vec<u32>) -> Result<Self, RawPartsError> {
429        if versions.len() > MAX_INDICES as usize {
430            return Err(RawPartsError::TooManyIndices);
431        }
432        let mut listed = alloc::vec![false; versions.len()];
433        for &index in &free {
434            let i = index as usize;
435            match versions.get(i) {
436                Some(&v) if v != 0 && v % 2 == 0 => {}
437                _ => return Err(RawPartsError::NotVacant),
438            }
439            if core::mem::replace(&mut listed[i], true) {
440                return Err(RawPartsError::ListedTwice);
441            }
442        }
443        let vacant = versions.iter().filter(|&&v| v != 0 && v % 2 == 0).count();
444        if vacant != free.len() {
445            return Err(RawPartsError::MissingVacant);
446        }
447        let len = versions.iter().filter(|&&v| v % 2 == 1).count();
448        Ok(IdAllocator {
449            versions,
450            free,
451            len,
452        })
453    }
454
455    /// Iterates over the live ids in index order.
456    pub fn iter(&self) -> Iter<'_> {
457        Iter {
458            inner: self.versions.iter().enumerate(),
459            remaining: self.len,
460        }
461    }
462}
463
464impl fmt::Debug for IdAllocator {
465    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466        f.debug_set().entries(self.iter()).finish()
467    }
468}
469
470impl<'a> IntoIterator for &'a IdAllocator {
471    type Item = Id;
472    type IntoIter = Iter<'a>;
473
474    fn into_iter(self) -> Iter<'a> {
475        self.iter()
476    }
477}
478
479/// Why [`IdAllocator::try_from_raw_parts`] rejected its input.
480#[derive(Clone, Copy, Debug, PartialEq, Eq)]
481#[non_exhaustive]
482pub enum RawPartsError {
483    /// More than [`MAX_INDICES`] versions.
484    TooManyIndices,
485    /// The free list holds an index that is not vacant (or out of range).
486    NotVacant,
487    /// The free list holds an index twice.
488    ListedTwice,
489    /// A vacant index is missing from the free list.
490    MissingVacant,
491}
492
493impl fmt::Display for RawPartsError {
494    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495        f.write_str(match self {
496            RawPartsError::TooManyIndices => "more than u32::MAX indices",
497            RawPartsError::NotVacant => "free list holds an index that is not vacant",
498            RawPartsError::ListedTwice => "free list holds an index twice",
499            RawPartsError::MissingVacant => "free list misses a vacant index",
500        })
501    }
502}
503
504impl core::error::Error for RawPartsError {}
505
506/// Iterator over the live ids of an [`IdAllocator`], in index order.
507#[derive(Clone)]
508pub struct Iter<'a> {
509    inner: Enumerate<core::slice::Iter<'a, u32>>,
510    remaining: usize,
511}
512
513impl Iter<'_> {
514    #[inline]
515    fn live(i: usize, version: u32) -> Option<Id> {
516        // `i < MAX_INDICES`, so it fits.
517        (version % 2 == 1).then(|| Id {
518            index: i as u32,
519            generation: generation_of(version),
520        })
521    }
522}
523
524impl Iterator for Iter<'_> {
525    type Item = Id;
526
527    fn next(&mut self) -> Option<Id> {
528        if self.remaining == 0 {
529            return None;
530        }
531        let id = self.inner.by_ref().find_map(|(i, &v)| Self::live(i, v))?;
532        self.remaining -= 1;
533        Some(id)
534    }
535
536    fn size_hint(&self) -> (usize, Option<usize>) {
537        (self.remaining, Some(self.remaining))
538    }
539}
540
541impl DoubleEndedIterator for Iter<'_> {
542    fn next_back(&mut self) -> Option<Id> {
543        if self.remaining == 0 {
544            return None;
545        }
546        let id = self
547            .inner
548            .by_ref()
549            .rev()
550            .find_map(|(i, &v)| Self::live(i, v))?;
551        self.remaining -= 1;
552        Some(id)
553    }
554}
555
556impl ExactSizeIterator for Iter<'_> {}
557impl FusedIterator for Iter<'_> {}
558
559impl fmt::Debug for Iter<'_> {
560    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561        f.debug_list().entries(self.clone()).finish()
562    }
563}
564
565#[cfg(feature = "serde")]
566pub(crate) mod serde_impl {
567    use super::*;
568    use serde::de::{Deserialize, Deserializer, Error};
569    use serde::ser::{Serialize, Serializer};
570
571    /// Serializes as its bits ([`Id::to_bits`]).
572    impl Serialize for Id {
573        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
574            serializer.serialize_u64(self.to_bits())
575        }
576    }
577
578    /// Deserializes from its bits; rejects a zero generation.
579    impl<'de> Deserialize<'de> for Id {
580        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
581            let bits = u64::deserialize(deserializer)?;
582            Id::from_bits(bits).ok_or_else(|| De::Error::custom("id with generation 0"))
583        }
584    }
585
586    #[derive(serde::Serialize)]
587    struct ReprRef<'a> {
588        versions: &'a [u32],
589        free: &'a [u32],
590    }
591
592    /// Writes already validated versions and their corresponding free list.
593    pub(crate) fn serialize_raw_parts<S: Serializer>(
594        versions: &[u32],
595        free: &[u32],
596        serializer: S,
597    ) -> Result<S::Ok, S::Error> {
598        ReprRef { versions, free }.serialize(serializer)
599    }
600
601    #[derive(serde::Deserialize)]
602    struct Repr {
603        versions: Vec<u32>,
604        free: Vec<u32>,
605    }
606
607    /// Serializes the per-index versions and the free list, so a round trip
608    /// gives an equal allocator that issues the same ids.
609    impl Serialize for IdAllocator {
610        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
611            serialize_raw_parts(&self.versions, &self.free, serializer)
612        }
613    }
614
615    /// Deserializes and validates the state: rejects more than
616    /// [`MAX_INDICES`] indices, and a free list that is not exactly the
617    /// vacant indices, each once. Memory is linear in the input size.
618    impl<'de> Deserialize<'de> for IdAllocator {
619        fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
620            let Repr { versions, free } = Repr::deserialize(deserializer)?;
621            IdAllocator::try_from_raw_parts(versions, free).map_err(De::Error::custom)
622        }
623    }
624}
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629
630    fn g(n: u32) -> NonZeroU32 {
631        NonZeroU32::new(n).unwrap()
632    }
633
634    #[test]
635    fn reuses_last_freed_index_with_next_generation() {
636        let mut ids = IdAllocator::new();
637        let a = ids.alloc();
638        let b = ids.alloc();
639        let c = ids.alloc();
640        assert_eq!((a.index(), b.index(), c.index()), (0, 1, 2));
641        assert!(ids.free(a));
642        assert!(ids.free(c));
643        assert!(!ids.free(c));
644        assert_eq!(ids.len(), 1);
645        assert_eq!(ids.free_len(), 2);
646        assert_eq!(ids.alloc(), Id::new(2, g(2)));
647        assert_eq!(ids.alloc(), Id::new(0, g(2)));
648        assert_eq!(ids.alloc(), Id::new(3, g(1)));
649        assert!(!ids.is_alive(a) && !ids.is_alive(c));
650        assert!(ids.is_alive(b));
651        assert_eq!(ids.occupant(0), Some(Id::new(0, g(2))));
652        assert_eq!(ids.occupant(9), None);
653    }
654
655    #[test]
656    fn last_generation_retires_the_index() {
657        let mut ids = IdAllocator::new();
658        let a = ids.alloc();
659        // Jump index 0 to its last generation.
660        ids.versions[0] = u32::MAX;
661        let last = Id::new(0, g(MAX_GENERATION));
662        assert!(!ids.is_alive(a));
663        assert!(ids.is_alive(last));
664        assert!(ids.free(last));
665        assert_eq!(ids.retired_len(), 1);
666        assert_eq!(ids.free_len(), 0);
667        assert_eq!(ids.occupant(0), None);
668        assert_eq!(ids.alloc().index(), 1);
669        // Generations above the maximum are never alive.
670        assert!(!ids.is_alive(Id::new(1, g(MAX_GENERATION + 1))));
671    }
672
673    #[test]
674    fn retain_clear_and_iter() {
675        let mut ids = IdAllocator::new();
676        let all: Vec<Id> = (0..6).map(|_| ids.alloc()).collect();
677        ids.retain(|id| id.index() % 2 == 0);
678        assert_eq!(ids.iter().collect::<Vec<_>>(), [all[0], all[2], all[4]]);
679        assert_eq!(
680            ids.iter().rev().collect::<Vec<_>>(),
681            [all[4], all[2], all[0]]
682        );
683        let mut it = ids.iter();
684        assert_eq!(it.len(), 3);
685        assert_eq!(
686            (it.next(), it.next_back(), it.len()),
687            (Some(all[0]), Some(all[4]), 1)
688        );
689        ids.clear();
690        assert!(ids.is_empty());
691        assert_eq!(ids.iter().next(), None);
692        assert!(all.iter().all(|&id| !ids.is_alive(id)));
693        assert_eq!(ids.free_len(), 6);
694    }
695
696    #[test]
697    fn bits_round_trip() {
698        let id = Id::new(7, g(3));
699        assert_eq!(id.to_bits(), (3 << 32) | 7);
700        assert_eq!(Id::from_bits(id.to_bits()), Some(id));
701        assert_eq!(Id::from_bits(7), None);
702        assert!(Id::new(1, g(9)) < Id::new(2, g(1)));
703        assert_eq!(alloc::format!("{id:?}"), "Id(7v3)");
704    }
705
706    #[test]
707    fn ids_share_a_slot_across_generations() {
708        use crate::sparse_set::PagedSparseSet;
709        let mut ids = IdAllocator::new();
710        let mut set = PagedSparseSet::<Id>::new();
711        let a = ids.alloc();
712        assert!(set.insert(a));
713        ids.free(a);
714        let b = ids.alloc();
715        assert!(!set.contains(b));
716        assert!(!set.insert(b));
717        assert_eq!(set.replace(b), Some(a));
718        assert!(set.contains(b));
719    }
720
721    #[cfg(feature = "serde")]
722    #[test]
723    fn serde_round_trip_and_validation() {
724        let mut ids = IdAllocator::new();
725        let v: Vec<Id> = (0..4).map(|_| ids.alloc()).collect();
726        ids.free(v[1]);
727        ids.free(v[3]);
728        let json = serde_json::to_string(&ids).unwrap();
729        assert_eq!(json, r#"{"versions":[1,2,1,2],"free":[1,3]}"#);
730        let back: IdAllocator = serde_json::from_str(&json).unwrap();
731        assert_eq!(back, ids);
732        assert_eq!(back.len(), 2);
733
734        for bad in [
735            r#"{"versions":[1,2],"free":[]}"#,
736            r#"{"versions":[1,2],"free":[0]}"#,
737            r#"{"versions":[1,2],"free":[1,1]}"#,
738            r#"{"versions":[0],"free":[0]}"#,
739            r#"{"versions":[2],"free":[5]}"#,
740        ] {
741            assert!(serde_json::from_str::<IdAllocator>(bad).is_err(), "{bad}");
742        }
743
744        assert_eq!(
745            serde_json::to_string(&v[1]).unwrap(),
746            alloc::format!("{}", (1u64 << 32) | 1)
747        );
748        assert!(serde_json::from_str::<Id>("5").is_err());
749    }
750
751    #[test]
752    fn raw_parts_round_trip_and_validation() {
753        let mut ids = IdAllocator::new();
754        let a = ids.alloc();
755        let b = ids.alloc();
756        ids.alloc();
757        ids.free(b);
758        ids.free(a);
759        let (versions, free) = ids.raw_parts();
760        assert_eq!((versions, free), (&[2, 2, 1][..], &[1, 0][..]));
761        let back = IdAllocator::try_from_raw_parts(versions.to_vec(), free.to_vec()).unwrap();
762        assert_eq!(back, ids);
763        assert_eq!(back.len(), 1);
764        let bad = |v: &[u32], f: &[u32]| IdAllocator::try_from_raw_parts(v.to_vec(), f.to_vec());
765        assert_eq!(bad(&[1], &[0]), Err(RawPartsError::NotVacant));
766        assert_eq!(bad(&[0], &[0]), Err(RawPartsError::NotVacant));
767        assert_eq!(bad(&[2], &[1]), Err(RawPartsError::NotVacant));
768        assert_eq!(bad(&[2], &[0, 0]), Err(RawPartsError::ListedTwice));
769        assert_eq!(bad(&[2, 4], &[1]), Err(RawPartsError::MissingVacant));
770        assert_eq!(
771            bad(&[0, 3], &[]).map(|a| (a.len(), a.retired_len())),
772            Ok((1, 1))
773        );
774    }
775
776    #[test]
777    fn ids_order_by_index_then_generation() {
778        assert!(Id::new(0, g(2)) < Id::new(1, g(1)));
779        assert!(Id::new(1, g(1)) < Id::new(1, g(2)));
780        assert_eq!(
781            Id::new(3, g(4)).cmp(&Id::new(3, g(4))),
782            core::cmp::Ordering::Equal
783        );
784    }
785}