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

use futures::Sink;
use futures::task::AtomicWaker;

use super::{Counter, LocalTaskType, TaskType};

pub struct Flush<Tx, D> {
    sink: Tx,
    waiting_count: Counter,
    active_count: Counter,
    is_flushing: Arc<AtomicBool>,
    w: Arc<AtomicWaker>,
    _d: std::marker::PhantomData<D>,
}

impl<Tx, D> Unpin for Flush<Tx, D> {}

impl<Tx, D> Flush<Tx, D> {
    pub(crate) fn new(
        sink: Tx,
        waiting_count: Counter,
        active_count: Counter,
        is_flushing: Arc<AtomicBool>,
        w: Arc<AtomicWaker>,
    ) -> Self {
        Self {
            sink,
            waiting_count,
            active_count,
            is_flushing,
            w,
            _d: std::marker::PhantomData,
        }
    }
}

impl<Tx, D> Future for Flush<Tx, D>
    where
        Tx: Sink<(D, TaskType)> + Unpin,
{
    type Output = Result<(), Tx::Error>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        futures::ready!(Pin::new(&mut self.sink).poll_flush(cx))?;
        if self.waiting_count.value() > 0 || self.active_count.value() > 0 {
            self.w.register(cx.waker());
            Poll::Pending
        } else {
            self.is_flushing.store(false, Ordering::SeqCst);
            Poll::Ready(Ok(()))
        }
    }
}

pub struct LocalFlush<Tx, D> {
    sink: Tx,
    waiting_count: Counter,
    active_count: Counter,
    is_flushing: Arc<AtomicBool>,
    w: Arc<AtomicWaker>,
    _d: std::marker::PhantomData<D>,
}

impl<Tx, D> Unpin for LocalFlush<Tx, D> {}

impl<Tx, D> LocalFlush<Tx, D> {
    pub(crate) fn new(
        sink: Tx,
        waiting_count: Counter,
        active_count: Counter,
        is_flushing: Arc<AtomicBool>,
        w: Arc<AtomicWaker>,
    ) -> Self {
        Self {
            sink,
            waiting_count,
            active_count,
            is_flushing,
            w,
            _d: std::marker::PhantomData,
        }
    }
}

impl<Tx, D> Future for LocalFlush<Tx, D>
    where
        Tx: Sink<(D, LocalTaskType)> + Unpin,
{
    type Output = Result<(), Tx::Error>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        futures::ready!(Pin::new(&mut self.sink).poll_flush(cx))?;
        if self.waiting_count.value() > 0 || self.active_count.value() > 0 {
            self.w.register(cx.waker());
            Poll::Pending
        } else {
            self.is_flushing.store(false, Ordering::SeqCst);
            Poll::Ready(Ok(()))
        }
    }
}