irox_tools/
buf.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2025 IROX Contributors
3//
4
5//!
6//! Stack Buffers
7
8pub use round::*;
9
10mod round;
11pub use fixed::*;
12
13mod fixed;
14pub use fixed_u8::*;
15mod fixed_u8;
16pub use round_u8::*;
17mod round_u8;
18
19use crate::cfg_feature_alloc;
20cfg_feature_alloc! {
21    extern crate alloc;
22
23    pub use unlimited::*;
24    mod unlimited;
25}
26
27///
28/// Standard buffer functions
29pub trait Buffer<T> {
30    fn get(&self, index: usize) -> Option<&T>;
31    fn get_mut(&mut self, index: usize) -> Option<&mut T>;
32    fn capacity(&self) -> usize;
33    fn len(&self) -> usize;
34    fn clear(&mut self);
35
36    fn front(&self) -> Option<&T>;
37    fn front_mut(&mut self) -> Option<&mut T>;
38    fn back(&self) -> Option<&T>;
39    fn back_mut(&mut self) -> Option<&mut T>;
40    fn pop_front(&mut self) -> Option<T>;
41    fn pop_back(&mut self) -> Option<T>;
42    fn push_front(&mut self, value: T) -> Result<(), T>;
43    fn push_back(&mut self, value: T) -> Result<(), T>;
44    fn push(&mut self, value: T) -> Result<(), T> {
45        self.push_back(value)
46    }
47
48    fn is_empty(&self) -> bool {
49        self.len() == 0
50    }
51    fn is_full(&self) -> bool {
52        self.capacity() == self.len()
53    }
54
55    cfg_feature_alloc! {
56        fn into_boxed_slice(mut self) -> alloc::boxed::Box<[T]> where Self: Sized {
57            let mut vec = alloc::vec::Vec::<T>::with_capacity(self.len());
58            while let Some(elem) = self.pop_front() {
59                vec.push(elem);
60            }
61            vec.into_boxed_slice()
62        }
63    }
64}
65
66///
67/// Trait used for things like [`Vec`] and [`VecDeq`] to pre-allocate and fill
68/// with zeros.
69pub trait ZeroedBuffer {
70    type Output;
71    fn new_zeroed(capacity: usize) -> Self::Output;
72}