author | unC0Rr |
Wed, 28 Aug 2024 15:31:51 +0200 | |
branch | transitional_engine |
changeset 16021 | 6a3dc15b78b9 |
parent 15780 | f4b563a9ac5e |
permissions | -rw-r--r-- |
15282 | 1 |
use fpnum::FPNum; |
15381 | 2 |
use std::{collections::BinaryHeap, num::NonZeroU16, ops::Add}; |
15274 | 3 |
|
4 |
pub type GearId = NonZeroU16; |
|
15120 | 5 |
|
15275 | 6 |
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)] |
15281 | 7 |
#[repr(transparent)] |
15275 | 8 |
pub struct Millis(u32); |
9 |
||
10 |
impl Millis { |
|
11 |
#[inline] |
|
15780 | 12 |
pub const fn new(value: u32) -> Self { |
15275 | 13 |
Self(value) |
14 |
} |
|
15 |
||
16 |
#[inline] |
|
15780 | 17 |
pub const fn get(self) -> u32 { |
15275 | 18 |
self.0 |
19 |
} |
|
20 |
||
21 |
#[inline] |
|
22 |
pub fn to_fixed(self) -> FPNum { |
|
15383
701ad89a9f2a
avoid time multiplication when not skipping ticks
alfadur
parents:
15381
diff
changeset
|
23 |
FPNum::new(self.0 as i32, 1) |
15275 | 24 |
} |
25 |
} |
|
26 |
||
27 |
impl Add for Millis { |
|
28 |
type Output = Self; |
|
29 |
||
30 |
fn add(self, rhs: Self) -> Self::Output { |
|
31 |
Self(self.0 + rhs.0) |
|
32 |
} |
|
33 |
} |
|
34 |
||
15274 | 35 |
pub struct GearAllocator { |
36 |
max_id: u16, |
|
37 |
free_ids: BinaryHeap<GearId>, |
|
38 |
} |
|
39 |
||
40 |
impl GearAllocator { |
|
41 |
pub fn new() -> Self { |
|
42 |
Self { |
|
43 |
max_id: 0, |
|
44 |
free_ids: BinaryHeap::with_capacity(1024), |
|
45 |
} |
|
46 |
} |
|
47 |
||
48 |
pub fn alloc(&mut self) -> Option<GearId> { |
|
49 |
self.free_ids.pop().or_else(|| { |
|
50 |
self.max_id.checked_add(1).and_then(|new_max_id| { |
|
51 |
self.max_id = new_max_id; |
|
52 |
NonZeroU16::new(new_max_id) |
|
53 |
}) |
|
54 |
}) |
|
55 |
} |
|
56 |
||
57 |
pub fn free(&mut self, gear_id: GearId) { |
|
58 |
self.free_ids.push(gear_id) |
|
59 |
} |
|
60 |
} |