1use owner_monad::{Owner, OwnerMut};
2use raii_map::set::{insert, Set, SetHandle};
3
4use crate::{bindings, rtos::Task};
5
6pub struct Event(Set<Task>);
8
9impl Event {
10 #[inline]
11 pub fn new() -> Self {
13 Event(Set::new())
14 }
15
16 pub fn notify(&self) {
18 for t in self.0.iter() {
19 unsafe { bindings::task_notify(t.0) };
20 }
21 }
22
23 #[inline]
24 pub fn task_count(&self) -> usize {
26 self.0.len()
27 }
28}
29
30impl Default for Event {
31 fn default() -> Self {
32 Self::new()
33 }
34}
35
36pub struct EventHandle<O: OwnerMut<Event>>(Option<SetHandle<Task, EventHandleOwner<O>>>);
39
40impl<O: OwnerMut<Event>> EventHandle<O> {
41 pub fn is_done(&self) -> bool {
44 self.with(|_| ()).is_none()
45 }
46
47 pub fn clear(&mut self) {
50 self.0.take();
51 }
52}
53
54impl<O: OwnerMut<Event>> Owner<O> for EventHandle<O> {
55 fn with<'a, U>(&'a self, f: impl FnOnce(&O) -> U) -> Option<U>
56 where
57 O: 'a,
58 {
59 self.0.as_ref()?.with(|o| f(&o.0))
60 }
61}
62
63struct EventHandleOwner<O: OwnerMut<Event>>(O);
64
65impl<O: OwnerMut<Event>> OwnerMut<Set<Task>> for EventHandleOwner<O> {
66 fn with<'a, U>(&'a mut self, f: impl FnOnce(&mut Set<Task>) -> U) -> Option<U>
67 where
68 Event: 'a,
69 {
70 self.0.with(|e| f(&mut e.0))
71 }
72}
73
74#[inline]
75pub fn handle_event<O: OwnerMut<Event>>(owner: O) -> EventHandle<O> {
78 EventHandle(insert(EventHandleOwner(owner), Task::current()))
79}