unsync 0.2.0

Unsynchronized synchronization primitives for async Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! An unsynchronized single-producer, single-consumer channel.
//!
//! You might also know this simply as a "queue", but I'm sticking with a
//! uniform naming scheme here so give me a break.
//!
//! This allocates storage internally to maintain shared state between the
//! [Sender] and [Receiver].

use core::error::Error;
use core::fmt::{self, Debug, Display, Formatter};
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll, Waker};

use alloc::collections::VecDeque;

use crate::bi_rc::BiRc;

/// Error raised when sending a message over the queue.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct SendError<T>(pub T);

impl<T> Display for SendError<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "channel disconnected")
    }
}

impl<T> Error for SendError<T> where T: Debug {}

/// Interior shared state.
///
/// Note that we maintain two sets of waker to avoid having to clone the waker
/// associated with the channel unecessarily through the [`Waker::will_wake`]
/// optimization. This is done because it's presumed that the channel will be
/// re-used.
struct Shared<T> {
    /// Waker to wake once sending is available.
    tx: Option<Waker>,
    /// Waker to wake once receiving is available.
    rx: Option<Waker>,
    /// The buffer of messages for this channel.
    buf: VecDeque<T>,
    /// Indicates if the channel is unbounded.
    unbounded: bool,
}

impl<T> Shared<T> {
    /// Test if the current channel is at capacity.
    fn at_capacity(&self) -> bool {
        !self.unbounded && self.buf.capacity() == self.buf.len()
    }
}

/// Sender end of the channel created through [`channel`].
pub struct Sender<T> {
    inner: BiRc<Shared<T>>,
}

impl<T> Sender<T> {
    /// Try to send a message on this channel without blocking.
    ///
    /// This will succeed if there is sufficient capacity to send, but fail
    /// otherwise.
    ///
    /// Note: don't attempt to use this as an optimization over [`Sender::send`]
    /// since it already performs this operation internally as needed.
    ///
    /// # Examples
    ///
    /// ```rust
    /// #[tokio::main(flavor = "current_thread")]
    /// # async fn main() {
    /// let (mut tx, mut rx) = unsync::spsc::channel(3);
    /// assert!(tx.try_send(1).is_ok());
    /// assert!(tx.try_send(2).is_ok());
    /// assert!(tx.try_send(3).is_ok());
    /// assert!(tx.try_send(4).is_err());
    ///
    /// let first = rx.recv().await;
    /// assert_eq!(first, Some(1));
    ///
    /// assert!(tx.try_send(5).is_ok());
    /// assert!(tx.try_send(6).is_err());
    ///
    /// let mut collected = Vec::new();
    ///
    /// // Drop sender so that the channel "ends".
    /// drop(tx);
    ///
    /// while let Some(value) = rx.recv().await {
    ///     collected.push(value);
    /// }
    ///
    /// assert_eq!(collected, vec![2, 3, 5]);
    /// # }
    /// ```
    pub fn try_send(&mut self, value: T) -> Result<(), SendError<T>> {
        unsafe {
            let (inner, both_present) = self.inner.get_mut_unchecked();

            if !both_present || inner.at_capacity() {
                return Err(SendError(value));
            }

            inner.buf.push_back(value);

            if let Some(waker) = &inner.rx {
                waker.wake_by_ref();
            };

            Ok(())
        }
    }

    /// Send a message on this channel.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tokio::task;
    ///
    /// # #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), task::JoinError> {
    /// let (mut tx, mut rx) = unsync::spsc::channel(1);
    ///
    /// let local = task::LocalSet::new();
    ///
    /// let collected = local.run_until(async move {
    ///     let collect = task::spawn_local(async move {
    ///         let mut out = Vec::new();
    ///
    ///         while let Some(value) = rx.recv().await {
    ///             out.push(value);
    ///         }
    ///
    ///         out
    ///     });
    ///
    ///     let sender = task::spawn_local(async move {
    ///         for n in 0..10 {
    ///             let result = tx.send(n).await;
    ///         }
    ///     });
    ///
    ///     collect.await
    /// }).await?;
    ///
    /// assert_eq!(collected, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
    /// # Ok(()) }
    /// ```
    pub async fn send(&mut self, value: T) -> Result<(), SendError<T>> {
        Send {
            inner: &self.inner,
            value: Some(value),
        }
        .await
    }
}

/// Future returned when sending a value through [Sender::send].
struct Send<'a, T> {
    inner: &'a BiRc<Shared<T>>,
    value: Option<T>,
}

impl<T> Future for Send<'_, T> {
    type Output = Result<(), SendError<T>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = Pin::into_inner(self);

        unsafe {
            let (inner, both_present) = this.inner.get_mut_unchecked();

            if !both_present {
                inner.tx = None;
                let value = this.value.take().expect("future already completed");
                return Poll::Ready(Err(SendError(value)));
            }

            // If we are at capacity, register ourselves as an interested waker
            // and move on.
            if inner.at_capacity() {
                if !matches!(&inner.tx, Some(w) if w.will_wake(cx.waker())) {
                    inner.tx = Some(cx.waker().clone());
                }

                return Poll::Pending;
            };

            inner
                .buf
                .push_back(this.value.take().expect("future already completed"));

            if let Some(waker) = &inner.rx {
                waker.wake_by_ref();
            };

            Poll::Ready(Ok(()))
        }
    }
}

impl<T> Unpin for Send<'_, T> {}

/// Receiver end of the channel created through [channel].
pub struct Receiver<T> {
    inner: BiRc<Shared<T>>,
}

