author | unc0rr |
Wed, 30 Jun 2021 00:18:53 +0200 | |
changeset 15832 | ee84e417d8d0 |
parent 15802 | f4b563a9ac5e |
permissions | -rw-r--r-- |
15303 | 1 |
use fpnum::FPNum; |
15402 | 2 |
use std::{collections::BinaryHeap, num::NonZeroU16, ops::Add}; |
15295 | 3 |
|
4 |
pub type GearId = NonZeroU16; |
|
15141 | 5 |
|
15296 | 6 |
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)] |
15302 | 7 |
#[repr(transparent)] |
15296 | 8 |
pub struct Millis(u32); |
9 |
||
10 |
impl Millis { |
|
11 |
#[inline] |
|
15802 | 12 |
pub const fn new(value: u32) -> Self { |
15296 | 13 |
Self(value) |
14 |
} |
|
15 |
||
16 |
#[inline] |
|
15802 | 17 |
pub const fn get(self) -> u32 { |
15296 | 18 |
self.0 |
19 |
} |
|
20 |
||
21 |
#[inline] |
|
22 |
pub fn to_fixed(self) -> FPNum { |
|
15404
701ad89a9f2a
avoid time multiplication when not skipping ticks
alfadur
parents:
15402
diff
changeset
|
23 |
FPNum::new(self.0 as i32, 1) |
15296 | 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 |
||
15295 | 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 |
} |