Skip to content

Commit c961718

Browse files
committed
Make Queue::split const.
1 parent 1a33fec commit c961718

File tree

3 files changed

+143
-8
lines changed

3 files changed

+143
-8
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
5555
- Changed `stable_deref_trait` to a platform-dependent dependency.
5656
- Changed `SortedLinkedList::pop` return type from `Result<T, ()>` to `Option<T>` to match `std::vec::pop`.
5757
- `Vec::capacity` is no longer a `const` function.
58+
- Changed `Queue::split` to be `const`.
5859

5960
### Fixed
6061

Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ defmt-03 = ["dep:defmt"]
3939
# Enable larger MPMC sizes.
4040
mpmc_large = []
4141

42+
# Enable nightly features.
4243
nightly = []
4344

4445
[dependencies]
@@ -53,6 +54,7 @@ defmt = { version = ">=0.2.0,<0.4", optional = true }
5354
stable_deref_trait = { version = "1", default-features = false }
5455

5556
[dev-dependencies]
57+
critical-section = { version = "1.1", features = ["std"] }
5658
ufmt = "0.2"
5759
static_assertions = "1.1.0"
5860

src/spsc.rs

+140-8
Original file line numberDiff line numberDiff line change
@@ -128,16 +128,21 @@ pub struct QueueInner<T, S: Storage> {
128128
pub(crate) buffer: S::Buffer<UnsafeCell<MaybeUninit<T>>>,
129129
}
130130

131-
/// A statically allocated single producer single consumer queue with a capacity of `N - 1` elements
131+
/// A statically allocated single producer, single consumer queue with a capacity of `N - 1` elements.
132132
///
133-
/// *IMPORTANT*: To get better performance use a value for `N` that is a power of 2 (e.g. `16`, `32`,
134-
/// etc.).
133+
/// >
134+
/// <div class="warning">
135+
///
136+
/// To get better performance use a value for `N` that is a power of 2, e.g. 16, 32, etc.
137+
///
138+
/// </div>
139+
///
140+
/// You will likely want to use [`split`](QueueInner::split) to create a producer and consumer handle.
135141
pub type Queue<T, const N: usize> = QueueInner<T, OwnedStorage<N>>;
136142

137-
/// Asingle producer single consumer queue
143+
/// A [`Queue`] with dynamic capacity.
138144
///
139-
/// *IMPORTANT*: To get better performance use a value for `N` that is a power of 2 (e.g. `16`, `32`,
140-
/// etc.).
145+
/// [`Queue`] coerces to `QueueView`. `QueueView` is `!Sized`, meaning it can only ever be used by reference.
141146
pub type QueueView<T> = QueueInner<T, ViewStorage>;
142147

