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
use std::fmt::Debug;
use std::future::Future;
use std::hash::Hash;
use std::marker::Unpin;
use std::pin::Pin;
use std::sync::atomic::Ordering;
use std::task::{Context, Poll};

use futures::Sink;

use super::{LocalTaskExecQueue, LocalTaskType, TaskExecQueue, TaskType};

pub struct Flush<'a, Tx, G, D> {
    sink: &'a TaskExecQueue<Tx, G, D>,
}

impl<'a, Tx, G, D> Unpin for Flush<'a, Tx, G, D> {}

impl<'a, Tx, G, D> Flush<'a, Tx, G, D> {
    pub(crate) fn new(sink: &'a TaskExecQueue<Tx, G, D>) -> Self {
        Self { sink }
    }
}

impl<'a, Tx, G, D> Future for Flush<'a, Tx, G, D>
where
    Tx: Clone + Sink<(D, TaskType)> + Unpin + Send + Sync + 'static,
    G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    type Output = Result<(), Tx::Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        futures::ready!(Pin::new(&mut this.sink.tx.clone()).poll_flush(cx))?;
        if this.sink.is_active() {
            this.sink.flush_waker.register(cx.waker());
            Poll::Pending
        } else {
            this.sink.is_flushing.store(false, Ordering::SeqCst);
            Poll::Ready(Ok(()))
        }
    }
}

pub struct LocalFlush<'a, Tx, G, D> {
    sink: &'a LocalTaskExecQueue<Tx, G, D>,
}

impl<'a, Tx, G, D> Unpin for LocalFlush<'a, Tx, G, D> {}

impl<'a, Tx, G, D> LocalFlush<'a, Tx, G, D> {
    pub(crate) fn new(sink: &'a LocalTaskExecQueue<Tx, G, D>) -> Self {
        Self { sink }
    }
}

impl<'a, Tx, G, D> Future for LocalFlush<'a, Tx, G, D>
where
    Tx: Clone + Sink<(D, LocalTaskType)> + Unpin + 'static,
    G: Hash + Eq + Clone + Debug + 'static,
{
    type Output = Result<(), Tx::Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        futures::ready!(Pin::new(&mut this.sink.tx.clone()).poll_flush(cx))?;
        if this.sink.is_active() {
            this.sink.flush_waker.register(cx.waker());
            Poll::Pending
        } else {
            this.sink.is_flushing.store(false, Ordering::SeqCst);
            Poll::Ready(Ok(()))
        }
    }
}