|
| 1 | +use alloc::collections::VecDeque; |
| 2 | + |
| 3 | +/// A queue of IPI events. |
| 4 | +/// |
| 5 | +/// It internally uses a `VecDeque` to store the events, make it |
| 6 | +/// possible to pop these events using FIFO order. |
| 7 | +pub struct IPIEventQueue<E: IPIEvent> { |
| 8 | + events: VecDeque<IPIEventWrapper<E>>, |
| 9 | +} |
| 10 | + |
| 11 | +/// A trait that all events must implement. |
| 12 | +pub trait IPIEvent: 'static { |
| 13 | + /// Callback function that will be called when the event is triggered. |
| 14 | + fn callback(self); |
| 15 | +} |
| 16 | + |
| 17 | +struct IPIEventWrapper<E> { |
| 18 | + src_cpu_id: u32, |
| 19 | + event: E, |
| 20 | +} |
| 21 | + |
| 22 | +impl<E: IPIEvent> IPIEventQueue<E> { |
| 23 | + /// Creates a new empty timer list. |
| 24 | + pub fn new() -> Self { |
| 25 | + Self { |
| 26 | + events: VecDeque::new(), |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + /// Whether there is no event. |
| 31 | + #[inline] |
| 32 | + pub fn is_empty(&self) -> bool { |
| 33 | + self.events.is_empty() |
| 34 | + } |
| 35 | + |
| 36 | + pub fn push(&mut self, src_cpu_id: u32, event: E) { |
| 37 | + self.events.push_back(IPIEventWrapper { src_cpu_id, event }); |
| 38 | + } |
| 39 | + |
| 40 | + /// Try to pop the latest event that exists in the queue. |
| 41 | + /// |
| 42 | + /// Returns `None` if no event is available. |
| 43 | + pub fn pop_one(&mut self) -> Option<E> { |
| 44 | + if let Some(e) = self.events.pop_front() { |
| 45 | + Some(e.event) |
| 46 | + } else { |
| 47 | + None |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl<E: IPIEvent> Default for IPIEventQueue<E> { |
| 53 | + fn default() -> Self { |
| 54 | + Self::new() |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +/// A simple wrapper of a closure that implements the [`IPIEvent`] trait. |
| 59 | +/// |
| 60 | +/// So that it can be used as in the [`IPIEventQueue`]. |
| 61 | +pub struct IPIEventFn(Box<dyn FnOnce() + 'static>); |
| 62 | + |
| 63 | +impl IPIEventFn { |
| 64 | + /// Constructs a new [`IPIEventFn`] from a closure. |
| 65 | + pub fn new<F>(f: F) -> Self |
| 66 | + where |
| 67 | + F: FnOnce() + 'static, |
| 68 | + { |
| 69 | + Self(Box::new(f)) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl IPIEvent for IPIEventFn { |
| 74 | + fn callback(self) { |
| 75 | + (self.0)() |
| 76 | + } |
| 77 | +} |
0 commit comments