Crate historybuffer

Crate historybuffer 

Source
Expand description

HistoryBuffer

This crate provides a circular history buffer similar to what you would want for a terminal window buffer. It returns bytes from any range still in memory.

It copies new data into the circular buffer, automatically handling wrap-arounds, always overwriting the oldest data. (Data is copied when entering and exiting)

The size of the buffer is always scaled up to the next power of 2, avoiding many unnecessary code branches.

The library could be easily extended to other types besides u8.

use historybuffer::HistoryBuffer;

fn main() {
    let mut hb = HistoryBuffer::new(6); // Create an 8-element buffer (next power of 2).

    hb.add("The Terminal History.".to_string().as_bytes());
    assert_eq!(
        hb.get_vec(15, 6),
        "story.".to_string().as_bytes().to_vec()
    );

    assert_eq!(hb.last_byte(), Some(b'.'));

    assert_eq!(hb.get_recent(4), "ory.".to_string().as_bytes());

    assert_eq!(hb.get_index(), 13);

    assert_eq!(hb.get(13), Some(b'H'));

    assert_eq!(hb.get_last_index(), 20);

    assert_eq!(hb.get(20), Some(b'.'));

    hb.add(" and".to_string().as_bytes());

    assert_eq!(hb.get(13), None);
}

get_vec returns as much data as possible from any desired range in history up to a maximum length of the available data at that moment.

get_vec_and_index returns a tuple containing the data and the start index of the returned data.

Note: This code has not been tested for wrapping usize values > 4 billion chars from long running apps.

Structsยง

HistoryBuffer