Skip to main content

ntex_util/channel/
oneshot.rs

1//! A one-shot, futures-aware channel.
2use std::{future::Future, future::poll_fn, pin::Pin, task::Context, task::Poll};
3
4use super::{Canceled, cell::Cell, cell::wake};
5use crate::task::LocalWaker;
6
7/// Creates a new futures-aware, one-shot channel.
8pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
9    let inner = Cell::new(Inner {
10        value: None,
11        rx_task: LocalWaker::new(),
12    });
13    let tx = Sender {
14        inner: inner.clone(),
15    };
16    let rx = Receiver { inner };
17    (tx, rx)
18}
19
20/// Represents the completion half of a oneshot through which the result of a
21/// computation is signaled.
22#[derive(Debug)]
23pub struct Sender<T> {
24    inner: Cell<Inner<T>>,
25}
26
27/// A future representing the completion of a computation happening elsewhere in
28/// memory.
29#[derive(Debug)]
30#[must_use = "futures do nothing unless polled"]
31pub struct Receiver<T> {
32    inner: Cell<Inner<T>>,
33}
34
35// The channels do not ever project Pin to the inner T
36impl<T> Unpin for Receiver<T> {}
37impl<T> Unpin for Sender<T> {}
38
39#[derive(Debug)]
40struct Inner<T> {
41    value: Option<T>,
42    rx_task: LocalWaker,
43}
44
45impl<T> Sender<T> {
46    /// Completes this oneshot with a successful result.
47    ///
48    /// This function will consume `self` and indicate to the other end, the
49    /// `Receiver`, that the value provided is the result of the computation this
50    /// represents.
51    ///
52    /// If the value is successfully enqueued for the remote end to receive,
53    /// then `Ok(())` is returned. If the receiving end was dropped before
54    /// this function was called, however, then `Err` is returned with the value
55    /// provided.
56    pub fn send(self, val: T) -> Result<(), T> {
57        if self.inner.strong_count() == 2 {
58            let waker = {
59                let inner = self.inner.get_mut();
60                inner.value = Some(val);
61                inner.rx_task.take_local()
62            };
63            wake(waker);
64            Ok(())
65        } else {
66            Err(val)
67        }
68    }
69
70    /// Tests to see whether this `Sender`'s corresponding `Receiver`
71    /// has gone away.
72    pub fn is_canceled(&self) -> bool {
73        self.inner.strong_count() == 1
74    }
75}
76
77impl<T> Drop for Sender<T> {
78    fn drop(&mut self) {
79        let waker = self.inner.get_ref().rx_task.take_local();
80        wake(waker);
81    }
82}
83
84impl<T> Receiver<T> {
85    /// Waits for the value.
86    ///
87    /// Returns [`Canceled`] if the sender is dropped without sending a value.
88    pub async fn recv(&self) -> Result<T, Canceled> {
89        poll_fn(|cx| self.poll_recv(cx)).await
90    }
91
92    /// Polls for the value.
93    ///
94    /// Returns [`Canceled`] if the sender is dropped without sending a value.
95    pub fn poll_recv(&self, cx: &mut Context<'_>) -> Poll<Result<T, Canceled>> {
96        if let Poll::Ready(res) = self.try_recv() {
97            return Poll::Ready(res);
98        }
99        LocalWaker::register_in(|| &self.inner.get_ref().rx_task, cx.waker());
100
101        // the waker callbacks may have sent the value or dropped the sender
102        self.try_recv()
103    }
104
105    fn try_recv(&self) -> Poll<Result<T, Canceled>> {
106        if let Some(val) = self.inner.get_mut().value.take() {
107            Poll::Ready(Ok(val))
108        } else if self.inner.strong_count() == 1 {
109            Poll::Ready(Err(Canceled))
110        } else {
111            Poll::Pending
112        }
113    }
114}
115
116impl<T> Future for Receiver<T> {
117    type Output = Result<T, Canceled>;
118
119    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
120        self.poll_recv(cx)
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use crate::future::lazy;
128    use crate::task::hooks::{ON_CLONE, hook_waker};
129
130    /// STATEMENT: One-shot channels deliver once and expose cancellation when either endpoint drops.
131    ///
132    /// HOW:
133    /// - Receive values through both future and `recv` APIs, including after a pending poll.
134    /// - Drop each endpoint in fresh channels and check sender cancellation and receiver errors.
135    #[ntex::test]
136    async fn test_oneshot() {
137        let (tx, rx) = channel();
138
139        tx.send("test").unwrap();
140        assert_eq!(rx.await.unwrap(), "test");
141
142        let (tx, rx) = channel();
143        tx.send("test").unwrap();
144        assert_eq!(rx.recv().await.unwrap(), "test");
145
146        let (tx, rx) = channel();
147        assert!(!tx.is_canceled());
148        drop(rx);
149        assert!(tx.is_canceled());
150        assert!(tx.send("test").is_err());
151
152        let (tx, rx) = channel::<&'static str>();
153        drop(tx);
154        assert!(rx.await.is_err());
155
156        let (tx, mut rx) = channel::<&'static str>();
157        assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
158        tx.send("test").unwrap();
159        assert_eq!(rx.await.unwrap(), "test");
160
161        let (tx, mut rx) = channel::<&'static str>();
162        assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending);
163        drop(tx);
164        assert!(rx.await.is_err());
165    }
166
167    /// STATEMENT: `poll_recv` returns a value sent by its waker's clone callback instead of missing it.
168    ///
169    /// HOW:
170    /// - Set an `ON_CLONE` hook that sends `1` through the sender.
171    /// - Poll the receiver with `hook_waker` and check it returns `Ready(Ok(1))`.
172    #[test]
173    fn miri_poll_recv_with_reentrant_clone() {
174        let (tx, rx) = channel();
175        ON_CLONE.set(Some(Box::new(move || tx.send(1).unwrap())));
176
177        let waker = hook_waker();
178        let mut cx = Context::from_waker(&waker);
179        assert_eq!(rx.poll_recv(&mut cx), Poll::Ready(Ok(1)));
180    }
181}