rust/hwphysics/src/common.rs
branchui-scaling
changeset 15288 c4fd2813b127
parent 15280 66c987015f2d
child 15286 8095853811a6
equal deleted inserted replaced
13395:0135e64c6c66 15288:c4fd2813b127
       
     1 use fpnum::{fp, FPNum};
       
     2 use std::{collections::BinaryHeap, num::NonZeroU16, ops::Add};
       
     3 
       
     4 pub type GearId = NonZeroU16;
       
     5 pub trait GearData {}
       
     6 
       
     7 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
       
     8 pub struct Millis(u32);
       
     9 
       
    10 impl Millis {
       
    11     #[inline]
       
    12     pub fn new(value: u32) -> Self {
       
    13         Self(value)
       
    14     }
       
    15 
       
    16     #[inline]
       
    17     pub fn get(self) -> u32 {
       
    18         self.0
       
    19     }
       
    20 
       
    21     #[inline]
       
    22     pub fn to_fixed(self) -> FPNum {
       
    23         FPNum::new(self.0 as i32, 1000)
       
    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 
       
    35 pub trait GearDataProcessor<T: GearData> {
       
    36     fn add(&mut self, gear_id: GearId, gear_data: T);
       
    37     fn remove(&mut self, gear_id: GearId);
       
    38 }
       
    39 
       
    40 pub trait GearDataAggregator<T: GearData> {
       
    41     fn find_processor(&mut self) -> &mut GearDataProcessor<T>;
       
    42 }
       
    43 
       
    44 pub struct GearAllocator {
       
    45     max_id: u16,
       
    46     free_ids: BinaryHeap<GearId>,
       
    47 }
       
    48 
       
    49 impl GearAllocator {
       
    50     pub fn new() -> Self {
       
    51         Self {
       
    52             max_id: 0,
       
    53             free_ids: BinaryHeap::with_capacity(1024),
       
    54         }
       
    55     }
       
    56 
       
    57     pub fn alloc(&mut self) -> Option<GearId> {
       
    58         self.free_ids.pop().or_else(|| {
       
    59             self.max_id.checked_add(1).and_then(|new_max_id| {
       
    60                 self.max_id = new_max_id;
       
    61                 NonZeroU16::new(new_max_id)
       
    62             })
       
    63         })
       
    64     }
       
    65 
       
    66     pub fn free(&mut self, gear_id: GearId) {
       
    67         self.free_ids.push(gear_id)
       
    68     }
       
    69 }