sync-oneshot 0.1.0

A minimal oneshot channel for synchronous 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! A minimal oneshot channel for synchronous Rust.
//!
//! A oneshot channel is used for sending a single message between threads.
//! The [`channel`] function is used to create a [`Sender`] and [`Receiver`]
//! handle pair that form the channel.
//!
//! - The [`Sender`] handle is used by the producer to send the value.
//! - The [`Receiver`] handle is used by the consumer to receive the value.
//!
//! Each handle can be used on other threads.
//!
//! - [`Sender::send`] will no block the calling thread.
//! - [`Receiver::recv`] will **block** the calling thread.
//!
//! # Example
//! ```rust
//! # use std::time::Duration;
//! let (tx, rx) = sync_oneshot::channel();
//!
//! std::thread::spawn(move || {
//!     std::thread::sleep(Duration::from_millis(200));
//!     tx.send(5).unwrap();
//! });
//!
//! // blocking thread until a message available
//! let val = rx.recv().unwrap();
//! assert_eq!(val, 5);
//! ```
#[cfg(loom)]
use loom::{
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
    thread,
};

use std::fmt;
#[cfg(not(loom))]
use std::{
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
    thread,
};

use crate::{notify::Notify, slot::Slot};

mod error;
mod notify;
mod slot;

pub use error::{RecvError, TryRecvError};

/// Creates a new oneshot channel, returning the sender/receiver halves.
///
/// The [`Sender`] is used by the producer to send the value.
/// The [`Receiver`] handle is used by the consumer to receive the value.
///
/// [`send`](Sender::send) will no block the calling thread. [`recv`](Receiver::recv)
/// will **block** until a message is available.
#[inline]
pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
    let inner = Arc::new(Inner {
        state: AtomicUsize::new(0),
        value: Slot::new(),
        notify: Notify::new(),
    });

    (
        Sender {
            inner: Some(inner.clone()),
        },
        Receiver { inner: Some(inner) },
    )
}

/// Sends a value to the associated [`Receiver`].
///
/// This is created by the [`channel`] function.
/// Messages can be sent using [`send`](Sender::send).
#[derive(Debug)]
pub struct Sender<T> {
    inner: Option<Arc<Inner<T>>>,
}

/// Receive a value from the associated [`Sender`].
///
/// This is created by the [`channel`] function.
/// Messages sent to the channel can be retrieved using [`recv`](Receiver::recv).
/// [`recv`](Receiver::recv) method blocks thread.
#[derive(Debug)]
pub struct Receiver<T> {
    inner: Option<Arc<Inner<T>>>,
}

unsafe impl<T> Send for Sender<T> where T: Send {}
unsafe impl<T> Sync for Sender<T> where T: Send {}

unsafe impl<T> Send for Receiver<T> where T: Send {}
unsafe impl<T> Sync for Receiver<T> where T: Send {}

struct Inner<T> {
    state: AtomicUsize,
    value: Slot<T>,
    notify: Notify,
}

/*
 *
 * ===== impl Sender =====
 *
 */
impl<T> Sender<T> {
    /// Attempts to send a value on this channel, returning it back if it could not be sent.
    ///
    /// A successful send occurs when it is determined that the other end of the
    /// channel has not hung up already. An unsuccessful send would be one where
    /// the corresponding receiver has already been deallocated. Note that a
    /// return value of [`Err`] means that the data will never be received, but
    /// a return value of [`Ok`] does *not* mean that the data will be received.
    /// It is possible for the corresponding receiver to hang up immediately
    /// after this function returns [`Ok`].
    ///
    /// This method will never block the current thread.
    /// # Example
    /// ```rust
    /// let (tx, rx) = sync_oneshot::channel();
    /// std::thread::spawn(move || {
    ///     if let Err(e) = tx.send(5) {
    ///         println!("the receiver dropped");
    ///     }
    /// });
    ///
    /// match rx.recv() {
    ///     Ok(v) => println!("got = {:?}", v),
    ///     Err(_) => println!("the sender dropped"),
    /// }
    /// ```
    #[inline]
    pub fn send(mut self, value: T) -> Result<(), T> {
        // take inner
        // The case inner None is unreachable
        let inner = self.inner.take().unwrap();

        // set value
        unsafe {
            // SAFETY:
            // Receiver don't access inner value until set status as VALUE_SENT
            inner.value.set(value);
        }

        // set state as VALUE_SEND and notify
        let prev_state = inner.set_complete();

        if prev_state.is_closed() {
            // SAFETY:
            // Receiver already has been droped. So can access inner value.
            return Err(unsafe { inner.consume_value().unwrap() });
        }

        if prev_state.is_waiting() {
            unsafe {
                inner.notify();
            }
        }

        Ok(())
    }

