Start stdin
This commit is contained in:
55
src/data_structures/circular_buffer.rs
Normal file
55
src/data_structures/circular_buffer.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use core::mem::MaybeUninit;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CircularBuffer<T, const SIZE: usize> {
|
||||
buffer: [MaybeUninit<T>; SIZE],
|
||||
head: usize,
|
||||
tail: usize,
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl<T, const SIZE: usize> CircularBuffer<T, SIZE> {
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
buffer: [const { MaybeUninit::uninit() }; SIZE],
|
||||
head: 0,
|
||||
tail: 0,
|
||||
len: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.len
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
pub fn is_full(&self) -> bool {
|
||||
self.len() == SIZE - 1
|
||||
}
|
||||
|
||||
pub fn pop(&mut self) -> Option<T> {
|
||||
if self.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let out = core::mem::replace(&mut self.buffer[self.head], MaybeUninit::uninit());
|
||||
self.head = (self.head + 1) % SIZE;
|
||||
self.len -= 1;
|
||||
// # Safety
|
||||
// the queue is not empty and head points to a valid value
|
||||
Some(unsafe { out.assume_init() })
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push(&mut self, value: T) {
|
||||
self.buffer[self.tail] = MaybeUninit::new(value);
|
||||
if self.is_full() {
|
||||
self.head = (self.head + 1) % SIZE;
|
||||
} else {
|
||||
self.len += 1;
|
||||
}
|
||||
self.tail = (self.tail + 1) % SIZE;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user