use std::cell::Cell;
use wasm_bindgen::prelude::wasm_bindgen;
#[non_exhaustive] #[wasm_bindgen]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub enum Strategy {
#[default]
RoundRobin,
LoadBased,
}
pub(super) struct Scheduler {
strategy: Strategy,
current_worker: Cell<usize>,
}
impl Scheduler {
pub(super) fn new(strategy: Strategy) -> Self {
Self {
strategy,
current_worker: Cell::new(0),
}
}
pub(super) fn schedule(&self, loads: &[Option<usize>]) -> Option<usize> {
match self.strategy {
Strategy::RoundRobin => {
let num = loads.len();
for _ in 0..num {
let id = self.current_worker.get();
self.current_worker.set((id + 1) % num);
if loads[id].is_some() {
return Some(id);
}
}
None
}
Strategy::LoadBased => loads
.iter()
.enumerate()
.filter_map(|(i, load)| load.map(|l| (i, l)))
.min_by_key(|(_i, load)| *load)
.map(|(i, _)| i),
}
}
}