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
//! ## Futures-based Shuttle
//! A channel for shuttling a single object/message back and forth between two asynchronous tasks.
//! Contrary to the mutex or lock, shuttle always belongs to one of the two tasks. The side that
//! owns the control over `Shuttle` at a specific moment can manipulate its content and send it
//! to the other side. At this point control goes over to the other side and the original side
//! loses the ability to access the `Shuttle` object. It, however, can wait for `Shuttle`
//! to come back from the other side of the track, and then regain the access.

#![cfg_attr(all(feature = "cargo-clippy", feature = "pedantic"), warn(clippy_pedantic))]
#![cfg_attr(feature = "cargo-clippy", warn(use_self))]
#![cfg_attr(feature = "cargo-clippy", allow(missing_docs_in_private_items))]
#![deny(missing_debug_implementations, warnings)]
#![doc(html_root_url = "https://docs.rs/futures-shuttle/0.2.1")]

extern crate futures_core;
extern crate parking_lot;

use std::error::Error;
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst};

use futures_core::task::{AtomicWaker, Context, Waker};
use futures_core::{Async, Future, IntoFuture, Poll};
use parking_lot::{Mutex, MutexGuard};

/// Describes the possible error state of the `Shuttle` object.
#[derive(Debug, PartialEq)]
pub enum ShuttleError {
    /// This object' internal state is corrupted and it cannot be used anymore.
    Corrupted,
    /// This `Shuttle` has been stopped (the other side has been dropped and disappeared)
    Stopped,
}

impl fmt::Display for ShuttleError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.description())
    }
}

impl Error for ShuttleError {
    fn description(&self) -> &str {
        use ShuttleError::*;
        match *self {
            Corrupted => "Shuttle is corrupted",
            Stopped => "Shuttle is stopped",
        }
    }
}

/// Describes two possible owners of the `Shuttle` object.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Owner {
    Left,
    Right,
}

impl From<bool> for Owner {
    fn from(owner: bool) -> Self {
        if owner {
            Owner::Right
        } else {
            Owner::Left
        }
    }
}

impl From<Owner> for bool {
    fn from(owner: Owner) -> Self {
        match owner {
            Owner::Left => false,
            Owner::Right => true,
        }
    }
}

impl Owner {
    fn other(&self) -> Self {
        match *self {
            Owner::Left => Owner::Right,
            Owner::Right => Owner::Left,
        }
    }
}

/// This is created by the [`shuttle`](shuttle) function.
#[derive(Debug)]
pub struct Shuttle<T> {
    inner: Arc<Inner<T>>,
    whoami: Owner,
}

impl<T> Shuttle<T> {
    /// Checks this `Shuttle` object for being on my side of the track at this time.
    pub fn is_mine(&self) -> bool {
        self.whoami == self.inner.owner().into()
    }

    /// Access the underlying data item of this `Shuttle`. Similar to `MutexGuard`.
    pub fn data(&self) -> ShuttleValue<T> {
        ShuttleValue {
            data: self.inner.data(),
        }
    }

    /// Turns the ownership of this `Shuttle` object to the other side of the track.
    ///
    /// # Panics
    ///
    /// Panics if the shuttle is stopped. I.e. there is no other side to send it to.
    pub fn send(&self) {
        assert!(!self.inner.is_stopped(), "Sending stopped shuttle");
        self.send_impl();
    }

    /// Attempts to send the shuttle to the other end. If the shuttle is stopped it returns
    /// `ShuttleError::Stopped` error.
    pub fn try_send(&self) -> Result<(), ShuttleError> {
        if self.inner.is_stopped() {
            Err(ShuttleError::Stopped)
        } else {
            self.send_impl();
            Ok(())
        }
    }

    #[inline]
    fn send_impl(&self) {
        let other = self.whoami.other().into();
        self.inner.turnover(other);
    }

    fn left(inner: Arc<Inner<T>>) -> Self {
        Self {
            inner,
            whoami: Owner::Left,
        }
    }

    fn right(inner: Arc<Inner<T>>) -> Self {
        Self {
            inner,
            whoami: Owner::Right,
        }
    }

    fn pair(item: T) -> (Self, Self) {
        let left = Arc::new(Inner::new(item, false));
        let right = Arc::clone(&left);
        let left = Self::left(left);
        let right = Self::right(right);
        (left, right)
    }

    fn set_waker(&self, waker: &Waker) {
        let idx = self.whoami as usize;
        self.inner.set_waker(idx, waker);
    }
}

impl<T> Drop for Shuttle<T> {
    fn drop(&mut self) {
        self.inner.stop();
        if self.is_mine() {
            self.send_impl();
        }
    }
}

#[derive(Debug)]
pub struct ShuttleCombined<T> {
    inner: Arc<Inner<T>>,
}

impl<T> ShuttleCombined<T> {
    pub fn new(item: T) -> Self {
        let inner = Arc::new(Inner::new(item, true));
        Self { inner }
    }

    pub fn split(self) -> (Shuttle<T>, Shuttle<T>) {
        let left = self.inner;
        left.set_combined(false);
        let right = Arc::clone(&left);
        let left = Shuttle::left(left);
        let right = Shuttle::right(right);
        (left, right)
    }

    pub fn left(&self) -> ShuttleWait<T> {
        Shuttle::left(Arc::clone(&self.inner)).into_future()
    }

    pub fn right(&self) -> ShuttleWait<T> {
        Shuttle::right(Arc::clone(&self.inner)).into_future()
    }
}

/// Internal state of the `Shuttle` pair above. This is all used as
/// the internal synchronization between the two shuttle owners.
#[derive(Debug)]
struct Inner<T> {
    data: Mutex<T>,
    wakers: [AtomicWaker; 2],
    owner: AtomicBool,
    stopped: AtomicBool,
    combined: AtomicBool,
}

