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
use std::pin::Pin;
use crate::Context;
use atomic::{Atomic, Ordering};
use crate::stream::{PollRecv, Stream};
#[derive(Copy, Clone)]
enum State {
Reading,
Closed,
}
pub struct FindStream<From, Condition> {
state: Atomic<State>,
from: From,
condition: Condition,
}
impl<From, Condition> FindStream<From, Condition>
where
From: Stream,
Condition: Fn(&From::Item) -> bool,
{
pub fn new(from: From, condition: Condition) -> Self {
Self {
state: Atomic::new(State::Reading),
from,
condition,
}
}
}
impl<From, Condition> Stream for FindStream<From, Condition>
where
From: Stream + Unpin,
Condition: Fn(&From::Item) -> bool + Unpin,
{
type Item = From::Item;
fn poll_recv(self: Pin<&mut Self>, cx: &mut Context<'_>) -> PollRecv<Self::Item> {
let this = self.get_mut();
if let State::Closed = this.state.load(Ordering::Acquire) {
return PollRecv::Closed;
}
loop {
let from = Pin::new(&mut this.from);
match from.poll_recv(cx) {
PollRecv::Ready(value) => {
if (this.condition)(&value) {
this.state.store(State::Closed, Ordering::Release);
return PollRecv::Ready(value);
}
}
PollRecv::Pending => return PollRecv::Pending,
PollRecv::Closed => return PollRecv::Closed,
}
}
}
}
#[cfg(test)]
mod tests {
use std::pin::Pin;
use crate::test::stream::*;
use crate::{
stream::{PollRecv, Stream},
Context,
};
use super::FindStream;
#[test]
fn find() {
let source = from_iter(vec![1, 2, 3]);
let mut find = FindStream::new(source, |i| *i == 2);
let mut cx = Context::empty();
assert_eq!(PollRecv::Ready(2), Pin::new(&mut find).poll_recv(&mut cx));
assert_eq!(PollRecv::Closed, Pin::new(&mut find).poll_recv(&mut cx));
}
#[test]
fn find_none() {
let source = from_iter(vec![1, 3]);
let mut find = FindStream::new(source, |i| *i == 2);
let mut cx = Context::empty();
assert_eq!(PollRecv::Closed, Pin::new(&mut find).poll_recv(&mut cx));
}
#[test]
fn find_only_once() {
let source = from_iter(vec![1, 2, 2]);
let mut find = FindStream::new(source, |i| *i == 2);
let mut cx = Context::empty();
assert_eq!(PollRecv::Ready(2), Pin::new(&mut find).poll_recv(&mut cx));
assert_eq!(PollRecv::Closed, Pin::new(&mut find).poll_recv(&mut cx));
}
#[test]
fn forward_pending() {
let source = pending::<usize>();
let mut find = FindStream::new(source, |i| *i == 2);
let mut cx = Context::empty();
assert_eq!(PollRecv::Pending, Pin::new(&mut find).poll_recv(&mut cx));
}
#[test]
fn forward_closed() {
let source = closed::<usize>();
let mut find = FindStream::new(source, |i| *i == 2);
let mut cx = Context::empty();
assert_eq!(PollRecv::Closed, Pin::new(&mut find).poll_recv(&mut cx));
}
}