Skip to main content

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