-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_ring_buffer.rs
More file actions
86 lines (76 loc) · 2.28 KB
/
Copy pathsimple_ring_buffer.rs
File metadata and controls
86 lines (76 loc) · 2.28 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
79
80
81
82
83
84
85
86
//! linux-parity: complete
//! linux-source: vendor/linux/kernel/trace/simple_ring_buffer.c
//! test-origin: linux:vendor/linux/kernel/trace/simple_ring_buffer.c
//! A simplified, lockless ring buffer for "single producer, single consumer"
//! traces (used by trace_remote and some test paths).
//!
//! Ref: vendor/linux/kernel/trace/simple_ring_buffer.c
extern crate alloc;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicUsize, Ordering};
use spin::Mutex;
pub struct SimpleRing<T: Clone> {
inner: Mutex<Vec<T>>,
cap: usize,
head: AtomicUsize,
tail: AtomicUsize,
}
impl<T: Clone + Default> SimpleRing<T> {
pub fn new(cap: usize) -> Self {
let mut v = Vec::with_capacity(cap);
v.resize(cap, T::default());
Self {
inner: Mutex::new(v),
cap,
head: AtomicUsize::new(0),
tail: AtomicUsize::new(0),
}
}
pub fn push(&self, item: T) -> bool {
let tail = self.tail.load(Ordering::Acquire);
let head = self.head.load(Ordering::Acquire);
if tail.wrapping_sub(head) == self.cap {
return false;
}
self.inner.lock()[tail % self.cap] = item;
self.tail.store(tail.wrapping_add(1), Ordering::Release);
true
}
pub fn pop(&self) -> Option<T> {
let head = self.head.load(Ordering::Acquire);
let tail = self.tail.load(Ordering::Acquire);
if head == tail {
return None;
}
let v = self.inner.lock()[head % self.cap].clone();
self.head.store(head.wrapping_add(1), Ordering::Release);
Some(v)
}
pub fn len(&self) -> usize {
self.tail
.load(Ordering::Acquire)
.wrapping_sub(self.head.load(Ordering::Acquire))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_pop_fifo() {
let r: SimpleRing<u32> = SimpleRing::new(4);
r.push(1);
r.push(2);
r.push(3);
assert_eq!(r.pop(), Some(1));
assert_eq!(r.pop(), Some(2));
assert_eq!(r.pop(), Some(3));
assert_eq!(r.pop(), None);
}
#[test]
fn push_rejects_when_full() {
let r: SimpleRing<u32> = SimpleRing::new(2);
assert!(r.push(1));
assert!(r.push(2));
assert!(!r.push(3));
}
}