1use 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
62pub const MAX_GENERATION: u32 = 1 << 31;
66
67pub const MAX_INDICES: u32 = u32::MAX;
70
71#[derive(Clone, Copy, PartialEq, Eq, Hash)]
85#[repr(C, align(8))]
86pub struct Id {
87 #[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 #[inline]
115 pub const fn new(index: u32, generation: NonZeroU32) -> Self {
116 Self { index, generation }
117 }
118
119 #[inline]
121 pub const fn index(self) -> u32 {
122 self.index
123 }
124
125 #[inline]
127 pub const fn generation(self) -> NonZeroU32 {
128 self.generation
129 }
130
131 #[inline]
133 pub const fn to_bits(self) -> u64 {
134 ((self.generation.get() as u64) << 32) | self.index as u64
135 }
136
137 #[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
164impl 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 Self::new(index as u32, generation)
178 }
179}
180
181#[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#[inline]
203pub(crate) fn live_version(generation: NonZeroU32) -> Option<u32> {
204 (generation.get() - 1).checked_mul(2).map(|v| v | 1)
205}
206
207#[derive(Clone, Default, PartialEq, Eq)]
219pub struct IdAllocator {
220 versions: Vec<u32>,
221 free: Vec<u32>,
222 len: usize,
223}
224
225impl IdAllocator {
226 #[inline]
228 pub const fn new() -> Self {
229 Self {
230 versions: Vec::new(),
231 free: Vec::new(),
232 len: 0,
233 }
234 }
235
236 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 #[inline]
247 pub fn len(&self) -> usize {
248 self.len
249 }
250
251 #[inline]
253 pub fn is_empty(&self) -> bool {
254 self.len == 0
255 }
256
257 #[inline]
260 pub fn index_bound(&self) -> usize {
261 self.versions.len()
262 }
263
264 #[inline]
266 pub fn free_len(&self) -> usize {
267 self.free.len()
268 }
269
270 #[inline]
272 pub fn retired_len(&self) -> usize {
273 self.versions.len() - self.len - self.free.len()
274 }
275
276 pub fn reserve(&mut self, additional: usize) {
283 self.versions
284 .reserve(additional.saturating_sub(self.free.len()));
285 }
286
287 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 #[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 #[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 *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 self.versions.push(1);
329 self.len += 1;
330 Some(Id {
331 index,
332 generation: NonZeroU32::MIN,
333 })
334 }
335
336 #[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 #[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 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 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 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 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 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 pub fn clear(&mut self) {
401 self.retain(|_| false);
402 }
403
404 pub fn shrink_to_fit(&mut self) {
407 self.versions.shrink_to_fit();
408 self.free.shrink_to_fit();
409 }
410
411 #[inline]
420 pub fn raw_parts(&self) -> (&[u32], &[u32]) {
421 (&self.versions, &self.free)
422 }
423
424 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
481#[non_exhaustive]
482pub enum RawPartsError {
483 TooManyIndices,
485 NotVacant,
487 ListedTwice,
489 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#[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 (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 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 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 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 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 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 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 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}