use owner_monad::{Owner, OwnerMut};
use raii_map::set::{insert, Set, SetHandle};
use crate::{bindings, rtos::Task};
pub struct Event(Set<Task>);
impl Event {
#[inline]
pub fn new() -> Self {
Event(Set::new())
}
pub fn notify(&self) {
for t in self.0.iter() {
unsafe { bindings::task_notify(t.0) };
}
}
#[inline]
pub fn task_count(&self) -> usize {
self.0.len()
}
}
impl Default for Event {
fn default() -> Self {
Self::new()
}
}
pub struct EventHandle<O: OwnerMut<Event>>(Option<SetHandle<Task, EventHandleOwner<O>>>);
impl<O: OwnerMut<Event>> EventHandle<O> {
pub fn is_done(&self) -> bool {
self.with(|_| ()).is_none()
}
pub fn clear(&mut self) {
self.0.take();
}
}
impl<O: OwnerMut<Event>> Owner<O> for EventHandle<O> {
fn with<'a, U>(&'a self, f: impl FnOnce(&O) -> U) -> Option<U>
where
O: 'a,
{
self.0.as_ref()?.with(|o| f(&o.0))
}
}
struct EventHandleOwner<O: OwnerMut<Event>>(O);
impl<O: OwnerMut<Event>> OwnerMut<Set<Task>> for EventHandleOwner<O> {
fn with<'a, U>(&'a mut self, f: impl FnOnce(&mut Set<Task>) -> U) -> Option<U>
where
Event: 'a,
{
self.0.with(|e| f(&mut e.0))
}
}
#[inline]
pub fn handle_event<O: OwnerMut<Event>>(owner: O) -> EventHandle<O> {
EventHandle(insert(EventHandleOwner(owner), Task::current()))
}