rust/hwphysics/src/common.rs
changeset 15279 42b710b0f883
parent 15268 24828281c9c5
child 15280 66c987015f2d
equal deleted inserted replaced
15278:bfd185ad03e7 15279:42b710b0f883
     1 pub type GearId = std::num::NonZeroU16;
     1 use std::{collections::BinaryHeap, num::NonZeroU16};
       
     2 
       
     3 pub type GearId = NonZeroU16;
     2 pub trait GearData {}
     4 pub trait GearData {}
     3 
     5 
     4 pub trait GearDataProcessor<T: GearData> {
     6 pub trait GearDataProcessor<T: GearData> {
     5     fn add(&mut self, gear_id: GearId, gear_data: T);
     7     fn add(&mut self, gear_id: GearId, gear_data: T);
       
     8     fn remove(&mut self, gear_id: GearId);
     6 }
     9 }
     7 
    10 
     8 pub trait GearDataAggregator<T: GearData> {
    11 pub trait GearDataAggregator<T: GearData> {
     9     fn find_processor(&mut self) -> &mut GearDataProcessor<T>;
    12     fn find_processor(&mut self) -> &mut GearDataProcessor<T>;
    10 }
    13 }
       
    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 }