blob: 3f348eae23233d4f2d3f7b05dd15271de0378704 (
plain) (
blame)
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
|
/* Ring buffer implementing the WireGuard queuing semantics:
*
* 1. A fixed sized buffer
* 2. Inserting into the buffer always succeeds, but might overwrite the oldest item
*/
const BUFFER_SIZE : usize = 1024;
pub struct DiscardingRingBuffer<T> {
buf : [ Option<T> ; BUFFER_SIZE],
idx : usize,
next : usize
}
impl <T>DiscardingRingBuffer<T> where T: Copy {
pub fn new() -> Self {
DiscardingRingBuffer{
buf : [None; BUFFER_SIZE],
idx : 0,
next : 0
}
}
pub fn empty(&mut self) {
self.next = 0;
self.idx = 0;
for i in 1..BUFFER_SIZE {
self.buf[i] = None;
}
}
pub fn push(&mut self, val : T) {
// assign next slot (free / oldest)
self.buf[self.idx] = Some(val);
self.idx += 1;
self.idx %= BUFFER_SIZE;
// check for wrap-around
if self.idx == self.next {
self.next += 1;
self.next %= BUFFER_SIZE;
}
}
pub fn consume(&mut self) -> Option<T> {
match self.buf[self.next] {
None => None,
some => {
self.buf[self.next] = None;
self.next += 1;
self.next %= BUFFER_SIZE;
some
}
}
}
pub fn has_element(&self) -> bool {
match self.buf[self.next] {
None => true,
_ => false
}
}
}
proptest! {
#[test]
fn test_order(elems: Vec<usize>) {
let mut buf = DiscardingRingBuffer<usize>::new();
for e in &elems {
buf.push(e);
}
}
}
|