impl<T> Receiver<T> {
    /// Receive a message on this channel.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use tokio::task;
    ///
    /// # #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), task::JoinError> {
    /// let (mut tx, mut rx) = unsync::spsc::channel(1);
    ///
    /// let local = task::LocalSet::new();
    ///
    /// let collected = local.run_until(async move {
    ///     let collect = task::spawn_local(async move {
    ///         let mut out = Vec::new();
    ///
    ///         while let Some(value) = rx.recv().await {
    ///             out.push(value);
    ///         }
    ///
    ///         out
    ///     });
    ///
    ///     let sender = task::spawn_local(async move {
    ///         for n in 0..10 {
    ///             let result = tx.send(n).await;
    ///         }
    ///     });
    ///
    ///     collect.await
    /// }).await?;
    ///
    /// assert_eq!(collected, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
    /// # Ok(()) }
    /// ```
    pub async fn recv(&mut self) -> Option<T> {
        Recv { inner: &self.inner }.await
    }
}

struct Recv<'a, T> {
    inner: &'a BiRc<Shared<T>>,
}

impl<T> Future for Recv<'_, T> {
    type Output = Option<T>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = Pin::into_inner(self);

        unsafe {
            let (inner, both_present) = this.inner.get_mut_unchecked();

            if let Some(value) = inner.buf.pop_front() {
                // Popping freed capacity, so wake a sender waiting to send.
                if let Some(tx) = &inner.tx {
                    tx.wake_by_ref();
                }

                return Poll::Ready(Some(value));
            }

            if !both_present {
                inner.rx = None;
                return Poll::Ready(None);
            }

            if !matches!(&inner.rx, Some(w) if w.will_wake(cx.waker())) {
                inner.rx = Some(cx.waker().clone())
            }

            if let Some(tx) = &inner.tx {
                tx.wake_by_ref();
            }

            Poll::Pending
        }
    }
}

impl<T> Drop for Sender<T> {
    fn drop(&mut self) {
        unsafe {
            if let Some(waker) = self.inner.get_mut_unchecked().0.rx.take() {
                waker.wake();
            }
        }
    }
}

impl<T> Drop for Receiver<T> {
    fn drop(&mut self) {
        unsafe {
            if let Some(waker) = self.inner.get_mut_unchecked().0.tx.take() {
                waker.wake();
            }
        }
    }
}

/// Setup a spsc with the given capacity.
///
/// Any sender is capable of sending without blocking up until `capacity` number
/// of elements have been buffered.
///
/// # Panics
///
/// Panics if `capacity` is set to `0`.
pub fn channel<T>(capacity: usize) -> (Sender<T>, Receiver<T>) {
    assert!(capacity > 0, "capacity cannot be 0");

    let (a, b) = BiRc::new(Shared {
        tx: None,
        rx: None,
        buf: VecDeque::with_capacity(capacity),
        unbounded: false,
    });

    let rx = Receiver { inner: a };
    let tx = Sender { inner: b };

    (tx, rx)
}

/// Setup a spsc with an unbounded capacity.
///
/// Sending through this channel will never block.
pub fn unbounded<T>() -> (Sender<T>, Receiver<T>) {
    let (a, b) = BiRc::new(Shared {
        tx: None,
        rx: None,
        buf: VecDeque::new(),
        unbounded: true,
    });

    let rx = Receiver { inner: a };
    let tx = Sender { inner: b };

    (tx, rx)
}

#[cfg(test)]
mod tests {
    use core::future::Future;
    use core::sync::atomic::{AtomicBool, Ordering};
    use core::task::{Context, Poll, Waker};

    use alloc::boxed::Box;
    use alloc::sync::Arc;
    use alloc::task::Wake;

    use super::channel;
    use crate::utils::noop_cx;

    struct Flag(AtomicBool);

    impl Wake for Flag {
        fn wake(self: Arc<Self>) {
            self.0.store(true, Ordering::SeqCst);
        }

        fn wake_by_ref(self: &Arc<Self>) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    // A `recv` re-polled with a new waker (e.g. moved between tasks) must register
    // it. Otherwise a later send wakes the old waker and the receiver never runs.
    #[test]
    fn recv_updates_changed_waker() {
        let (mut tx, mut rx) = channel::<u32>(1);

        let first = Arc::new(Flag(AtomicBool::new(false)));
        let second = Arc::new(Flag(AtomicBool::new(false)));
        let w1 = Waker::from(first.clone());
        let w2 = Waker::from(second.clone());

        let mut fut = Box::pin(rx.recv());
        assert!(
            fut.as_mut()
                .poll(&mut Context::from_waker(&w1))
                .is_pending()
        );
        assert!(
            fut.as_mut()
                .poll(&mut Context::from_waker(&w2))
                .is_pending()
        );

        tx.try_send(1).unwrap();

        assert!(
            second.0.load(Ordering::SeqCst),
            "latest waker was not woken"
        );
    }

    // A sender blocked on a full channel must be woken when the receiver pops a
    // value (freeing capacity), not only the next time it finds the queue empty.
    #[test]
    fn recv_wakes_blocked_sender_on_pop() {
        let (mut tx, mut rx) = channel::<u32>(1);
        tx.try_send(1).unwrap();

        let sender = Arc::new(Flag(AtomicBool::new(false)));
        let ws = Waker::from(sender.clone());

        // The channel is full, so this send parks and registers `ws`.
        let mut send = Box::pin(tx.send(2));
        assert!(
            send.as_mut()
                .poll(&mut Context::from_waker(&ws))
                .is_pending()
        );

        // Popping a value frees capacity and must wake the parked sender.
        let mut recv = Box::pin(rx.recv());
        assert_eq!(recv.as_mut().poll(&mut noop_cx()), Poll::Ready(Some(1)));

        assert!(
            sender.0.load(Ordering::SeqCst),
            "blocked sender was not woken"
        );
    }
}