    /// Returns true if the associated Receiver handle has been dropped.
    ///
    /// A Receiver is closed by either calling close explicitly or the Receiver value is dropped.
    /// If true is returned, a call to send will always result in an error.
    pub fn is_closed(&self) -> bool {
        let inner = self.inner.as_ref().unwrap();
        State(inner.state.load(Ordering::Acquire)).is_closed()
    }
}

impl<T> Drop for Sender<T> {
    fn drop(&mut self) {
        if let Some(inner) = self.inner.take() {
            let prev_state = inner.set_complete();

            if prev_state.is_waiting() {
                unsafe {
                    inner.notify.notify();
                }
            }
        }
    }
}

/*
 *
 * ===== impl Receiver =====
 *
 */
impl<T> Receiver<T> {
    /// Attempts to wait for a value on this receiver, returning an error if
    /// the corresponding channel has hung up.
    ///
    /// This function will always block the current thread if there is no data
    /// available. Once a message is sent to the corresponding [`Sender`],
    /// this receiver will wake up and return that message.
    ///
    /// If the corresponding [`Sender`] has disconnected, or it disconnects while
    /// this call is blocking, this call will wake up and return [`Err`] to
    /// indicate that no more messages can ever be received on this channel.
    /// # Example
    /// ```rust
    /// let (tx, rx) = sync_oneshot::channel();
    ///
    /// let th_handle = std::thread::spawn(move || {
    ///     tx.send(5).unwrap();
    /// });
    ///
    /// th_handle.join().unwrap();
    ///
    /// assert_eq!(5, rx.recv().unwrap());
    /// ```
    #[inline]
    pub fn recv(mut self) -> Result<T, RecvError> {
        let inner = self.inner.take().unwrap();

        let mut state = inner.state.load(Ordering::Acquire);
        loop {
            if State(state).is_complete() {
                let value = unsafe { inner.consume_value() };
                return value.ok_or(RecvError);
            } else if State(state).is_closed() {
                return Err(RecvError);
            }

            unsafe {
                // SAFETY:
                // Notify::notify dose not call until state is WAITING.
                // So we can access notify.

                // Prevent double write due to spurious wake-up.
                if !State(state).is_waiting() {
                    inner.notify.set_current();
                }
            }

            match inner.state.compare_exchange(
                state,
                state | WAITING,
                Ordering::Release,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    thread::park();
                    state = inner.state.load(Ordering::Acquire);
                }
                Err(actual) => state = actual,
            }
        }
    }

    /// Attempts to return a pending value on this receiver without blocking.
    ///
    /// This method will never block the caller in order to wait for data to
    /// become available. Instead, this will always return immediately with a
    /// possible option of pending data on the channel.
    ///
    /// This is useful for a flavor of “optimistic check” before deciding to
    /// block on a receiver.
    ///
    /// Compared with recv, this function has two failure cases instead of one (one for disconnection, one for an empty buffer).
    #[inline]
    pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
        let result = if let Some(inner) = self.inner.as_ref() {
            let state = State(inner.state.load(Ordering::Acquire));

            if state.is_complete() {
                unsafe {
                    // SAFETY:
                    // When state is complete, Sender no longer access value
                    // Can access value safely
                    match inner.consume_value() {
                        Some(value) => Ok(value),
                        None => Err(TryRecvError::Closed),
                    }
                }
            } else if state.is_closed() {
                Err(TryRecvError::Closed)
            } else {
                return Err(TryRecvError::Empty);
            }
        } else {
            Err(TryRecvError::Closed)
        };

        self.inner = None;
        result
    }

    /// Prevents the associated [`Sender`] handle from sending a value.
    ///
    /// Any `send` operation which happens after calling `close` is guaranteed
    /// to fail. After calling `close`, [`try_recv`] should be called to
    /// receive a value if one was sent **before** the call to `close`
    /// completed.
    ///
    /// This function is useful to perform a graceful shutdown and ensure that a
    /// value will not be sent into the channel and never received.
    ///
    /// `close` is no-op if a message is already received or the channel
    /// is already closed.
    ///
    /// [`Sender`]: Sender
    /// [`try_recv`]: Receiver::try_recv
    ///
    /// # Examples
    ///
    /// Prevent a value from being sent
    ///
    /// ```
    /// use sync_oneshot::TryRecvError;
    ///
    /// # fn main() {
    /// let (tx, mut rx) = sync_oneshot::channel();
    ///
    /// assert!(!tx.is_closed());
    ///
    /// rx.close();
    ///
    /// assert!(tx.is_closed());
    /// assert!(tx.send("never received").is_err());
    ///
    /// match rx.try_recv() {
    ///     Err(TryRecvError::Closed) => {}
    ///     _ => unreachable!(),
    /// }
    /// # }
    /// ```
    ///
    /// Receive a value sent **before** calling `close`
    ///
    /// ```
    /// # fn main() {
    /// let (tx, mut rx) = sync_oneshot::channel();
    ///
    /// assert!(tx.send("will receive").is_ok());
    ///
    /// rx.close();
    ///
    /// let msg = rx.try_recv().unwrap();
    /// assert_eq!(msg, "will receive");
    /// # }
    /// ```
    pub fn close(&mut self) {
        if let Some(inner) = self.inner.as_ref() {
            let _ = inner.set_close();
        }
    }
}

