HistoryBuf

Type Alias HistoryBuf 

Source
pub type HistoryBuf<T, const N: usize> = HistoryBufInner<T, OwnedHistoryBufStorage<T, N>>;
Expand description

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.

§Examples

use heapless::HistoryBuf;

// Initialize a new buffer with 8 elements.
let mut buf = HistoryBuf::<_, 8>::new();

// Starts with no data
assert_eq!(buf.recent(), None);

buf.write(3);
buf.write(5);
buf.extend(&[4, 4]);

// The most recent written element is a four.
assert_eq!(buf.recent(), Some(&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 4.
let avg = buf.as_slice().iter().sum::<usize>() / buf.len();
assert_eq!(avg, 4);

Aliased Type§

pub struct HistoryBuf<T, const N: usize> { /* private fields */ }

Implementations§

Source§

impl<T, const N: usize> HistoryBuf<T, N>

Source

pub const fn new() -> Self

Constructs a new history buffer.

The construction of a HistoryBuf works in const contexts.

§Examples
use heapless::HistoryBuf;

// Allocate a 16-element buffer on the stack
let x: HistoryBuf<u8, 16> = HistoryBuf::new();
assert_eq!(x.len(), 0);
Source§

impl<T, const N: usize> HistoryBuf<T, N>
where T: Copy + Clone,

Source

pub fn new_with(t: T) -> Self

Constructs a new history buffer, where every element is the given value.

§Examples
use heapless::HistoryBuf;

// Allocate a 16-element buffer on the stack
let mut x: HistoryBuf<u8, 16> = HistoryBuf::new_with(4);
// All elements are four
assert_eq!(x.as_slice(), [4; 16]);

Trait Implementations§

Source§

impl<T, const N: usize> Clone for HistoryBuf<T, N>
where T: Clone,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T, const N: usize> Default for HistoryBuf<T, N>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more