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
use std::{time::Duration, pin::Pin, task::{Poll, Context}};
use futures::{prelude::*, channel::mpsc, stream::unfold};
use futures_timer::Delay;

/// Something that can produce stream of events.
pub trait IntoStream {
    type Guard;
    fn into_stream(self) -> Box<dyn Stream<Item=Self::Guard> + Unpin + Send>;
}

/// Interval that produces stream of `()` events.
pub struct Interval {
    value: Duration,
}

impl Interval {
    /// New interval.
    pub fn new(duration: Duration) -> Interval {
        Interval { value: duration }
    }
}

impl IntoStream for Interval {
    type Guard = ();

    fn into_stream(self) -> Box<dyn Stream<Item=()> + Unpin + Send> {
        let value = self.value;
        Box::new(
            unfold((), move |_| {
                Delay::new(value).map(|_| Some(((), ())))
            }).map(drop)
        )
    }
}

/// Guard for interval event
///
/// This guard detects when it is dropped and notifies the party
/// that cretated `BackSignalInterval`.
pub struct BackSignalGuard {
    sender: Option<mpsc::UnboundedSender<()>>,
}

impl Drop for BackSignalGuard {
    fn drop(&mut self) {
        let _ = self.sender.take()
            .expect("Drop cannot be called twice, and BackSignalGuard never created without sender")
            .unbounded_send(());
    }
}

/// Interval that produces stream of "guarded" events.
///
/// Each time when such guarded event handled (dropped), event for the
/// receiver is generated.
pub struct BackSignalInterval {
    value: Duration,
    sender: mpsc::UnboundedSender<()>,
}

impl IntoStream for BackSignalInterval {
    type Guard = BackSignalGuard;

    fn into_stream(self) -> Box<dyn Stream<Item=BackSignalGuard> + Unpin + Send> {
        let value = self.value;
        let sender = self.sender;
        Box::new(
            unfold(sender, move |sender| {
                Delay::new(value).map(|_| {
                    let back_signal_guard = BackSignalGuard { sender: Some(sender.clone()) };
                    Some((back_signal_guard, sender))
                })
            })
        )
    }
}

impl BackSignalInterval {
    /// New interval with hanldling notification.
    pub fn new(duration: Duration) -> (Self, mpsc::UnboundedReceiver<()>) {
        let (sender, receiver) = mpsc::unbounded();
        let back_signal = BackSignalInterval {
            value: duration,
            sender: sender,
        };
        (back_signal, receiver)
    }
}

pub struct ManualSignalInterval {
    event_receiver: mpsc::UnboundedReceiver<()>,
    handle_sender: mpsc::UnboundedSender<()>,
}

pub struct ManualIntervalControl {
    handle_receiver: mpsc::UnboundedReceiver<()>,
    event_sender: mpsc::UnboundedSender<()>,
}

impl ManualIntervalControl {
    pub fn next<'a>(&'a mut self) -> Pin<Box<dyn Future<Output=Option<()>> + 'a>> {
        if let Err(_) = self.event_sender.unbounded_send(()) {
            return futures::future::ready(None).boxed()
        }
        self.handle_receiver.next().boxed()
    }
}

impl ManualSignalInterval {
    /// New manual interval.
    ///
    /// Use
    pub fn new() -> (Self, ManualIntervalControl) {
        let (event_sender, event_receiver) = mpsc::unbounded();
        let (handle_sender, handle_receiver) = mpsc::unbounded();
        let back_signal = ManualSignalInterval {
            event_receiver, handle_sender,
        };
        let control = ManualIntervalControl {
            event_sender, handle_receiver,
        };
        (back_signal, control)
    }
}

impl Stream for ManualSignalInterval {
    type Item = BackSignalGuard;
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = Pin::into_inner(self);
        match Pin::new(&mut this.event_receiver).poll_next(cx) {
            Poll::Ready(Some(_)) => {
                let guard = BackSignalGuard { sender: Some(this.handle_sender.clone()) };
                Poll::Ready(Some(guard))
            },
            Poll::Ready(None) => Poll::Ready(None),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl IntoStream for ManualSignalInterval {
    type Guard = BackSignalGuard;

    fn into_stream(self) -> Box<dyn Stream<Item=Self::Guard> + Unpin + Send> {
        Box::new(self)
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use futures::channel::oneshot;
    use std::sync::{Arc, atomic::{AtomicBool, Ordering as AtomicOrdering}};

    async fn run_test<R: IntoStream>(rythm: R, exit: oneshot::Receiver<()>, change_this: Arc<AtomicBool>) {
        let interval = rythm.into_stream().fuse();
        let exit = exit.fuse();
        futures::pin_mut!(interval, exit);
        loop {
            futures::select! {
                _ = interval.next() => {
                    change_this.store(true, AtomicOrdering::SeqCst);
                },
                _ = exit => {
                    break;
                }
            }
        }
    }

    #[test]
    fn test_back_signal() {
        let (rythm, mut rythm_receiver) = BackSignalInterval::new(std::time::Duration::from_millis(100));
        let change_this = Arc::new(AtomicBool::new(false));
        let (exit_sender, exit_receiver) = oneshot::channel();
        let background_thread = futures::executor::ThreadPool::new().unwrap();
        background_thread.spawn_ok(run_test(rythm, exit_receiver, change_this.clone()));

        futures::executor::block_on(async move {
            rythm_receiver.next().await;
            assert_eq!(change_this.load(AtomicOrdering::SeqCst), true);
            let _ = exit_sender.send(());
        });
    }

    #[test]
    fn test_manual_interval() {
        let (rythm, mut control) = ManualSignalInterval::new();
        let change_this = Arc::new(AtomicBool::new(false));
        let (_, exit_receiver) = oneshot::channel();
        let background_thread = futures::executor::ThreadPool::new().unwrap();
        background_thread.spawn_ok(run_test(rythm, exit_receiver, change_this.clone()));

        futures::executor::block_on(control.next());

        assert_eq!(change_this.load(AtomicOrdering::SeqCst), true);
    }
}