lyrics-smslv/src/counter.rs
2023-11-10 17:10:36 -06:00

51 lines
1.1 KiB
Rust

use std::collections::HashSet;
use lunatic::{abstract_process, ap::Config, Process};
pub struct Counter {
counter: i64,
subscribers: HashSet<Process<i64>>,
}
#[abstract_process(visibility = pub)]
impl Counter {
#[init]
pub fn init(_: Config<Self>, start: i64) -> Result<Self, ()> {
Ok(Self {
counter: start,
subscribers: HashSet::new(),
})
}
#[handle_message]
pub fn subscribe(&mut self, m: Process<i64>) {
// monitor the process so we can remove it from this list when it dies
// let p = Process::spawn_link(self.counter, |capture, m: Mailbox<()>| {
// });
// add it to our list of subscribers
self.subscribers.insert(m);
}
fn notify(&self) {
for s in self.subscribers.iter() {
s.send(self.counter)
}
}
#[handle_message]
pub fn increment(&mut self) {
self.counter += 1;
}
#[handle_message]
pub fn decrement(&mut self) {
self.counter -= 1;
}
#[handle_request]
pub fn count(&self) -> i64 {
self.counter
}
}