kernel/collections/ring_buffer.rs
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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Implementation of a ring buffer.
use crate::collections::queue;
pub struct RingBuffer<'a, T: 'a> {
ring: &'a mut [T],
head: usize,
tail: usize,
}
impl<'a, T: Copy> RingBuffer<'a, T> {
pub fn new(ring: &'a mut [T]) -> RingBuffer<'a, T> {
RingBuffer {
head: 0,
tail: 0,
ring,
}
}
/// Returns the number of elements that can be enqueued until the ring buffer is full.
pub fn available_len(&self) -> usize {
// The maximum capacity of the queue is ring.len - 1, because head == tail for the empty
// queue.
self.ring.len().saturating_sub(1 + queue::Queue::len(self))
}
/// Returns up to 2 slices that together form the contents of the ring buffer.
///
/// Returns:
/// - `(None, None)` if the buffer is empty.
/// - `(Some(slice), None)` if the head is before the tail (therefore all the contents is
/// contiguous).
/// - `(Some(left), Some(right))` if the head is after the tail. In that case, the logical
/// contents of the buffer is `[left, right].concat()` (although physically the "left" slice is
/// stored after the "right" slice).
pub fn as_slices(&'a self) -> (Option<&'a [T]>, Option<&'a [T]>) {
if self.head < self.tail {
(Some(&self.ring[self.head..self.tail]), None)
} else if self.head > self.tail {
let (left, right) = self.ring.split_at(self.head);
(
Some(right),
if self.tail == 0 {
None
} else {
Some(&left[..self.tail])
},
)
} else {
(None, None)
}
}
}
impl<T: Copy> queue::Queue<T> for RingBuffer<'_, T> {
fn has_elements(&self) -> bool {
self.head != self.tail
}
fn is_full(&self) -> bool {
self.head == ((self.tail + 1) % self.ring.len())
}
fn len(&self) -> usize {
if self.tail > self.head {
self.tail - self.head
} else if self.tail < self.head {
(self.ring.len() - self.head) + self.tail
} else {
// head equals tail, length is zero
0
}
}
fn enqueue(&mut self, val: T) -> bool {
if self.is_full() {
// Incrementing tail will overwrite head
false
} else {
self.ring[self.tail] = val;
self.tail = (self.tail + 1) % self.ring.len();
true
}
}
fn push(&mut self, val: T) -> Option<T> {
let result = if self.is_full() {
let val = self.ring[self.head];
self.head = (self.head + 1) % self.ring.len();
Some(val)
} else {
None
};
self.ring[self.tail] = val;
self.tail = (self.tail + 1) % self.ring.len();
result
}
fn dequeue(&mut self) -> Option<T> {
if self.has_elements() {
let val = self.ring[self.head];
self.head = (self.head + 1) % self.ring.len();
Some(val)
} else {
None
}
}
/// Removes the first element for which the provided closure returns `true`.
///
/// This walks the ring buffer and, upon finding a matching element, removes
/// it. It then shifts all subsequent elements forward (filling the hole
/// created by removing the element).
///
/// If an element was removed, this function returns it as `Some(elem)`.
fn remove_first_matching<F>(&mut self, f: F) -> Option<T>
where
F: Fn(&T) -> bool,
{
let len = self.ring.len();
let mut slot = self.head;
while slot != self.tail {
if f(&self.ring[slot]) {
// This is the desired element, remove it and return it
let val = self.ring[slot];
let mut next_slot = (slot + 1) % len;
// Move everything past this element forward in the ring
while next_slot != self.tail {
self.ring[slot] = self.ring[next_slot];
slot = next_slot;
next_slot = (next_slot + 1) % len;
}
self.tail = slot;
return Some(val);
}
slot = (slot + 1) % len;
}
None
}
fn empty(&mut self) {
self.head = 0;
self.tail = 0;
}
fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&T) -> bool,
{
let len = self.ring.len();
// Index over the elements before the retain operation.
let mut src = self.head;
// Index over the retained elements.
let mut dst = self.head;
while src != self.tail {
if f(&self.ring[src]) {
// When the predicate is true, move the current element to the
// destination if needed, and increment the destination index.
if src != dst {
self.ring[dst] = self.ring[src];
}
dst = (dst + 1) % len;
}
src = (src + 1) % len;
}
self.tail = dst;
}
}
#[cfg(test)]
mod test {
use super::super::queue::Queue;
use super::RingBuffer;
#[test]
fn test_enqueue_dequeue() {
const LEN: usize = 10;
let mut ring = [0; LEN];
let mut buf = RingBuffer::new(&mut ring);
for _ in 0..2 * LEN {
assert!(buf.enqueue(42));
assert_eq!(buf.len(), 1);
assert!(buf.has_elements());
assert_eq!(buf.dequeue(), Some(42));
assert_eq!(buf.len(), 0);
assert!(!buf.has_elements());
}
}
#[test]
fn test_push() {
const LEN: usize = 10;
const MAX: usize = 100;
let mut ring = [0; LEN + 1];
let mut buf = RingBuffer::new(&mut ring);
for i in 0..LEN {
assert_eq!(buf.len(), i);
assert!(!buf.is_full());
assert_eq!(buf.push(i), None);
assert!(buf.has_elements());
}
for i in LEN..MAX {
assert!(buf.is_full());
assert_eq!(buf.push(i), Some(i - LEN));
}
for i in 0..LEN {
assert!(buf.has_elements());
assert_eq!(buf.len(), LEN - i);
assert_eq!(buf.dequeue(), Some(MAX - LEN + i));
assert!(!buf.is_full());
}
assert!(!buf.has_elements());
}
// Enqueue integers 1 <= n < len, checking that it succeeds and that the
// queue is full at the end.
// See std::iota in C++.
fn enqueue_iota(buf: &mut RingBuffer<usize>, len: usize) {
for i in 1..len {
assert!(!buf.is_full());
assert!(buf.enqueue(i));
assert!(buf.has_elements());
assert_eq!(buf.len(), i);
}
assert!(buf.is_full());
assert!(!buf.enqueue(0));
assert!(buf.has_elements());
}
// Dequeue all elements, expecting integers 1 <= n < len, checking that the
// queue is empty at the end.
// See std::iota in C++.
fn dequeue_iota(buf: &mut RingBuffer<usize>, len: usize) {
for i in 1..len {
assert!(buf.has_elements());
assert_eq!(buf.len(), len - i);
assert_eq!(buf.dequeue(), Some(i));
assert!(!buf.is_full());
}
assert!(!buf.has_elements());
assert_eq!(buf.len(), 0);
}
// Move the head by `count` elements, by enqueueing/dequeueing `count`
// times an element.
// This assumes an empty queue at the beginning, and yields an empty queue.
fn move_head(buf: &mut RingBuffer<usize>, count: usize) {
assert!(!buf.has_elements());
assert_eq!(buf.len(), 0);
for _ in 0..count {
assert!(buf.enqueue(0));
assert_eq!(buf.dequeue(), Some(0));
}
assert!(!buf.has_elements());
assert_eq!(buf.len(), 0);
}
#[test]
fn test_fill_once() {
const LEN: usize = 10;
let mut ring = [0; LEN];
let mut buf = RingBuffer::new(&mut ring);
assert!(!buf.has_elements());
assert_eq!(buf.len(), 0);
enqueue_iota(&mut buf, LEN);
dequeue_iota(&mut buf, LEN);
}
#[test]
fn test_refill() {
const LEN: usize = 10;
let mut ring = [0; LEN];
let mut buf = RingBuffer::new(&mut ring);
for _ in 0..10 {
enqueue_iota(&mut buf, LEN);
dequeue_iota(&mut buf, LEN);
}
}
#[test]
fn test_retain() {
const LEN: usize = 10;
let mut ring = [0; LEN];
let mut buf = RingBuffer::new(&mut ring);
move_head(&mut buf, LEN - 2);
enqueue_iota(&mut buf, LEN);
buf.retain(|x| x % 2 == 1);
assert_eq!(buf.len(), LEN / 2);
assert_eq!(buf.dequeue(), Some(1));
assert_eq!(buf.dequeue(), Some(3));
assert_eq!(buf.dequeue(), Some(5));
assert_eq!(buf.dequeue(), Some(7));
assert_eq!(buf.dequeue(), Some(9));
assert_eq!(buf.dequeue(), None);
}
}