Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. circular_buffer/lib.rs

circular_buffer/
lib.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#![no_std]
15
16use core::mem::MaybeUninit;
17
18use pw_status::{Error, Result};
19
20/// A fixed-capacity circular buffer.
21///
22/// The buffer has the following properties:
23/// - No restrictions on a power of two on the value of N.
24/// - The full size of buffer is used (no wasted space).
25/// - When the buffer is full, writing will return an error until the
26///   buffer is read from.
27///
28/// ## Invariants
29///
30/// For a buffer with `N > 0`, the following invariants are maintained:
31///
32/// 1. `0 <= self.len <= N`: The number of elements is always between 0 and
33///    the capacity, inclusive.
34/// 2. `0 <= self.head < N`: The head index is always within the array bounds.
35/// 3. `0 <= self.tail < N`: The tail index is always within the array bounds.
36/// 4. `self.head == (self.tail + self.len) % N`: The head is advanced from the
37///    tail by the length, modulo N.
38/// 5. The `self.len` populated elements are stored in `buffer` at indices
39///    `(self.tail) % N`, `(self.tail + 1) % N`, ..., `(self.tail + self.len - 1) % N`.
40///
41/// The case `N = 0` is valid and handled; `push_back` will always return
42/// `Error::ResourceExhausted` and `pop_front` will always return `None`,
43/// preventing any out-of-bounds access or division by zero.
44///
45// TODO: The const generic N could potentially lead to monomorphization
46// bloat, but LTO may alleviate the bloat.  Investigate during the
47// next round of size optimizations.
48pub struct CircularBuffer<T, const N: usize> {
49    buffer: [MaybeUninit<T>; N],
50    head: usize,
51    tail: usize,
52    len: usize,
53}
54
55impl<T, const N: usize> CircularBuffer<T, N> {
56    /// Creates a new, empty circular buffer.
57    #[must_use]
58    pub const fn new() -> Self {
59        Self {
60            buffer: [const { MaybeUninit::uninit() }; N],
61            head: 0,
62            tail: 0,
63            len: 0,
64        }
65    }
66
67    /// Returns `true` if the buffer is empty.
68    pub const fn is_empty(&self) -> bool {
69        self.len == 0
70    }
71
72    /// Returns `true` if the buffer is full.
73    pub const fn is_full(&self) -> bool {
74        self.len == N
75    }
76
77    /// Returns the number of elements in the buffer.
78    pub const fn len(&self) -> usize {
79        self.len
80    }
81
82    /// Returns the capacity of the buffer.
83    pub const fn capacity(&self) -> usize {
84        N
85    }
86
87    /// Pushes an element to the back of the buffer.
88    ///
89    /// If the buffer is full, `Error::ResourceExhausted` is returned.
90    pub fn push_back(&mut self, item: T) -> Result<()> {
91        if self.is_full() {
92            return Err(Error::ResourceExhausted);
93        }
94        // SAFETY:
95        // 1. By Invariant 1 (`0 <= self.len <= N`) and the `is_full()` check,
96        //    we know `self.len < N`.
97        // 2. By Invariant 2 (`0 <= self.head < N`), `self.head` is a valid
98        //    index (this is only reachable if `N > 0`).
99        // 3. By Invariants 5, the slot at `self.head` is empty
100        //    because `self.len < N`.
101        unsafe {
102            self.buffer.get_unchecked_mut(self.head).write(item);
103        }
104        self.head = (self.head + 1) % N;
105        self.len += 1;
106        Ok(())
107    }
108
109    /// Removes an element from the **front** of the buffer (dequeue).
110    ///
111    /// Returns `None` if the buffer is empty.
112    pub fn pop_front(&mut self) -> Option<T> {
113        if self.is_empty() {
114            return None;
115        }
116        // SAFETY:
117        // 1. By Invariant 1 (`0 <= self.len <= N`) and the `is_empty()` check,
118        //    we know `self.len > 0`.
119        // 2. By Invariant 3 (`0 <= self.tail < N`), `self.tail` is a valid
120        //    index (this is only reachable if `N > 0`).
121        // 3. By Invariant 5, the slot at `self.tail` is the first of
122        //    `self.len` initialized elements.
123        let item = unsafe { self.buffer.get_unchecked(self.tail).assume_init_read() };
124        self.tail = (self.tail + 1) % N;
125        self.len -= 1;
126        Some(item)
127    }
128}
129
130impl<T, const N: usize> Default for CircularBuffer<T, N> {
131    fn default() -> Self {
132        Self::new()
133    }
134}
135
136impl<T, const N: usize> Drop for CircularBuffer<T, N> {
137    fn drop(&mut self) {
138        while self.pop_front().is_some() {}
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use pw_status::Error;
145    use unittest::test;
146
147    use super::*;
148
149    #[test]
150    fn new_buffer_is_empty() -> unittest::Result<()> {
151        let buffer = CircularBuffer::<u32, 8>::new();
152        unittest::assert_true!(buffer.is_empty());
153        unittest::assert_false!(buffer.is_full());
154        unittest::assert_eq!(buffer.len(), 0);
155        unittest::assert_eq!(buffer.capacity(), 8);
156
157        Ok(())
158    }
159
160    #[test]
161    fn push_and_pop_one_element() -> unittest::Result<()> {
162        let mut buffer = CircularBuffer::<u32, 8>::new();
163
164        buffer.push_back(42).unwrap();
165        unittest::assert_false!(buffer.is_empty());
166        unittest::assert_eq!(buffer.len(), 1);
167
168        let item = buffer.pop_front();
169        unittest::assert_eq!(item, Some(42));
170        unittest::assert_true!(buffer.is_empty());
171        unittest::assert_eq!(buffer.len(), 0);
172
173        Ok(())
174    }
175
176    #[test]
177    fn fill_and_empty_buffer() -> unittest::Result<()> {
178        let mut buffer = CircularBuffer::<u32, 4>::new();
179
180        for i in 0..4 {
181            buffer.push_back(i).unwrap();
182        }
183        unittest::assert_true!(buffer.is_full());
184        unittest::assert_eq!(buffer.len(), 4);
185
186        for i in 0..4 {
187            let item = buffer.pop_front();
188            unittest::assert_eq!(item, Some(i));
189        }
190        unittest::assert_true!(buffer.is_empty());
191
192        Ok(())
193    }
194
195    #[test]
196    fn push_to_full_buffer_returns_error() -> unittest::Result<()> {
197        let mut buffer = CircularBuffer::<u32, 2>::new();
198
199        buffer.push_back(1).unwrap();
200        buffer.push_back(2).unwrap();
201        unittest::assert_true!(buffer.is_full());
202
203        let result = buffer.push_back(3);
204        unittest::assert_true!(result.is_err());
205        unittest::assert_eq!(result.unwrap_err(), Error::ResourceExhausted);
206
207        Ok(())
208    }
209
210    #[test]
211    fn pop_from_empty_buffer_returns_none() -> unittest::Result<()> {
212        let mut buffer = CircularBuffer::<u32, 2>::new();
213
214        let item = buffer.pop_front();
215        unittest::assert_true!(item.is_none());
216
217        Ok(())
218    }
219
220    #[test]
221    fn wrap_around_behavior() -> unittest::Result<()> {
222        let mut buffer = CircularBuffer::<u32, 3>::new();
223
224        buffer.push_back(1).unwrap();
225        buffer.push_back(2).unwrap();
226        buffer.push_back(3).unwrap();
227        unittest::assert_eq!(buffer.pop_front().unwrap(), 1);
228
229        buffer.push_back(4).unwrap();
230        unittest::assert_true!(buffer.is_full());
231        unittest::assert_eq!(buffer.pop_front().unwrap(), 2);
232        unittest::assert_eq!(buffer.pop_front().unwrap(), 3);
233        unittest::assert_eq!(buffer.pop_front().unwrap(), 4);
234        unittest::assert_true!(buffer.is_empty());
235
236        Ok(())
237    }
238
239    #[test]
240    fn drop_drops_elements() -> unittest::Result<()> {
241        use core::cell::Cell;
242
243        struct DropCounter<'a> {
244            count: &'a Cell<u32>,
245        }
246
247        impl<'a> Drop for DropCounter<'a> {
248            fn drop(&mut self) {
249                self.count.set(self.count.get() + 1);
250            }
251        }
252
253        let counter = Cell::new(0);
254        {
255            let mut buffer = CircularBuffer::<DropCounter, 4>::new();
256            buffer.push_back(DropCounter { count: &counter }).unwrap();
257            buffer.push_back(DropCounter { count: &counter }).unwrap();
258        }
259        unittest::assert_eq!(counter.get(), 2);
260        Ok(())
261    }
262}