15295
|
1 |
use std::{collections::BinaryHeap, num::NonZeroU16};
|
|
2 |
|
|
3 |
pub type GearId = NonZeroU16;
|
15141
|
4 |
pub trait GearData {}
|
|
5 |
|
|
6 |
pub trait GearDataProcessor<T: GearData> {
|
|
7 |
fn add(&mut self, gear_id: GearId, gear_data: T);
|
15295
|
8 |
fn remove(&mut self, gear_id: GearId);
|
15141
|
9 |
}
|
|
10 |
|
|
11 |
pub trait GearDataAggregator<T: GearData> {
|
|
12 |
fn find_processor(&mut self) -> &mut GearDataProcessor<T>;
|
|
13 |
}
|
15295
|
14 |
|
|
15 |
pub struct GearAllocator {
|
|
16 |
max_id: u16,
|
|
17 |
free_ids: BinaryHeap<GearId>,
|
|
18 |
}
|
|
19 |
|
|
20 |
impl GearAllocator {
|
|
21 |
pub fn new() -> Self {
|
|
22 |
Self {
|
|
23 |
max_id: 0,
|
|
24 |
free_ids: BinaryHeap::with_capacity(1024),
|
|
25 |
}
|
|
26 |
}
|
|
27 |
|
|
28 |
pub fn alloc(&mut self) -> Option<GearId> {
|
|
29 |
self.free_ids.pop().or_else(|| {
|
|
30 |
self.max_id.checked_add(1).and_then(|new_max_id| {
|
|
31 |
self.max_id = new_max_id;
|
|
32 |
NonZeroU16::new(new_max_id)
|
|
33 |
})
|
|
34 |
})
|
|
35 |
}
|
|
36 |
|
|
37 |
pub fn free(&mut self, gear_id: GearId) {
|
|
38 |
self.free_ids.push(gear_id)
|
|
39 |
}
|
|
40 |
}
|