Skip to content

Add ordered_get() to HistoryBuffer #364

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/histbuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,32 @@ impl<T, S: HistBufStorage<T> + ?Sized> HistoryBufferInner<T, S> {
}
}

/// Returns a reference to the element in the order from oldest to newest.
///
/// `buf.ordered_get(0)` will always return the oldest element in the buffer.
///
/// `buf.ordered_get(buf.len() - 1)` will always return the newest element
/// in the buffer.
///
/// Returns None if `index >= self.len()`.
///
/// # Examples
///
/// ```
/// use heapless::HistoryBuffer;
///
/// let mut buffer: HistoryBuffer<u8, 6> = HistoryBuffer::new();
/// buffer.extend([0, 0, 0]);
/// buffer.extend([1, 2, 3, 4, 5, 6]);
/// assert_eq!(buffer.ordered_get(0), Some(&1u8));
/// assert_eq!(buffer.ordered_get(1), Some(&2u8));
/// assert_eq!(buffer.ordered_get(2), Some(&3u8));
/// assert_eq!(buffer.ordered_get(6), None);
/// ```
pub fn ordered_get(&self, idx: usize) -> Option<&T> {
self.oldest_ordered().nth(idx)
}

/// Returns double ended iterator for iterating over the buffer from
/// the oldest to the newest and back.
///
Expand Down Expand Up @@ -855,6 +881,24 @@ mod tests {
}
}

#[test]
fn ordered_get() {
let mut buffer: HistoryBuffer<u8, 6> = HistoryBuffer::new();
assert_eq!(buffer.ordered_get(0), None);

buffer.write(1u8);
assert_eq!(buffer.ordered_get(0), Some(&1u8));

buffer.write(2u8);
assert_eq!(buffer.ordered_get(0), Some(&1u8));
assert_eq!(buffer.ordered_get(1), Some(&2u8));

buffer.extend([3, 4, 5, 6, 7, 8]);
assert_eq!(buffer.ordered_get(0), Some(&3u8));
assert_eq!(buffer.ordered_get(5), Some(&8u8));
assert_eq!(buffer.ordered_get(6), None);
}

#[test]
fn ordered() {
// test on an empty buffer
Expand Down
Loading