#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Priority {
Low,
Normal,
High,
Critical,
}
impl Priority {
pub fn weight(&self) -> u8 {
match self {
Self::Low => 0,
Self::Normal => 1,
Self::High => 2,
Self::Critical => 3,
}
}
}
pub struct ScheduledTask {
pub id: String,
pub priority: Priority,
pub dependencies: Vec<String>,
}
pub struct Scheduler {
tasks: Vec<ScheduledTask>,
}
impl Scheduler {
pub fn new() -> Self {
Self { tasks: Vec::new() }
}
pub fn add(&mut self, task: ScheduledTask) {
self.tasks.push(task);
}
pub fn schedule(&mut self) -> Vec<String> {
self.tasks
.sort_by(|a, b| b.priority.weight().cmp(&a.priority.weight()));
let mut order = Vec::new();
let mut completed: Vec<String> = Vec::new();
let mut remaining: Vec<&ScheduledTask> = self.tasks.iter().collect();
while !remaining.is_empty() {
let mut progress = false;
let mut next_remaining = Vec::new();
for task in &remaining {
if task.dependencies.iter().all(|d| completed.contains(d)) {
order.push(task.id.clone());
completed.push(task.id.clone());
progress = true;
} else {
next_remaining.push(*task);
}
}
remaining = next_remaining;
if !progress {
break;
}
}
order
}
pub fn count(&self) -> usize {
self.tasks.len()
}
}
impl Default for Scheduler {
fn default() -> Self {
Self::new()
}
}