use alloc::collections::BTreeMap;
use crate::machine::Machine;
use crate::runtime::Runtime;
pub struct Fleet<K, M: Machine> {
inner: BTreeMap<K, Runtime<M>>,
}
impl<K: Ord, M: Machine> Fleet<K, M> {
pub const fn new() -> Self {
Self {
inner: BTreeMap::new(),
}
}
pub fn boot(&mut self, key: K, flags: M::Flags) -> M::Cmd {
let (rt, cmd) = Runtime::boot(flags);
self.inner.insert(key, rt);
cmd
}
pub fn apply(&mut self, key: &K, msg: M::Msg) -> Option<M::Cmd> {
self.inner.get_mut(key).map(|rt| rt.apply(msg))
}
pub fn apply_if(&mut self, key: &K, gate: bool, msg: M::Msg) -> Option<M::Cmd> {
self.inner
.get_mut(key)
.and_then(|rt| rt.apply_if(gate, msg))
}
pub fn get(&self, key: &K) -> Option<&Runtime<M>> {
self.inner.get(key)
}
pub fn get_mut(&mut self, key: &K) -> Option<&mut Runtime<M>> {
self.inner.get_mut(key)
}
pub fn remove(&mut self, key: &K) -> Option<Runtime<M>> {
self.inner.remove(key)
}
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn iter(&self) -> alloc::collections::btree_map::Iter<'_, K, Runtime<M>> {
self.inner.iter()
}
}
impl<K: Ord, M: Machine> Default for Fleet<K, M> {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::Fleet;
use crate::cmd::Cmd;
use crate::machine::{Boot, Machine};
struct Tick;
impl Machine for Tick {
type Flags = ();
type Model = u32;
type Msg = ();
type Cmd = Cmd<()>;
type View = u32;
type History = ();
type NodeId = ();
fn init(_: ()) -> Boot<Self> {
Boot::new(Tick, 0, (), Cmd::none())
}
fn update(&mut self, n: &mut u32, _: &mut (), _: ()) -> Cmd<()> {
*n += 1;
Cmd::none()
}
fn view(&self, n: &u32) -> u32 {
*n
}
fn in_state(&self, _: ()) -> bool {
true
}
}
#[test]
fn two_symbols_do_not_share_model() {
let mut f = Fleet::<&str, Tick>::new();
let _ = f.boot("east", ());
let _ = f.boot("west", ());
f.apply(&"east", ());
f.apply(&"east", ());
f.apply(&"west", ());
assert_eq!(f.get(&"east").unwrap().view(), 2);
assert_eq!(f.get(&"west").unwrap().view(), 1);
}
#[test]
fn apply_missing_is_none() {
let mut f = Fleet::<&str, Tick>::new();
assert!(f.apply(&"east", ()).is_none());
}
}