vex_rt/rtos/
event.rs

1use owner_monad::{Owner, OwnerMut};
2use raii_map::set::{insert, Set, SetHandle};
3
4use crate::{bindings, rtos::Task};
5
6/// Represents a self-maintaining set of tasks to notify when an event occurs.
7pub struct Event(Set<Task>);
8
9impl Event {
10    #[inline]
11    /// Creates a new event structure with an empty set of tasks.
12    pub fn new() -> Self {
13        Event(Set::new())
14    }
15
16    /// Notify the tasks which are waiting for the event.
17    pub fn notify(&self) {
18        for t in self.0.iter() {
19            unsafe { bindings::task_notify(t.0) };
20        }
21    }
22
23    #[inline]
24    /// Gets the number of tasks currently waiting for the event.
25    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
36/// Represents a handle into the listing of the current task in an [`Event`].
37/// When this handle is dropped, that task is removed from the event's set.
38pub struct EventHandle<O: OwnerMut<Event>>(Option<SetHandle<Task, EventHandleOwner<O>>>);
39
40impl<O: OwnerMut<Event>> EventHandle<O> {
41    /// Returns `true` if the event handle is orphaned, i.e. the parent event
42    /// object no longer exists.
43    pub fn is_done(&self) -> bool {
44        self.with(|_| ()).is_none()
45    }
46
47    /// Nullifies the handle. This has the same effect as dropping it or
48    /// destroying the parent event object.
49    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]
75/// Adds the current task to the notification set for an [`Event`], acquiring an
76/// [`EventHandle`] to manage the lifetime of that entry.
77pub fn handle_event<O: OwnerMut<Event>>(owner: O) -> EventHandle<O> {
78    EventHandle(insert(EventHandleOwner(owner), Task::current()))
79}