143148
impl<T, const N: usize> Queue<T, N> {
@@ -352,8 +357,106 @@ impl<T, S: Storage> QueueInner<T, S> {
352357
self.inner_dequeue_unchecked()
353358
}
354359

355-
/// Splits a queue into producer and consumer endpoints
356-
pub fn split(&mut self) -> (ProducerInner<'_, T, S>, ConsumerInner<'_, T, S>) {
360+
/// Splits a queue into producer and consumer endpoints.
361+
///
362+
/// # Examples
363+
///
364+
/// Create a queue at compile time, split it at runtime,
365+
/// and pass it to an interrupt handler via a mutex.
366+
///
367+
/// ```
368+
/// use core::cell::RefCell;
369+
/// use critical_section::Mutex;
370+
/// use heapless::spsc::{Producer, Queue};
371+
///
372+
/// static PRODUCER: Mutex<RefCell<Option<Producer<'static, (), 4>>>> =
373+
/// Mutex::new(RefCell::new(None));
374+
///
375+
/// fn interrupt() {
376+
/// let mut producer = {
377+
/// static mut P: Option<Producer<'static, (), 4>> = None;
378+
/// // SAFETY: Mutable access to `P` is allowed exclusively in this scope
379+
/// // and `interrupt` cannot be called directly or preempt itself.
380+
/// unsafe { &mut P }
381+
/// }
382+
/// .get_or_insert_with(|| {
383+
/// critical_section::with(|cs| PRODUCER.borrow_ref_mut(cs).take().unwrap())
384+
/// });
385+
///
386+
/// producer.enqueue(()).unwrap();
387+
/// }
388+
///
389+
/// fn main() {
390+
/// let mut consumer = {
391+
/// let (p, c) = {
392+
/// static mut Q: Queue<(), 4> = Queue::new();
393+
/// // SAFETY: `Q` is accessed mutably exclusively in this scope
394+
/// // and `main` is only called once.
395+
/// unsafe { Q.split() }
396+
/// };
397+
///
398+
/// critical_section::with(move |cs| {
399+
/// let mut producer = PRODUCER.borrow_ref_mut(cs);
400+
/// *producer = Some(p);
401+
/// });
402+
///
403+
/// c
404+
/// };
405+
///
406+
/// // Interrupt occurs.
407+
/// # interrupt();
408+
///
409+
/// consumer.dequeue().unwrap();
410+
/// }
411+
/// ```
412+
///
413+
/// Create and split a queue at compile time, and pass it to the main
414+
/// function and an interrupt handler via a mutex at runtime.
415+
///
416+
/// ```
417+
/// use core::cell::RefCell;
418+
///
419+
/// use critical_section::Mutex;
420+
/// use heapless::spsc::{Consumer, Producer, Queue};
421+
///
422+
/// static PC: (
423+
/// Mutex<RefCell<Option<Producer<'_, (), 4>>>>,
424+
/// Mutex<RefCell<Option<Consumer<'_, (), 4>>>>,
425+
/// ) = {
426+
/// static mut Q: Queue<(), 4> = Queue::new();
427+
/// // SAFETY: `Q` is accessed mutably exclusively in this scope.
428+
/// let (p, c) = unsafe { Q.split() };
429+
///
430+
/// (
431+
/// Mutex::new(RefCell::new(Some(p))),
432+
/// Mutex::new(RefCell::new(Some(c))),
433+
/// )
434+
/// };
435+
///
436+
/// fn interrupt() {
437+
/// let mut producer = {
438+
/// static mut P: Option<Producer<'_, (), 4>> = None;
439+
/// // SAFETY: Mutable access to `P` is allowed exclusively in this scope
440+
/// // and `interrupt` cannot be called directly or preempt itself.
441+
/// unsafe { &mut P }
442+
/// }
443+
/// .get_or_insert_with(|| {
444+
/// critical_section::with(|cs| PC.0.borrow_ref_mut(cs).take().unwrap())
445+
/// });
446+
///
447+
/// producer.enqueue(()).unwrap();
448+
/// }
449+
///
450+
/// fn main() {
451+
/// let mut consumer = critical_section::with(|cs| PC.1.borrow_ref_mut(cs).take().unwrap());
452+
///
453+
/// // Interrupt occurs.
454+
/// # interrupt();
455+
///
456+
/// consumer.dequeue().unwrap();
457+
/// }
458+
/// ```
459+
pub const fn split(&mut self) -> (ProducerInner<'_, T, S>, ConsumerInner<'_, T, S>) {
357460
(ProducerInner { rb: self }, ConsumerInner { rb: self })
358461
}
359462
}
@@ -734,6 +837,35 @@ mod tests {
734837
// Ensure a `Consumer` containing `!Send` values stays `!Send` itself.
735838
assert_not_impl_any!(Consumer<*const (), 4>: Send);
736839

840+
#[test]
841+
fn const_split() {
842+
use critical_section::Mutex;
843+
use std::cell::RefCell;
844+
845+
use super::{Consumer, Producer};
846+
847+
static PC: (
848+
Mutex<RefCell<Option<Producer<'_, (), 4>>>>,
849+
Mutex<RefCell<Option<Consumer<'_, (), 4>>>>,
850+
) = {
851+
static mut Q: Queue<(), 4> = Queue::new();
852+
let (p, c) = unsafe { Q.split() };
853+
854+
(
855+
Mutex::new(RefCell::new(Some(p))),
856+
Mutex::new(RefCell::new(Some(c))),
857+
)
858+
};
859+
let producer = critical_section::with(|cs| PC.0.borrow_ref_mut(cs).take().unwrap());
860+
let consumer = critical_section::with(|cs| PC.1.borrow_ref_mut(cs).take().unwrap());
861+
862+
let mut producer: Producer<'static, (), 4> = producer;
863+
let mut consumer: Consumer<'static, (), 4> = consumer;
864+
865+
assert_eq!(producer.enqueue(()), Ok(()));
866+
assert_eq!(consumer.dequeue(), Some(()));
867+
}
868+
737869
#[test]
738870
fn full() {
739871
let mut rb: Queue<i32, 3> = Queue::new();

0 commit comments

Comments
 (0)