-
Notifications
You must be signed in to change notification settings - Fork 543
Expand file tree
/
Copy pathexample.rs
More file actions
78 lines (67 loc) · 1.85 KB
/
example.rs
File metadata and controls
78 lines (67 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#[derive(Debug, PartialEq)]
pub enum Error {
EmptyBuffer,
FullBuffer,
}
pub struct CircularBuffer<T> {
/// Using Option leads to less efficient memory layout, but
/// it allows us to avoid using `unsafe` to handle uninitialized
/// mempory ourselves.
data: Vec<Option<T>>,
start: usize,
end: usize,
}
impl<T> CircularBuffer<T> {
pub fn new(capacity: usize) -> Self {
let mut data = Vec::with_capacity(capacity);
data.resize_with(capacity, || None);
Self {
data,
start: 0,
end: 0,
}
}
pub fn read(&mut self) -> Result<T, Error> {
if self.is_empty() {
return Err(Error::EmptyBuffer);
}
let v = self.data[self.start]
.take()
.expect("should not read 'uninitialized' memory");
self.advance_start();
Ok(v)
}
pub fn write(&mut self, byte: T) -> Result<(), Error> {
if self.is_full() {
return Err(Error::FullBuffer);
}
self.data[self.end] = Some(byte);
self.advance_end();
Ok(())
}
pub fn overwrite(&mut self, byte: T) {
self.data[self.end] = Some(byte);
if self.start == self.end {
self.advance_start();
}
self.advance_end();
}
pub fn clear(&mut self) {
self.start = 0;
self.end = 0;
// Clear any values in the buffer
self.data.fill_with(|| None);
}
fn is_empty(&self) -> bool {
self.start == self.end && self.data[self.start].is_none()
}
fn is_full(&self) -> bool {
self.start == self.end && self.data[self.start].is_some()
}
fn advance_start(&mut self) {
self.start = (self.start + 1) % self.data.len();
}
fn advance_end(&mut self) {
self.end = (self.end + 1) % self.data.len();
}
}