impl<T> Inner<T> {
    fn new(item: T, combined: bool) -> Self {
        Self {
            owner: AtomicBool::new(Owner::Left.into()),
            stopped: AtomicBool::new(false),
            combined: AtomicBool::new(combined),
            data: Mutex::new(item),
            wakers: Default::default(),
        }
    }

    #[inline]
    fn owner(&self) -> bool {
        self.owner.load(SeqCst)
    }

    #[inline]
    fn stop(&self) {
        self.stopped.store(true, Release);
    }

    #[inline]
    fn is_stopped(&self) -> bool {
        self.stopped.load(Acquire)
    }

    #[inline]
    fn data(&self) -> MutexGuard<T> {
        self.data.lock()
    }

    #[inline]
    fn set_waker(&self, idx: usize, waker: &Waker) {
        self.wakers[idx].register(waker);
    }

    #[inline]
    fn wake(&self, idx: usize) {
        self.wakers[idx].wake();
    }

    #[inline]
    fn set_combined(&self, combined: bool) {
        self.combined.store(combined, Release);
    }

    #[inline]
    fn turnover(&self, other: bool) {
        let me = !other;
        if let Ok(prev) = self.owner.compare_exchange(me, other, SeqCst, Relaxed) {
            debug_assert_eq!(prev, me);
            let idx = other as usize;
            self.wake(idx);
        }
    }
}

/// `ShuttleValue` is a guard for the object inside `Shuttle`, much like `MutexGuard' for `Mutex`.
pub struct ShuttleValue<'a, T: 'a> {
    data: MutexGuard<'a, T>,
}

impl<'a, T: 'a + fmt::Debug> fmt::Debug for ShuttleValue<'a, T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("ShuttleValue")
            .field("data", &self.data.deref())
            .finish()
    }
}

impl<'a, T: 'a> Deref for ShuttleValue<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        self.data.deref()
    }
}

impl<'a, T: 'a> DerefMut for ShuttleValue<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.data.deref_mut()
    }
}

impl<'a, T, U> PartialEq<U> for ShuttleValue<'a, T>
where
    T: PartialEq<U>,
{
    fn eq(&self, other: &U) -> bool {
        self.data.eq(other)
    }
}

/// `ShuttleWait` object is a `Future` that waits for `Shuttle` to arrive back. I.e. it completes
/// when the other side calls `send` on its object and the ownership turns to this object.
/// `ShuttleWait` is created when `Shuttle` is converted into `Future` (it implements `IntoFuture`)
/// and it consumes the `Shuttle` object.
/// When the future completes it yields the `Shuttle` object back.
#[must_use = "futures do nothing unless polled"]
#[derive(Debug)]
pub struct ShuttleWait<T> {
    shuttle: Option<Shuttle<T>>,
}

impl<T> IntoFuture for Shuttle<T> {
    type Future = ShuttleWait<T>;
    type Item = Self;
    type Error = ShuttleError;

    fn into_future(self) -> Self::Future {
        ShuttleWait {
            shuttle: Some(self),
        }
    }
}

impl<T> Future for ShuttleWait<T> {
    type Item = Shuttle<T>;
    type Error = ShuttleError;
    fn poll(&mut self, cx: &mut Context) -> Poll<Self::Item, Self::Error> {
        if let Some(shuttle) = self.shuttle.take() {
            // Save our context first
            shuttle.set_waker(cx.waker());

            // We are done if the shuttle is at our end of the track
            if shuttle.is_mine() {
                Ok(Async::Ready(shuttle))
            } else {
                // Otherwise stash shuttle object back into this future
                // and signal we are not ready yet
                self.shuttle = Some(shuttle);
                Ok(Async::Pending)
            }
        } else {
            Err(ShuttleError::Corrupted)
        }
    }
}

/// Creates a new shuttle synchronization object for sharing values between two asynchronous tasks.
///
///
/// Each half can be separately owned and sent across tasks.
///
/// # Examples
///
/// ```
/// extern crate futures;
/// extern crate futures_shuttle;
///
/// use futures_shuttle::shuttle;
/// use futures::*;
///
/// fn main() {
///     let (mut left, mut right) = shuttle(42);
///
///     assert!(left.is_mine());
///     assert!(!right.is_mine());
///     assert_eq!(left.data(), 42);
///     *left.data() = 84;
///     left.send();
///     assert!(!left.is_mine());
///     assert!(right.is_mine());
///     assert_eq!(right.data(), 84);
/// }
/// ```
pub fn shuttle<T>(item: T) -> (Shuttle<T>, Shuttle<T>) {
    Shuttle::pair(item)
}

pub fn shuttle_combined<T>(item: T) -> ShuttleCombined<T> {
    ShuttleCombined::new(item)
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn basic() {
        let (left, right) = shuttle(42);
        assert!(left.is_mine());
        assert!(!right.is_mine());
    }

    #[test]
    fn back_and_forth() {
        let (left, right) = shuttle(42);
        assert!(left.is_mine());
        assert!(!right.is_mine());

        *left.data() = 84;
        left.send();
        assert!(right.is_mine());
        assert!(!left.is_mine());
        assert_eq!(right.data(), 84);

        *right.data() = 123;
        right.send();
        assert!(left.is_mine());
        assert!(!right.is_mine());
        assert_eq!(left.data(), 123);
    }

    #[test]
    fn stopped() {
        let (left, right) = shuttle(42);
        assert!(left.is_mine());
        assert!(!right.is_mine());

        assert!(left.try_send().is_ok());

        assert!(right.is_mine());
        assert!(!left.is_mine());

        drop(left);
        assert_eq!(right.try_send(), Err(ShuttleError::Stopped));
    }
}