1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
use generic_array::{sequence::GenericSequence, ArrayLength, GenericArray};
/// A "history buffer", similar to a write-only ring buffer of fixed length.
///
/// This buffer keeps a fixed number of elements. On write, the oldest element
/// is overwritten. Thus, the buffer is useful to keep a history of values with
/// some desired depth, and for example calculate a rolling average.
///
/// The buffer is always fully initialized; depending on the constructor, the
/// initial value is either the default value for the element type or a supplied
/// initial value. This simplifies the API and is mostly irrelevant for the
/// intended use case.
///
/// # Examples
/// ```
/// use heapless::HistoryBuffer;
/// use heapless::consts::*;
///
/// // Initialize a new buffer with 8 elements, all initially zero.
/// let mut buf = HistoryBuffer::<_, U8>::new();
///
/// buf.write(3);
/// buf.write(5);
/// buf.extend(&[4, 4]);
///
/// // The most recent written element is a four.
/// assert_eq!(buf.recent(), &4);
///
/// // To access all elements in an unspecified order, use `as_slice()`.
/// for el in buf.as_slice() { println!("{:?}", el); }
///
/// // Now we can prepare an average of all values, which comes out to 2.
/// let avg = buf.as_slice().iter().sum::<usize>() / buf.len();
/// assert_eq!(avg, 2);
/// ```
#[derive(Clone)]
pub struct HistoryBuffer<T, N>
where
N: ArrayLength<T>,
{
data: GenericArray<T, N>,
write_at: usize,
}
impl<T, N> HistoryBuffer<T, N>
where
N: ArrayLength<T>,
T: Default,
{
/// Constructs a new history buffer, where every element is filled with the
/// default value of the type `T`.
///
/// `HistoryBuffer` currently cannot be constructed in `const` context.
///
/// # Examples
///
/// ```
/// use heapless::HistoryBuffer;
/// use heapless::consts::*;
///
/// // Allocate a 16-element buffer on the stack
/// let mut x: HistoryBuffer<u8, U16> = HistoryBuffer::new();
/// // All elements are zero
/// assert_eq!(x.as_slice(), [0; 16]);
/// ```
pub fn new() -> Self {
Self {
data: Default::default(),
write_at: 0,
}
}
/// Clears the buffer, replacing every element with the default value of
/// type `T`.
pub fn clear(&mut self) {
*self = Self::new();
}
}
impl<T, N> HistoryBuffer<T, N>
where
N: ArrayLength<T>,
T: Clone,
{
/// Constructs a new history buffer, where every element is the given value.
///
/// # Examples
///
/// ```
/// use heapless::HistoryBuffer;
/// use heapless::consts::*;
///
/// // Allocate a 16-element buffer on the stack
/// let mut x: HistoryBuffer<u8, U16> = HistoryBuffer::new_with(4);
/// // All elements are four
/// assert_eq!(x.as_slice(), [4; 16]);
/// ```
pub fn new_with(t: T) -> Self {
Self {
data: GenericArray::generate(|_| t.clone()),
write_at: 0,
}
}
/// Clears the buffer, replacing every element with the given value.
pub fn clear_with(&mut self, t: T) {
*self = Self::new_with(t);
}
}
impl<T, N> HistoryBuffer<T, N>
where
N: ArrayLength<T>,
{
/// Returns the capacity of the buffer, which is the length of the
/// underlying backing array.
pub fn len(&self) -> usize {
self.data.len()
}
/// Writes an element to the buffer, overwriting the oldest value.
pub fn write(&mut self, t: T) {
self.data[self.write_at] = t;
self.write_at += 1;
if self.write_at == self.len() {
self.write_at = 0;
}
}
/// Clones and writes all elements in a slice to the buffer.
///
/// If the slice is longer than the buffer, only the last `self.len()`
/// elements will actually be stored.
pub fn extend_from_slice(&mut self, other: &[T])
where
T: Clone,
{
for item in other {
self.write(item.clone());
}
}
/// Returns a reference to the most recently written value.
///
/// # Examples
///
/// ```
/// use heapless::HistoryBuffer;
/// use heapless::consts::*;
///
/// let mut x: HistoryBuffer<u8, U16> = HistoryBuffer::new();
/// x.write(4);
/// x.write(10);
/// assert_eq!(x.recent(), &10);
/// ```
pub fn recent(&self) -> &T {
if self.write_at == 0 {
&self.data[self.len() - 1]
} else {
&self.data[self.write_at - 1]
}
}
/// Returns the array slice backing the buffer, without keeping track
/// of the write position. Therefore, the element order is unspecified.
pub fn as_slice(&self) -> &[T] {
&self.data
}
}
impl<T, N> Extend<T> for HistoryBuffer<T, N>
where
N: ArrayLength<T>,
{
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = T>,
{
for item in iter.into_iter() {
self.write(item);
}
}
}
impl<'a, T, N> Extend<&'a T> for HistoryBuffer<T, N>
where
T: 'a + Clone,
N: ArrayLength<T>,
{
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = &'a T>,
{
self.extend(iter.into_iter().cloned())
}
}
#[cfg(test)]
mod tests {
use crate::{consts::*, HistoryBuffer};
#[test]
fn new() {
let x: HistoryBuffer<u8, U4> = HistoryBuffer::new_with(1);
assert_eq!(x.len(), 4);
assert_eq!(x.as_slice(), [1; 4]);
let x: HistoryBuffer<u8, U4> = HistoryBuffer::new();
assert_eq!(x.as_slice(), [0; 4]);
}
#[test]
fn write() {
let mut x: HistoryBuffer<u8, U4> = HistoryBuffer::new();
x.write(1);
x.write(4);
assert_eq!(x.as_slice(), [1, 4, 0, 0]);
x.write(5);
x.write(6);
x.write(10);
assert_eq!(x.as_slice(), [10, 4, 5, 6]);
x.extend([11, 12].iter());
assert_eq!(x.as_slice(), [10, 11, 12, 6]);
}
#[test]
fn clear() {
let mut x: HistoryBuffer<u8, U4> = HistoryBuffer::new_with(1);
x.clear();
assert_eq!(x.as_slice(), [0; 4]);
let mut x: HistoryBuffer<u8, U4> = HistoryBuffer::new();
x.clear_with(1);
assert_eq!(x.as_slice(), [1; 4]);
}
#[test]
fn recent() {
let mut x: HistoryBuffer<u8, U4> = HistoryBuffer::new();
assert_eq!(x.recent(), &0);
x.write(1);
x.write(4);
assert_eq!(x.recent(), &4);
x.write(5);
x.write(6);
x.write(10);
assert_eq!(x.recent(), &10);
}
#[test]
fn as_slice() {
let mut x: HistoryBuffer<u8, U4> = HistoryBuffer::new();
x.extend([1, 2, 3, 4, 5].iter());
assert_eq!(x.as_slice(), [5, 2, 3, 4]);
}
}