avian3d/data_structures/
id_pool.rs1use alloc::collections::BinaryHeap;
4use core::cmp::Reverse;
5
6#[derive(Clone, Debug, Default)]
10#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
11pub struct IdPool {
12 free_ids: BinaryHeap<Reverse<u32>>,
14 next_index: u32,
16}
17
18impl IdPool {
19 #[inline(always)]
21 pub const fn new() -> Self {
22 Self {
23 free_ids: BinaryHeap::new(),
24 next_index: 0,
25 }
26 }
27
28 #[inline(always)]
32 pub fn with_capacity(capacity: usize) -> Self {
33 Self {
34 free_ids: BinaryHeap::with_capacity(capacity),
35 next_index: 0,
36 }
37 }
38
39 #[inline(always)]
43 pub fn alloc(&mut self) -> u32 {
44 if let Some(id) = self.free_ids.pop() {
45 id.0
46 } else {
47 let id = self.next_index;
48 self.next_index += 1;
49 id
50 }
51 }
52
53 #[inline(always)]
57 pub fn free(&mut self, id: u32) {
58 debug_assert!(id < self.next_index);
59 self.free_ids.push(Reverse(id));
60 }
61
62 #[inline(always)]
64 pub fn clear(&mut self) {
65 self.free_ids.clear();
66 self.next_index = 0;
67 }
68
69 #[inline(always)]
71 pub fn next_id(&self) -> u32 {
72 if let Some(id) = self.free_ids.peek() {
73 id.0
74 } else {
75 self.next_index
76 }
77 }
78
79 #[inline(always)]
81 pub fn len(&self) -> usize {
82 self.next_index as usize - self.free_ids.len()
83 }
84
85 #[inline(always)]
87 pub fn free_len(&self) -> usize {
88 self.free_ids.len()
89 }
90
91 #[inline(always)]
93 pub fn total_len(&self) -> usize {
94 self.next_index as usize
95 }
96
97 #[inline(always)]
99 pub fn is_empty(&self) -> bool {
100 self.len() == 0
101 }
102}