new repo
This commit is contained in:
commit
36c51a1b10
|
@ -0,0 +1,8 @@
|
|||
/target
|
||||
|
||||
|
||||
# Added by cargo
|
||||
#
|
||||
# already existing elements were commented out
|
||||
|
||||
#/target
|
|
@ -0,0 +1,7 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "ring-buffer"
|
||||
version = "0.1.0"
|
|
@ -0,0 +1,5 @@
|
|||
[package]
|
||||
name = "ring-buffer"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
// Thanks to Low Byte Productions, I like this channel.
|
||||
// Youtube: https://www.youtube.com/watch?v=uIJnATS9j_0
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RingBuffer<const N: usize> {
|
||||
buf: [u8; N],
|
||||
mask: usize,
|
||||
head: usize,
|
||||
tail: usize,
|
||||
}
|
||||
|
||||
impl<const N: usize> Default for RingBuffer<N> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> RingBuffer<N> {
|
||||
#[inline]
|
||||
pub const fn new() -> Self {
|
||||
if N.is_power_of_two() {
|
||||
Self {
|
||||
buf: [0; N],
|
||||
mask: N - 1,
|
||||
head: 0,
|
||||
tail: 0,
|
||||
}
|
||||
} else {
|
||||
panic!("Buffer capacity isn't power of two");
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn get_buffer(&self) -> &[u8] {
|
||||
&self.buf
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.head == self.tail
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_full(&self) -> bool {
|
||||
(self.head + 1) & self.mask == self.tail
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn capacity(&self) -> usize {
|
||||
N
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn len(&self) -> usize {
|
||||
self.head.overflowing_sub(self.tail).0 & self.mask
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn clear(&mut self) {
|
||||
self.buf = [0; N];
|
||||
self.head = 0;
|
||||
self.tail = 0;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn push(&mut self, value: u8) -> bool {
|
||||
let (head, tail) = (self.head, self.tail);
|
||||
let next_head = (head + 1) & self.mask;
|
||||
|
||||
if next_head == tail {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.buf[head] = value;
|
||||
self.head = next_head;
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn pop(&mut self) -> Option<u8> {
|
||||
let (head, mut tail) = (self.head, self.tail);
|
||||
|
||||
if head == tail {
|
||||
return None;
|
||||
}
|
||||
|
||||
let value = self.buf[tail];
|
||||
tail = (tail + 1) & self.mask;
|
||||
self.tail = tail;
|
||||
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Iterator for RingBuffer<N> {
|
||||
type Item = u8;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.pop()
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue