use crate::task::{TaskHandle, TaskId};
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct BranchId(pub usize);
impl From<usize> for BranchId {
fn from(id: usize) -> Self {
BranchId(id)
}
}
impl From<i32> for BranchId {
fn from(id: i32) -> Self {
BranchId(id as usize)
}
}
pub struct ConditionalHandle {
pub(crate) task: TaskHandle,
pub(crate) branches: HashMap<BranchId, Vec<TaskHandle>>,
}
impl ConditionalHandle {
pub fn new(task: TaskHandle) -> Self {
Self {
task,
branches: HashMap::new(),
}
}
pub fn branch(&mut self, branch_id: impl Into<BranchId>, successor: &TaskHandle) -> &mut Self {
let branch_id = branch_id.into();
self.branches
.entry(branch_id)
.or_insert_with(Vec::new)
.push(successor.clone());
self
}
pub fn branch_many(&mut self, branch_id: impl Into<BranchId>, successors: &[TaskHandle]) -> &mut Self {
let branch_id = branch_id.into();
self.branches
.entry(branch_id)
.or_insert_with(Vec::new)
.extend(successors.iter().cloned());
self
}
pub fn task(&self) -> &TaskHandle {
&self.task
}
pub(crate) fn task_id(&self) -> TaskId {
self.task.id
}
}
pub struct Loop {
pub condition: TaskHandle,
pub body: Vec<TaskHandle>,
pub max_iterations: Option<usize>,
}
impl Loop {
pub fn new(condition: TaskHandle) -> Self {
Self {
condition,
body: Vec::new(),
max_iterations: None,
}
}
pub fn add_body_task(&mut self, task: TaskHandle) -> &mut Self {
self.body.push(task);
self
}
pub fn max_iterations(&mut self, max: usize) -> &mut Self {
self.max_iterations = Some(max);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Taskflow;
#[test]
fn test_branch_creation() {
let mut taskflow = Taskflow::new();
let condition = taskflow.emplace(|| {}).name("condition");
let mut cond_handle = ConditionalHandle::new(condition);
let task_a = taskflow.emplace(|| {}).name("a");
let task_b = taskflow.emplace(|| {}).name("b");
cond_handle.branch(0, &task_a);
cond_handle.branch(1, &task_b);
assert_eq!(cond_handle.branches.len(), 2);
}
}