xdevs/
port.rs

1/// Port is a generic structure that can be used to store values of any type `T`.
2/// It is the main artifact to exchange data between components.
3/// Note that, in `no_std` environments, the capacity of the port `N` must be known at compile time.
4#[derive(Debug, Default)]
5pub struct Port<T: Clone, const N: usize>(heapless::Vec<T, N>);
6
7impl<T: Clone, const N: usize> Port<T, N> {
8    /// Creates a new empty port.
9    #[inline]
10    pub const fn new() -> Self {
11        Self(heapless::Vec::new())
12    }
13
14    /// Returns `true` if the port is empty.
15    #[inline]
16    pub fn is_empty(&self) -> bool {
17        self.0.is_empty()
18    }
19
20    /// Returns `true` if the port is full.
21    #[inline]
22    pub fn is_full(&self) -> bool {
23        self.0.is_full()
24    }
25
26    /// Returns the number of elements in the port.
27    #[inline]
28    pub fn len(&self) -> usize {
29        self.0.len()
30    }
31
32    /// Clears the port, removing all values.
33    #[inline]
34    pub fn clear(&mut self) {
35        self.0.clear()
36    }
37
38    /// Adds a value to the port.
39    #[inline]
40    pub fn add_value(&mut self, item: T) -> Result<(), T> {
41        self.0.push(item)
42    }
43
44    /// Adds multiple values to the port.
45    #[inline]
46    #[allow(clippy::result_unit_err)]
47    pub fn add_values(&mut self, items: &[T]) -> Result<(), ()> {
48        self.0.extend_from_slice(items)
49    }
50
51    /// Returns a slice of the port's values.
52    #[inline]
53    pub fn get_values(&self) -> &[T] {
54        self.0.as_slice()
55    }
56}
57
58unsafe impl<T: Clone, const N: usize> crate::traits::Bag for Port<T, N> {
59    fn is_empty(&self) -> bool {
60        self.is_empty()
61    }
62
63    fn clear(&mut self) {
64        self.clear()
65    }
66}