aboutsummaryrefslogtreecommitdiff
path: root/embassy-hal-common/src/ring_buffer.rs
diff options
context:
space:
mode:
authorDario Nieuwenhuis <[email protected]>2021-07-29 13:44:51 +0200
committerDario Nieuwenhuis <[email protected]>2021-07-29 13:44:51 +0200
commit7bfb763e0990aac1b0bc4ad95dcc55df53cdb6d9 (patch)
treea7552da59a774d79a3cd73ad7c109b02b8bac921 /embassy-hal-common/src/ring_buffer.rs
parentc8a48d726a7cc92ef989a519fdf55ec1f9fffbcd (diff)
Rename embassy-extras to embassy-hal-common
Diffstat (limited to 'embassy-hal-common/src/ring_buffer.rs')
-rw-r--r--embassy-hal-common/src/ring_buffer.rs84
1 files changed, 84 insertions, 0 deletions
diff --git a/embassy-hal-common/src/ring_buffer.rs b/embassy-hal-common/src/ring_buffer.rs
new file mode 100644
index 000000000..18795787f
--- /dev/null
+++ b/embassy-hal-common/src/ring_buffer.rs
@@ -0,0 +1,84 @@
1pub struct RingBuffer<'a> {
2 buf: &'a mut [u8],
3 start: usize,
4 end: usize,
5 empty: bool,
6}
7
8impl<'a> RingBuffer<'a> {
9 pub fn new(buf: &'a mut [u8]) -> Self {
10 Self {
11 buf,
12 start: 0,
13 end: 0,
14 empty: true,
15 }
16 }
17
18 pub fn push_buf(&mut self) -> &mut [u8] {
19 if self.start == self.end && !self.empty {
20 trace!(" ringbuf: push_buf empty");
21 return &mut self.buf[..0];
22 }
23
24 let n = if self.start <= self.end {
25 self.buf.len() - self.end
26 } else {
27 self.start - self.end
28 };
29
30 trace!(" ringbuf: push_buf {:?}..{:?}", self.end, self.end + n);
31 &mut self.buf[self.end..self.end + n]
32 }
33
34 pub fn push(&mut self, n: usize) {
35 trace!(" ringbuf: push {:?}", n);
36 if n == 0 {
37 return;
38 }
39
40 self.end = self.wrap(self.end + n);
41 self.empty = false;
42 }
43
44 pub fn pop_buf(&mut self) -> &mut [u8] {
45 if self.empty {
46 trace!(" ringbuf: pop_buf empty");
47 return &mut self.buf[..0];
48 }
49
50 let n = if self.end <= self.start {
51 self.buf.len() - self.start
52 } else {
53 self.end - self.start
54 };
55
56 trace!(" ringbuf: pop_buf {:?}..{:?}", self.start, self.start + n);
57 &mut self.buf[self.start..self.start + n]
58 }
59
60 pub fn pop(&mut self, n: usize) {
61 trace!(" ringbuf: pop {:?}", n);
62 if n == 0 {
63 return;
64 }
65
66 self.start = self.wrap(self.start + n);
67 self.empty = self.start == self.end;
68 }
69
70 pub fn clear(&mut self) {
71 self.start = 0;
72 self.end = 0;
73 self.empty = true;
74 }
75
76 fn wrap(&self, n: usize) -> usize {
77 assert!(n <= self.buf.len());
78 if n == self.buf.len() {
79 0
80 } else {
81 n
82 }
83 }
84}