scheduler

This commit is contained in:
Quaternions 2024-10-16 19:53:58 -07:00
parent 9898c53de8
commit 752ad6bd95
3 changed files with 61 additions and 0 deletions

View File

@ -1,5 +1,6 @@
pub mod runner;
pub mod context;
pub(crate) mod scheduler;
#[cfg(test)]
mod tests;

View File

@ -60,6 +60,7 @@ impl Runner{
}
//this makes set_app_data shut up about the lifetime
self.lua.set_app_data::<&'static mut rbx_dom_weak::WeakDom>(unsafe{core::mem::transmute(&mut context.dom)});
self.lua.set_app_data::<crate::scheduler::Scheduler>(crate::scheduler::Scheduler::default());
Ok(Runnable{
lua:self.lua,
_lifetime:&std::marker::PhantomData
@ -75,6 +76,7 @@ pub struct Runnable<'a>{
impl Runnable<'_>{
pub fn drop_context(self)->Runner{
self.lua.remove_app_data::<&'static mut rbx_dom_weak::WeakDom>();
self.lua.remove_app_data::<crate::scheduler::Scheduler>();
Runner{
lua:self.lua,
}

58
src/scheduler.rs Normal file
View File

@ -0,0 +1,58 @@
pub use tick::Tick;
mod tick{
#[derive(Clone,Copy,Default,Hash,PartialEq,Eq,PartialOrd,Ord)]
pub struct Tick(u64);
impl Tick{
pub const fn new(value:u64)->Self{
Self(value)
}
pub const fn get(&self)->u64{
self.0
}
}
impl std::ops::Add<u64> for Tick{
type Output=Self;
fn add(self,rhs:u64)->Self::Output{
Self(self.0+rhs)
}
}
impl std::ops::Sub<u64> for Tick{
type Output=Self;
fn sub(self,rhs:u64)->Self::Output{
Self(self.0-rhs)
}
}
impl std::ops::AddAssign<u64> for Tick{
fn add_assign(&mut self,rhs:u64){
self.0+=rhs;
}
}
impl std::ops::SubAssign<u64> for Tick{
fn sub_assign(&mut self,rhs:u64){
self.0-=rhs;
}
}
}
#[derive(Default)]
pub struct Scheduler{
tick:Tick,
schedule:std::collections::HashMap<Tick,Vec<mlua::Thread>>,
}
impl Scheduler{
pub const fn tick(&self)->Tick{
self.tick
}
pub fn has_scheduled_threads(&self)->bool{
!self.schedule.is_empty()
}
pub fn schedule_thread(&mut self,delay:u64,thread:mlua::Thread){
self.schedule.entry(self.tick+delay.max(1))
.or_insert(Vec::new())
.push(thread);
}
pub fn tick_threads(&mut self)->Option<Vec<mlua::Thread>>{
self.tick+=1;
self.schedule.remove(&self.tick)
}
}