Skip to main content

low_latency_data_structures/spsc/
consumer.rs

1use std::marker::PhantomData;
2
3use crossbeam_utils::CachePadded;
4
5use crate::mem::Allocator;
6use crate::shim::cell::Cell;
7use crate::shim::sync::Arc;
8use crate::shim::sync::atomic::AtomicUsize;
9use crate::spsc::queue::Queue;
10
11pub(super) type ConsumerState = CachePadded<ConsumerStateInner>;
12
13#[derive(Default)]
14pub(super) struct ConsumerStateInner {
15    pub head: AtomicUsize,
16    pub cached_tail: Cell<usize>,
17}
18
19/// The popping handle of an SPSC FIFO queue.
20///
21/// Created together with its paired [`Producer`](crate::spsc::Producer) by
22/// [`new`](crate::spsc::new).
23/// `Consumer` is [`Send`] but not [`Sync`]: at most one thread may pop at a
24/// time.
25pub struct Consumer<T, const CAPACITY: usize, A>
26where
27    A: Allocator,
28{
29    inner: Arc<Queue<T, CAPACITY, A>>,
30    _not_sync: PhantomData<*const ()>,
31}
32
33impl<T, const CAPACITY: usize, A> std::fmt::Debug for Consumer<T, CAPACITY, A>
34where
35    A: Allocator,
36{
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.debug_struct("Consumer")
39            .field("capacity", &CAPACITY)
40            .finish_non_exhaustive()
41    }
42}
43
44// SAFETY: Consumer is Send because the underlying Queue is Send when both T
45// and the allocation are Send; PhantomData<*const ()> blocks Sync.
46unsafe impl<T, const CAPACITY: usize, A> Send for Consumer<T, CAPACITY, A>
47where
48    T: Send,
49    A: Allocator,
50    A::Allocation<T>: Send,
51{
52}
53
54impl<T, const CAPACITY: usize, A> Consumer<T, CAPACITY, A>
55where
56    A: Allocator,
57{
58    pub(super) fn new(queue: Arc<Queue<T, CAPACITY, A>>) -> Self {
59        Self {
60            inner: queue,
61            _not_sync: PhantomData,
62        }
63    }
64
65    /// Pops the next item from the queue.
66    ///
67    /// Wait-free. Returns `Some(item)` on success, `None` if the queue is
68    /// currently empty.
69    ///
70    /// # Examples
71    ///
72    /// ```
73    /// use low_latency_data_structures::spsc::{self, new};
74    /// use low_latency_data_structures::mem::global::GlobalAllocator;
75    ///
76    /// let (producer, consumer) = new::<u64, 4, GlobalAllocator>(
77    ///     spsc::Options::global_mlocked(),
78    /// );
79    /// assert_eq!(consumer.pop(), None);
80    /// let _ = producer.push(42);
81    /// assert_eq!(consumer.pop(), Some(42));
82    /// ```
83    #[inline]
84    #[must_use = "ignoring the popped item silently drops it"]
85    pub fn pop(&self) -> Option<T> {
86        self.inner.pop()
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    use crate::mem::test_util::NeverAllocator;
94
95    // Shouldn't be possible to construct Arc<Consumer<T>> and then use it from different threads as it
96    // will break the requirement of *Single* producer *Single* consumer queue.
97    static_assertions::assert_not_impl_any!(Consumer<u32, 0, NeverAllocator>: Sync);
98}