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
#![doc = "../README.md"]

#[doc(hidden)]
#[path = "exports.rs"]
pub mod __private;

use futures_core::Future;

use std::{
    ops::{Deref, DerefMut},
    pin::Pin,
    task::{Context, Poll, Waker},
};

/// Core trait
pub trait AsyncComponent: Unpin {
    fn poll_next_state(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()>;

    fn poll_next_stream(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()>;
}

impl<T: ?Sized + AsyncComponent> AsyncComponent for Box<T> {
    fn poll_next_state(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
        T::poll_next_state(Pin::new(&mut *self), cx)
    }

    fn poll_next_stream(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
        T::poll_next_stream(Pin::new(&mut *self), cx)
    }
}

impl<T: ?Sized + AsyncComponent> AsyncComponent for &mut T {
    fn poll_next_state(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
        T::poll_next_state(Pin::new(*self), cx)
    }

    fn poll_next_stream(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
        T::poll_next_stream(Pin::new(*self), cx)
    }
}

pub trait AsyncComponentExt {
    fn next(&mut self) -> Next<Self>;

    fn next_state(&mut self) -> NextState<Self>;

    fn next_stream(&mut self) -> NextStream<Self>;
}

#[derive(Debug)]
pub struct Next<'a, T: ?Sized>(&'a mut T);

impl<T: AsyncComponent> Future for Next<'_, T> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut result = Poll::Pending;

        if Pin::new(&mut *self.0).poll_next_stream(cx).is_ready() {
            result = Poll::Ready(());
        }

        if Pin::new(&mut *self.0).poll_next_state(cx).is_ready() {
            result = Poll::Ready(());
        }

        result
    }
}

impl<T: AsyncComponent> AsyncComponentExt for T {
    fn next(&mut self) -> Next<Self> {
        Next(self)
    }

    fn next_state(&mut self) -> NextState<Self> {
        NextState(self)
    }

    fn next_stream(&mut self) -> NextStream<Self> {
        NextStream(self)
    }
}

#[derive(Debug)]
pub struct NextState<'a, T: ?Sized>(&'a mut T);

impl<T: AsyncComponent> Future for NextState<'_, T> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut *self.0).poll_next_state(cx)
    }
}

#[derive(Debug)]
pub struct NextStream<'a, T: ?Sized>(&'a mut T);

impl<T: AsyncComponent> Future for NextStream<'_, T> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut *self.0).poll_next_stream(cx)
    }
}

pub type PhantomState = StateCell<()>;

/// Track change of value and notify the Executor.
/// This struct has no method and implements [`Deref`], [`DerefMut`].
/// When inner value is mutable dereferenced, it changes status and wake pending task.
/// This will also wake pending task when the cell is dropped.
#[derive(Debug)]
pub struct StateCell<T> {
    status: StateStatus,
    inner: T,
}

impl<T> StateCell<T> {
    /// Create new [`StateCell`]
    pub const fn new(inner: T) -> Self {
        Self {
            status: StateStatus::Changed,
            inner,
        }
    }

    /// Invalidate this [`StateCell`].
    /// It wakes task if there is any waker pending.
    pub fn invalidate(this: &mut Self) {
        match this.status {
            StateStatus::None => {
                this.status = StateStatus::Changed;
            }

            StateStatus::Pending(ref waker) => {
                waker.wake_by_ref();
                this.status = StateStatus::Changed;
            }

            StateStatus::Changed => {}
        }
    }

    /// Check if there are any changes or saves waker to wake task to notify when the value is changed.
    pub fn poll_state(mut this: Pin<&mut Self>, cx: &mut Context) -> Poll<()>
    where
        Self: Unpin,
    {
        match this.status {
            StateStatus::None => {
                this.status = StateStatus::Pending(cx.waker().clone());

                Poll::Pending
            }

            StateStatus::Pending(ref old_waker) => {
                if !old_waker.will_wake(cx.waker()) {
                    this.status = StateStatus::Pending(cx.waker().clone());
                }

                Poll::Pending
            }

            StateStatus::Changed => {
                this.status = StateStatus::None;
                Poll::Ready(())
            }
        }
    }
}

impl<T> Deref for StateCell<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T> DerefMut for StateCell<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        StateCell::invalidate(self);

        &mut self.inner
    }
}

impl<T> From<T> for StateCell<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T: Default> Default for StateCell<T> {
    fn default() -> Self {
        Self::new(Default::default())
    }
}

impl<T> Drop for StateCell<T> {
    fn drop(&mut self) {
        if let StateStatus::Pending(ref waker) = self.status {
            waker.wake_by_ref();
        }
    }
}

#[derive(Debug, Clone)]
enum StateStatus {
    None,
    Pending(Waker),
    Changed,
}

impl Default for StateStatus {
    fn default() -> Self {
        Self::None
    }
}