Skip to main content

veloxity_core/
ports.rs

1use crate::{
2    events::{EventQueue, EventQueueError},
3    params::{ParamId, ParamValue, Params},
4};
5
6pub struct ParamsReadPort<'a> {
7    params: &'a Params,
8}
9
10impl<'a> ParamsReadPort<'a> {
11    pub fn new(params: &'a Params) -> Self {
12        Self { params }
13    }
14
15    pub fn raw(&self) -> &'a Params {
16        self.params
17    }
18
19    pub fn get(&self, id: ParamId) -> ParamValue {
20        self.params.get_by_id(id)
21    }
22}
23
24pub struct ParamsWritePort<'a> {
25    params: &'a mut Params,
26}
27
28impl<'a> ParamsWritePort<'a> {
29    pub fn new(params: &'a mut Params) -> Self {
30        Self { params }
31    }
32
33    pub fn get(&self, id: ParamId) -> ParamValue {
34        self.params.get_by_id(id)
35    }
36
37    pub fn set(&mut self, id: ParamId, value: ParamValue) {
38        self.params.set_by_id(id, value);
39    }
40
41    pub fn raw_mut(&mut self) -> &mut Params {
42        self.params
43    }
44}
45
46pub struct EventEmitPort<'a, T: Copy, const N: usize> {
47    queue: &'a mut EventQueue<T, N>,
48}
49
50impl<'a, T: Copy, const N: usize> EventEmitPort<'a, T, N> {
51    pub fn new(queue: &'a mut EventQueue<T, N>) -> Self {
52        Self { queue }
53    }
54
55    pub fn emit(&mut self, event: T) -> Result<(), EventQueueError> {
56        self.queue.push(event)
57    }
58
59    pub fn emit_or_log(&mut self, event: T, label: &str) -> bool {
60        if self.emit(event).is_ok() {
61            true
62        } else {
63            crate::log_warn!("event queue full: {}", label);
64            false
65        }
66    }
67}
68
69pub struct EventDrainPort<'a, T: Copy, const N: usize> {
70    queue: &'a mut EventQueue<T, N>,
71}
72
73impl<'a, T: Copy, const N: usize> EventDrainPort<'a, T, N> {
74    pub fn new(queue: &'a mut EventQueue<T, N>) -> Self {
75        Self { queue }
76    }
77
78    pub fn next(&mut self) -> Option<T> {
79        self.queue.pop()
80    }
81}
82
83pub struct EventReadPort<'a, T: Copy, const N: usize> {
84    queue: &'a EventQueue<T, N>,
85}
86
87impl<'a, T: Copy, const N: usize> EventReadPort<'a, T, N> {
88    pub fn new(queue: &'a EventQueue<T, N>) -> Self {
89        Self { queue }
90    }
91
92    pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
93        self.queue.iter()
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use crate::log::Logger;
101
102    #[test]
103    fn emit_or_log_reports_full_queue_without_overwriting_existing_event() {
104        let mut queue = EventQueue::<u8, 1>::new();
105        let mut port = EventEmitPort::new(&mut queue);
106
107        assert!(port.emit_or_log(1, "test event"));
108        assert!(!port.emit_or_log(2, "test event"));
109
110        assert_eq!(queue.pop(), Some(1));
111        assert_eq!(queue.pop(), None);
112
113        while Logger::pop().is_some() {}
114    }
115}