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
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};
pub fn until_true<F: FnMut() -> bool + Unpin>(f: F) -> impl Future<Output = ()> {
UntilTrue(f)
}
struct UntilTrue<F: FnMut() -> bool>(F);
impl<F: FnMut() -> bool + Unpin> Future for UntilTrue<F> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.0() {
Poll::Ready(())
} else {
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
pub fn until_some<T, F: FnMut() -> Option<T> + Unpin>(f: F) -> impl Future<Output = T> {
UntilSome(f)
}
struct UntilSome<T, F: FnMut() -> Option<T>>(F);
impl<T, F: FnMut() -> Option<T> + Unpin> Future for UntilSome<T, F> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(output) = self.0() {
Poll::Ready(output)
} else {
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[cfg(test)]
mod tests {
use crate::{until_some, until_true};
use futures_lite::future::block_on;
#[test]
fn until_true_once() {
block_on(until_true(|| true))
}
#[test]
fn until_true_twice() {
let mut first_time = true;
block_on(until_true(|| {
if first_time {
first_time = false;
false
} else {
true
}
}))
}
#[test]
fn until_some_once() {
assert_eq!((), block_on(until_some(|| Some(()))));
}
#[test]
fn until_some_twice() {
let mut first_time = true;
let resolved = block_on(until_some(|| {
if first_time {
first_time = false;
None
} else {
Some(())
}
}));
assert_eq!((), resolved);
}
}