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)]
5pub struct Port<T: Clone, const N: usize>(heapless::Vec<T, N>);
6
7impl<T: Clone, const N: usize> Default for Port<T, N> {
8    fn default() -> Self {
9        Self::new()
10    }
11}
12
13impl<T: Clone, const N: usize> Port<T, N> {
14    /// Creates a new empty port.
15    #[inline]
16    pub const fn new() -> Self {
17        Self(heapless::Vec::new())
18    }
19
20    /// Returns `true` if the port is empty.
21    #[inline]
22    pub fn is_empty(&self) -> bool {
23        self.0.is_empty()
24    }
25
26    /// Returns `true` if the port is full.
27    #[inline]
28    pub fn is_full(&self) -> bool {
29        self.0.is_full()
30    }
31
32    /// Returns the number of elements in the port.
33    #[inline]
34    pub fn len(&self) -> usize {
35        self.0.len()
36    }
37
38    /// Clears the port, removing all values.
39    #[inline]
40    pub fn clear(&mut self) {
41        self.0.clear()
42    }
43
44    /// Adds a value to the port.
45    #[inline]
46    pub fn add_value(&mut self, item: T) -> Result<(), T> {
47        self.0.push(item)
48    }
49
50    /// Adds multiple values to the port.
51    #[inline]
52    pub fn add_values(&mut self, items: &[T]) -> Result<(), heapless::CapacityError> {
53        self.0.extend_from_slice(items)
54    }
55
56    /// Returns a slice of the port's values.
57    #[inline]
58    pub fn get_values(&self) -> &[T] {
59        self.0.as_slice()
60    }
61}
62
63unsafe impl<T: Clone, const N: usize> crate::traits::Bag for Port<T, N> {
64    fn is_empty(&self) -> bool {
65        self.is_empty()
66    }
67
68    fn clear(&mut self) {
69        self.clear()
70    }
71}