Skip to main content

dfir_rs/util/unsync/
mpsc.rs

1//! Unsync single-producer single-consumer channel (i.e. a single-threaded queue with async hooks).
2
3use std::cell::RefCell;
4use std::collections::VecDeque;
5use std::num::NonZeroUsize;
6use std::pin::Pin;
7use std::rc::{Rc, Weak};
8use std::task::{Context, Poll, Waker};
9
10use futures::{Sink, Stream, ready};
11#[doc(inline)]
12pub use tokio::sync::mpsc::error::{SendError, TrySendError};
13
14/// Send half of am unsync MPSC.
15pub struct Sender<T> {
16    weak: Weak<RefCell<Shared<T>>>,
17}
18impl<T> Sender<T> {
19    /// Asynchronously sends value to the receiver.
20    pub async fn send(&self, item: T) -> Result<(), SendError<T>> {
21        let mut item = Some(item);
22        std::future::poll_fn(move |ctx| {
23            if let Some(strong) = Weak::upgrade(&self.weak) {
24                let mut shared = strong.borrow_mut();
25                if shared
26                    .capacity
27                    .is_some_and(|cap| cap.get() <= shared.buffer.len())
28                {
29                    // Full.
30                    shared.send_wakers.push(ctx.waker().clone());
31                    Poll::Pending
32                } else {
33                    shared.buffer.push_back(item.take().unwrap());
34                    shared.wake_receiver();
35                    Poll::Ready(Ok(()))
36                }
37            } else {
38                // Closed.
39                Poll::Ready(Err(SendError(item.take().unwrap())))
40            }
41        })
42        .await
43    }
44
45    /// Tries to send the value to the receiver without blocking.
46    ///
47    /// Returns an error if the destination is closed or if the buffer is at capacity.
48    ///
49    /// [`TrySendError::Full`] will never be returned if this is an unbounded channel.
50    pub fn try_send(&self, item: T) -> Result<(), TrySendError<T>> {
51        if let Some(strong) = Weak::upgrade(&self.weak) {
52            let mut shared = strong.borrow_mut();
53            if shared
54                .capacity
55                .is_some_and(|cap| cap.get() <= shared.buffer.len())
56            {
57                Err(TrySendError::Full(item))
58            } else {
59                shared.buffer.push_back(item);
60                shared.wake_receiver();
61                Ok(())
62            }
63        } else {
64            Err(TrySendError::Closed(item))
65        }
66    }
67
68    /// Close this sender. No more messages can be sent from this sender.
69    ///
70    /// Note that this only closes the channel from the view-point of this sender. The channel
71    /// remains open until all senders have gone away, or until the [`Receiver`] closes the channel.
72    pub fn close_this_sender(&mut self) {
73        self.weak = Weak::new();
74    }
75
76    /// If this sender or the corresponding [`Receiver`] is closed.
77    pub fn is_closed(&self) -> bool {
78        0 == self.weak.strong_count()
79    }
80}
81impl<T> Clone for Sender<T> {
82    fn clone(&self) -> Self {
83        Self {
84            weak: self.weak.clone(),
85        }
86    }
87}
88impl<T> Drop for Sender<T> {
89    fn drop(&mut self) {
90        // Really we should only do this if we're the very last sender,
91        // But `1 == self.weak.weak_count()` seems unreliable.
92        if let Some(strong) = self.weak.upgrade() {
93            strong.borrow_mut().wake_receiver();
94        }
95    }
96}
97
98impl<T> Sink<T> for Sender<T> {
99    type Error = TrySendError<Option<T>>;
100
101    fn poll_ready(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
102        if let Some(strong) = Weak::upgrade(&self.weak) {
103            let mut shared = strong.borrow_mut();
104            if shared
105                .capacity
106                .is_some_and(|cap| cap.get() <= shared.buffer.len())
107            {
108                // Full.
109                shared.send_wakers.push(ctx.waker().clone());
110                Poll::Pending
111            } else {
112                // Has room.
113                Poll::Ready(Ok(()))
114            }
115        } else {
116            // Closed
117            Poll::Ready(Err(TrySendError::Closed(None)))
118        }
119    }
120
121    fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
122        self.try_send(item).map_err(|e| match e {
123            TrySendError::Full(item) => TrySendError::Full(Some(item)),
124            TrySendError::Closed(item) => TrySendError::Closed(Some(item)),
125        })
126    }
127
128    fn poll_flush(self: Pin<&mut Self>, _ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
129        Poll::Ready(Ok(()))
130    }
131
132    fn poll_close(
133        mut self: Pin<&mut Self>,
134        ctx: &mut Context<'_>,
135    ) -> Poll<Result<(), Self::Error>> {
136        ready!(self.as_mut().poll_flush(ctx))?;
137        Pin::into_inner(self).close_this_sender();
138        Poll::Ready(Ok(()))
139    }
140}
141
142/// Receiving half of an unsync MPSC.
143pub struct Receiver<T> {
144    strong: Rc<RefCell<Shared<T>>>,
145}
146impl<T> Receiver<T> {
147    /// Receive a value asynchronously.
148    pub async fn recv(&mut self) -> Option<T> {
149        std::future::poll_fn(|ctx| self.poll_recv(ctx)).await
150    }
151
152    /// Poll for a value.
153    /// NOTE: takes `&mut self` to prevent multiple concurrent receives.
154    pub fn poll_recv(&mut self, ctx: &Context<'_>) -> Poll<Option<T>> {
155        let mut shared = self.strong.borrow_mut();
156        if let Some(value) = shared.buffer.pop_front() {
157            shared.wake_sender();
158            Poll::Ready(Some(value))
159        } else if 0 == Rc::weak_count(&self.strong) {
160            Poll::Ready(None) // Empty and dropped.
161        } else {
162            shared.recv_waker = Some(ctx.waker().clone());
163            Poll::Pending
164        }
165    }
166
167    /// Closes this receiving end, not allowing more values to be sent while still allowing already-sent values to be consumed.
168    pub fn close(&mut self) {
169        assert_eq!(
170            1,
171            Rc::strong_count(&self.strong),
172            "BUG: receiver has non-exclusive Rc."
173        );
174
175        let new_shared = {
176            let mut shared = self.strong.borrow_mut();
177            shared.wake_all_senders();
178
179            Shared {
180                buffer: std::mem::take(&mut shared.buffer),
181                ..Default::default()
182            }
183        };
184        self.strong = Rc::new(RefCell::new(new_shared));
185        // Drop old `Rc`, invalidating all `Weak`s.
186    }
187}
188impl<T> Drop for Receiver<T> {
189    fn drop(&mut self) {
190        self.close()
191    }
192}
193impl<T> Stream for Receiver<T> {
194    type Item = T;
195
196    fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
197        self.poll_recv(ctx)
198    }
199}
200
201/// Struct shared between sender and receiver.
202///
203/// Hydro's simulator creates channels inside a `dlopen`ed dylib and polls them from the host
204/// test binary, so this layout must agree across two separate compilations of `dfir_rs`. Keep
205/// it to `std` types (whose layout is fixed by the shared toolchain) — third-party types can
206/// change layout under cargo feature unification (e.g. `smallvec/union`).
207struct Shared<T> {
208    buffer: VecDeque<T>,
209    capacity: Option<NonZeroUsize>,
210    send_wakers: SendWakers,
211    recv_waker: Option<Waker>,
212}
213impl<T> Shared<T> {
214    /// Wakes one sender (if there are any wakers), and removes the waker.
215    pub fn wake_sender(&mut self) {
216        if let Some(waker) = self.send_wakers.pop() {
217            waker.wake();
218        }
219    }
220    /// Wakes all senders and removes their wakers.
221    pub fn wake_all_senders(&mut self) {
222        self.send_wakers.wake_all();
223    }
224    /// Wakes the receiver (if the waker is set) and removes it.
225    pub fn wake_receiver(&mut self) {
226        if let Some(waker) = self.recv_waker.take() {
227            waker.wake();
228        }
229    }
230}
231
232/// Wakers of senders blocked on a full bounded channel.
233///
234/// Stores a single waker inline and only allocates once a second sender blocks concurrently
235/// (like the `SmallVec<[Waker; 1]>` it replaces), but is `std`-only for the layout reason
236/// documented on [`Shared`]. Wakers are popped LIFO.
237#[derive(Default)]
238enum SendWakers {
239    #[default]
240    Empty,
241    One(Waker),
242    Many(Vec<Waker>),
243}
244impl SendWakers {
245    fn push(&mut self, waker: Waker) {
246        *self = match std::mem::take(self) {
247            Self::Empty => Self::One(waker),
248            Self::One(first) => Self::Many(vec![first, waker]),
249            Self::Many(mut wakers) => {
250                wakers.push(waker);
251                Self::Many(wakers)
252            }
253        };
254    }
255
256    fn pop(&mut self) -> Option<Waker> {
257        match std::mem::take(self) {
258            Self::Empty => None,
259            Self::One(waker) => Some(waker),
260            Self::Many(mut wakers) => {
261                let waker = wakers.pop();
262                // Keep the allocation for the next burst of blocked senders.
263                *self = Self::Many(wakers);
264                waker
265            }
266        }
267    }
268
269    fn wake_all(&mut self) {
270        match std::mem::take(self) {
271            Self::Empty => {}
272            Self::One(waker) => waker.wake(),
273            Self::Many(wakers) => wakers.into_iter().for_each(Waker::wake),
274        }
275    }
276}
277impl<T> Default for Shared<T> {
278    fn default() -> Self {
279        let (buffer, capacity, send_wakers, recv_waker) = Default::default();
280        Self {
281            buffer,
282            capacity,
283            send_wakers,
284            recv_waker,
285        }
286    }
287}
288
289/// Create an unsync MPSC channel, either bounded (if `capacity` is `Some`) or unbounded (if `capacity` is `None`).
290pub fn channel<T>(capacity: Option<NonZeroUsize>) -> (Sender<T>, Receiver<T>) {
291    let (buffer, send_wakers, recv_waker) = Default::default();
292    let shared = Rc::new(RefCell::new(Shared {
293        buffer,
294        capacity,
295        send_wakers,
296        recv_waker,
297    }));
298    let sender = Sender {
299        weak: Rc::downgrade(&shared),
300    };
301    let receiver = Receiver { strong: shared };
302    (sender, receiver)
303}
304
305/// Create a bounded unsync MPSC channel. Panics if capacity is zero.
306pub fn bounded<T>(capacity: usize) -> (Sender<T>, Receiver<T>) {
307    let capacity = NonZeroUsize::new(capacity);
308    assert!(capacity.is_some(), "Capacity cannot be zero.");
309    channel(capacity)
310}
311
312/// Create an unbounded unsync MPSC channel.
313pub fn unbounded<T>() -> (Sender<T>, Receiver<T>) {
314    channel(None)
315}
316
317#[cfg(test)]
318mod test {
319    use futures::StreamExt;
320    use rand::RngExt;
321    use tokio::task::LocalSet;
322    use web_time::Duration;
323
324    use super::*;
325
326    async fn delay(n: u64) {
327        let millis = rand::rng().random_range(0..n);
328        tokio::time::sleep(Duration::from_millis(millis)).await;
329    }
330
331    #[crate::test]
332    async fn test_send_multiple_outstanding() {
333        let (send, recv) = bounded::<u64>(10);
334
335        let a_fut = send.send(123);
336        let b_fut = send.send(234);
337
338        futures::future::try_join(a_fut, b_fut).await.unwrap();
339        drop(send);
340
341        let mut out: Vec<_> = recv.collect().await;
342        out.sort_unstable();
343        assert_eq!([123, 234], &*out);
344    }
345
346    #[crate::test]
347    async fn test_spsc_random() {
348        let runs = (0..1_000).map(|_| async {
349            let (send, recv) = bounded::<u64>(10);
350
351            let local = LocalSet::new();
352
353            local.spawn_local(async move {
354                for x in 0..100 {
355                    send.send(x).await.unwrap();
356                    delay(4).await;
357                }
358            });
359            local.spawn_local(async move {
360                delay(5).await; // Delay once first.
361
362                let mut recv = recv;
363                let mut i = 0;
364                while let Some(x) = recv.recv().await {
365                    assert_eq!(i, x);
366                    i += 1;
367                    delay(5).await;
368                }
369                assert_eq!(100, i);
370            });
371            local.await;
372        });
373        futures::future::join_all(runs).await;
374    }
375
376    #[crate::test]
377    async fn test_mpsc_random() {
378        let runs = (0..1_000).map(|_| async {
379            let (send, recv) = bounded::<u64>(30);
380            let send_a = send.clone();
381            let send_b = send.clone();
382            let send_c = send;
383
384            let local = LocalSet::new();
385
386            local.spawn_local(async move {
387                for x in 0..100 {
388                    send_a.send(x).await.unwrap();
389                    delay(5).await;
390                }
391            });
392            local.spawn_local(async move {
393                for x in 100..200 {
394                    send_b.send(x).await.unwrap();
395                    delay(5).await;
396                }
397            });
398            local.spawn_local(async move {
399                for x in 200..300 {
400                    send_c.send(x).await.unwrap();
401                    delay(5).await;
402                }
403            });
404            local.spawn_local(async move {
405                delay(1).await; // Delay once first.
406
407                let mut recv = recv;
408                let mut vec = Vec::new();
409                while let Some(x) = recv.next().await {
410                    vec.push(x);
411                    delay(1).await;
412                }
413                assert_eq!(300, vec.len());
414                vec.sort_unstable();
415                for (i, &x) in vec.iter().enumerate() {
416                    assert_eq!(i as u64, x);
417                }
418            });
419            local.await;
420        });
421        futures::future::join_all(runs).await;
422    }
423
424    #[crate::test]
425    async fn test_stream_sink_loop() {
426        use futures::{SinkExt, StreamExt};
427
428        const N: usize = 100;
429
430        let (mut send, mut recv) = unbounded::<usize>();
431        send.send(0).await.unwrap();
432        // Connect it to itself
433        let mut recv_ref = recv.by_ref().map(|x| x + 1).map(Ok).take(N);
434        send.send_all(&mut recv_ref).await.unwrap();
435        assert_eq!(Some(N), recv.recv().await);
436    }
437
438    /// Several senders blocked on a full channel: freeing one slot wakes exactly one of
439    /// them, and closing the receiver wakes every remaining one (and fails their sends).
440    #[test]
441    fn test_bounded_blocked_senders_wakes() {
442        use std::sync::Arc;
443        use std::sync::atomic::{AtomicUsize, Ordering};
444        use std::task::Wake;
445
446        #[derive(Default)]
447        struct CountWakes(AtomicUsize);
448        impl Wake for CountWakes {
449            fn wake(self: Arc<Self>) {
450                self.0.fetch_add(1, Ordering::Relaxed);
451            }
452        }
453
454        let wakes = Arc::new(CountWakes::default());
455        let waker = Waker::from(Arc::clone(&wakes));
456        let mut cx = Context::from_waker(&waker);
457        let wake_count = || wakes.0.load(Ordering::Relaxed);
458
459        let (send, mut recv) = bounded::<u8>(1);
460        assert_eq!(
461            Poll::Ready(Ok(())),
462            Box::pin(send.send(0)).as_mut().poll(&mut cx)
463        );
464
465        let mut blocked: Vec<_> = (1..=3).map(|x| Box::pin(send.send(x))).collect();
466        for fut in &mut blocked {
467            assert!(fut.as_mut().poll(&mut cx).is_pending());
468        }
469        assert_eq!(0, wake_count());
470
471        // Freeing one slot wakes one blocked sender, not all of them.
472        assert_eq!(Poll::Ready(Some(0)), recv.poll_recv(&cx));
473        assert_eq!(1, wake_count());
474        assert!(recv.poll_recv(&cx).is_pending());
475
476        // Closing wakes the remaining blocked senders, whose sends then fail.
477        recv.close();
478        assert_eq!(3, wake_count());
479        for fut in &mut blocked {
480            assert!(matches!(fut.as_mut().poll(&mut cx), Poll::Ready(Err(_))));
481        }
482    }
483}