impl<T> Drop for Receiver<T> {
    fn drop(&mut self) {
        // if inner is some, Receiver::recv is not called before drop.
        // Drop value or change state
        if let Some(inner) = self.inner.take() {
            let prev_state = inner.set_close();
            if prev_state.is_complete() {
                unsafe {
                    inner.consume_value();
                }
            }
        }
    }
}

/*
 *
 * ===== impl Inner =====
 *
 */
impl<T> Inner<T> {
    #[inline]
    fn set_complete(&self) -> State {
        let mut state = self.state.load(Ordering::Relaxed);
        loop {
            if State(state).is_closed() {
                break;
            }

            match self.state.compare_exchange_weak(
                state,
                state | VALUE_SENT,
                Ordering::AcqRel,
                Ordering::Relaxed,
            ) {
                Ok(_) => break,
                Err(actual) => state = actual,
            }
        }
        State(state)
    }

    #[inline]
    fn set_close(&self) -> State {
        State(self.state.fetch_or(CLOSED, Ordering::AcqRel))
    }

    #[inline]
    unsafe fn notify(&self) {
        unsafe {
            self.notify.notify();
        }
    }

    #[inline]
    unsafe fn consume_value(&self) -> Option<T> {
        unsafe { self.value.take() }
    }
}

impl<T: fmt::Debug> fmt::Debug for Inner<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Inner")
            .field("state", &State(self.state.load(Ordering::Relaxed)))
            .finish()
    }
}

struct State(usize);

const WAITING: usize = 0b0001;
const VALUE_SENT: usize = 0b0010;
const CLOSED: usize = 0b0100;

/*
 *
 * ===== impl State =====
 *
 */
impl State {
    #[inline]
    fn is_closed(&self) -> bool {
        self.0 & CLOSED == CLOSED
    }

    #[inline]
    fn is_waiting(&self) -> bool {
        self.0 & WAITING == WAITING
    }

    #[inline]
    fn is_complete(&self) -> bool {
        self.0 & VALUE_SENT == VALUE_SENT
    }
}

impl fmt::Debug for State {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("State")
            .field("is_complete", &self.is_complete())
            .field("is_closed", &self.is_closed())
            .field("is_waiting", &self.is_waiting())
            .finish()
    }
}