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
/// Eventual is like Dart's "Completer"
/// It is a thread-safe concurrent data future that may eventually resolve to a value
/// Three variants exist
/// Eventual, which will complete each 'instance' future to that instance's value (can be different per instance) only when 'resolve' is called.
/// EventualValue, which will complete each 'instance' future when 'resolve' is called with an owned value, and one of those instances may 'take' the value.
/// EventualValueClone, which will complete each 'instance' future when 'resolve' is called with a Clone-able value, and any of those instances may get a clone of that value.
/// The future returned from an Eventual::resolve() can also be awaited on to wait until all instances have been completed
use super::*;

use eventual_base::*;

pub struct Eventual {
    inner: Arc<Mutex<EventualBaseInner<()>>>,
}

impl core::fmt::Debug for Eventual {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Eventual").finish()
    }
}

impl Clone for Eventual {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl EventualBase for Eventual {
    type ResolvedType = ();
    fn base_inner(&self) -> MutexGuard<EventualBaseInner<Self::ResolvedType>> {
        self.inner.lock()
    }
}

impl Default for Eventual {
    fn default() -> Self {
        Self::new()
    }
}

impl Eventual {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(EventualBaseInner::new())),
        }
    }

    pub fn instance_clone<T>(&self, value: T) -> EventualFutureClone<T>
    where
        T: Clone + Unpin,
    {
        EventualFutureClone {
            id: None,
            value,
            eventual: self.clone(),
        }
    }
    pub fn instance_none<T>(&self) -> EventualFutureNone<T>
    where
        T: Unpin,
    {
        EventualFutureNone {
            id: None,
            eventual: self.clone(),
            _marker: core::marker::PhantomData {},
        }
    }
    pub fn instance_empty(&self) -> EventualFutureEmpty {
        EventualFutureEmpty {
            id: None,
            eventual: self.clone(),
        }
    }

    pub fn resolve(&self) -> EventualResolvedFuture<Self> {
        self.resolve_to_value(())
    }
}

///////

pub struct EventualFutureClone<T>
where
    T: Clone + Unpin,
{
    id: Option<usize>,
    value: T,
    eventual: Eventual,
}

impl<T> Future for EventualFutureClone<T>
where
    T: Clone + Unpin,
{
    type Output = T;
    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
        let this = &mut *self;
        let out = {
            let mut inner = this.eventual.base_inner();
            inner.instance_poll(&mut this.id, cx)
        };
        match out {
            None => task::Poll::<Self::Output>::Pending,
            Some(wakers) => {
                // Wake all EventualResolvedFutures
                for w in wakers {
                    w.wake();
                }
                task::Poll::<Self::Output>::Ready(this.value.clone())
            }
        }
    }
}

impl<T> Drop for EventualFutureClone<T>
where
    T: Clone + Unpin,
{
    fn drop(&mut self) {
        if let Some(id) = self.id.take() {
            let wakers = {
                let mut inner = self.eventual.base_inner();
                inner.remove_waker(id)
            };
            for w in wakers {
                w.wake();
            }
        }
    }
}

///////

pub struct EventualFutureNone<T>
where
    T: Unpin,
{
    id: Option<usize>,
    eventual: Eventual,
    _marker: core::marker::PhantomData<T>,
}

impl<T> Future for EventualFutureNone<T>
where
    T: Unpin,
{
    type Output = Option<T>;
    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
        let this = &mut *self;
        let out = {
            let mut inner = this.eventual.base_inner();
            inner.instance_poll(&mut this.id, cx)
        };
        match out {
            None => task::Poll::<Self::Output>::Pending,
            Some(wakers) => {
                // Wake all EventualResolvedFutures
                for w in wakers {
                    w.wake();
                }
                task::Poll::<Self::Output>::Ready(None)
            }
        }
    }
}

impl<T> Drop for EventualFutureNone<T>
where
    T: Unpin,
{
    fn drop(&mut self) {
        if let Some(id) = self.id.take() {
            let wakers = {
                let mut inner = self.eventual.base_inner();
                inner.remove_waker(id)
            };
            for w in wakers {
                w.wake();
            }
        }
    }
}

///////

pub struct EventualFutureEmpty {
    id: Option<usize>,
    eventual: Eventual,
}

impl Future for EventualFutureEmpty {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
        let this = &mut *self;
        let out = {
            let mut inner = this.eventual.base_inner();
            inner.instance_poll(&mut this.id, cx)
        };
        match out {
            None => task::Poll::<Self::Output>::Pending,
            Some(wakers) => {
                // Wake all EventualResolvedFutures
                for w in wakers {
                    w.wake();
                }
                task::Poll::<Self::Output>::Ready(())
            }
        }
    }
}

impl Drop for EventualFutureEmpty {
    fn drop(&mut self) {
        if let Some(id) = self.id.take() {
            let wakers = {
                let mut inner = self.eventual.base_inner();
                inner.remove_waker(id)
            };
            for w in wakers {
                w.wake();
            }
        }
    }
}