Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_core/tests/channels.rs

9.7 KiB, 11 runs

created by r1870400018:63085, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1use oxedyne_fe2o3_core::{
2 prelude::*,
3 channels::{
4 bounded,
5 oneshot,
6 simplex,
7 watch,
8 Recv,
9 Simplex,
10 },
11 test::test_it,
12};
13
14use std::{
15 future::Future,
16 pin::pin,
17 rc::Rc,
18 sync::{
19 atomic::{
20 AtomicBool,
21 AtomicUsize,
22 Ordering,
23 },
24 Arc,
25 },
26 task::{
27 Context,
28 Poll,
29 Wake,
30 Waker,
31 },
32 thread,
33 time::Duration,
34};
35
36pub fn test_channels(filter: &'static str) -> Outcome<()> {
37
38 res!(test_it(filter, &["Send only if open 000", "all", "channels"], || {
39 let chan: Simplex<u32> = simplex();
40 let other = chan.clone();
41 req!(true, res!(chan.send_if_open(1)), "(L: expected)");
42 req!(true, res!(other.send_if_open(2)), "(L: expected)");
43 // The flag is shared by every clone, and closing says it was open.
44 req!(true, res!(other.close()), "(L: expected)");
45 req!(false, res!(chan.is_open()), "(L: expected)");
46 req!(false, res!(chan.send_if_open(3)), "(L: expected)");
47 req!(false, res!(other.send_if_open(4)), "(L: expected)");
48 // What went in before the close is still there to be read, in order, and nothing else.
49 for want in [1, 2] {
50 match chan.try_recv() {
51 Recv::Result(Ok(got)) => req!(want, got),
52 found => return Err(err!(
53 "Expected the message {} to be waiting, found {:?}.", want, found;
54 Test, Mismatch)),
55 }
56 }
57 match chan.try_recv() {
58 Recv::Empty => (),
59 found => return Err(err!(
60 "Expected nothing after the close, found {:?}.", found;
61 Test, Mismatch)),
62 }
63 Ok(())
64 }));
65
66 // Why `send_if_open` is needed. A `Simplex` holds its receiving end, so `send` succeeds
67 // after every reader of the channel has gone, and the message waits for nobody.
68 res!(test_it(filter, &["Send cannot see a reader gone 000", "all", "channels"], || {
69 let chan: Simplex<u32> = simplex();
70 let writer = chan.clone();
71 drop(chan);
72 req!(true, writer.send(1).is_ok(), "(L: expected)");
73 req!(1, writer.len());
74 Ok(())
75 }));
76
77 res!(test_it(filter, &["No send passes a close 000", "all", "channels"], || {
78 for _ in 0..20 {
79 let chan: Simplex<u32> = simplex();
80 let go = Arc::new(AtomicBool::new(false));
81 let sent = Arc::new(AtomicUsize::new(0));
82 let mut hands = Vec::new();
83 for _ in 0..6 {
84 let (chan, go, sent) = (chan.clone(), go.clone(), sent.clone());
85 hands.push(thread::spawn(move || {
86 while !go.load(Ordering::Acquire) {
87 thread::yield_now();
88 }
89 for i in 0..20_000u32 {
90 match chan.send_if_open(i) {
91 Ok(true) => { sent.fetch_add(1, Ordering::Relaxed); },
92 _ => break,
93 }
94 }
95 }));
96 }
97 go.store(true, Ordering::Release);
98 thread::sleep(Duration::from_micros(300));
99 res!(chan.close());
100 // Every message that reported itself sent was in the queue by the time the close
101 // returned, so a reader that drains after closing has them all, and no more come.
102 let at_close = chan.len();
103 for hand in hands {
104 let joined = hand.join().is_ok();
105 req!(true, joined, "(L: expected)");
106 }
107 req!(at_close, chan.len());
108 req!(sent.load(Ordering::Relaxed), chan.len());
109 }
110 Ok(())
111 }));
112
113 Ok(())
114}
115
116/// Records that it was woken, so a test can poll by hand and see exactly when a future is ready.
117struct Flag(AtomicBool);
118
119impl Wake for Flag {
120 fn wake(self: Arc<Self>) { self.0.store(true, Ordering::SeqCst); }
121}
122
123fn flag() -> (Arc<Flag>, Waker) {
124 let f = Arc::new(Flag(AtomicBool::new(false)));
125 (f.clone(), Waker::from(f))
126}
127
128/// The smallest executor: park the thread until woken.
129struct Unpark(thread::Thread);
130
131impl Wake for Unpark {
132 fn wake(self: Arc<Self>) { self.0.unpark(); }
133}
134
135fn block_on<F: Future>(fut: F) -> F::Output {
136 let waker = Waker::from(Arc::new(Unpark(thread::current())));
137 let mut cx = Context::from_waker(&waker);
138 let mut fut = pin!(fut);
139 loop {
140 match fut.as_mut().poll(&mut cx) {
141 Poll::Ready(v) => return v,
142 Poll::Pending => thread::park(),
143 }
144 }
145}
146
147#[test]
148fn mailbox_full_makes_sender_wait() -> Outcome<()> {
149 let (tx, rx) = bounded::<usize>(64);
150 for i in 0..64 {
151 res!(tx.try_send(i));
152 }
153 let (woken, waker) = flag();
154 let mut cx = Context::from_waker(&waker);
155 let mut send = pin!(tx.send_async(64));
156 req!(send.as_mut().poll(&mut cx).is_pending(), true);
157 req!(tx.len(), 64);
158 req!(woken.0.load(Ordering::SeqCst), false);
159 // A second poll while still full stays pending: the mailbox never grows.
160 req!(send.as_mut().poll(&mut cx).is_pending(), true);
161 req!(tx.len(), 64);
162 req!(res!(rx.try_recv()), 0);
163 req!(woken.0.load(Ordering::SeqCst), true);
164 match send.as_mut().poll(&mut cx) {
165 Poll::Ready(r) => res!(r),
166 Poll::Pending => return Err(err!("65th send still pending after a slot was freed."; Test)),
167 }
168 req!(tx.len(), 64);
169 for i in 1..65 {
170 req!(res!(rx.try_recv()), i);
171 }
172 Ok(())
173}
174
175#[test]
176fn watch_late_reader_sees_latest() -> Outcome<()> {
177 let (tx, rx) = watch(0u32);
178 for i in 1..4 {
179 res!(tx.send(i));
180 }
181 req!(*res!(rx.borrow()), 3);
182 let late = tx.subscribe();
183 req!(*res!(late.borrow()), 3);
184 let cloned = late.clone();
185 req!(*res!(cloned.borrow()), 3);
186 Ok(())
187}
188
189#[test]
190fn watch_changed_wakes_on_send() -> Outcome<()> {
191 let (tx, mut rx) = watch(String::from("idle"));
192 {
193 let (woken, waker) = flag();
194 let mut cx = Context::from_waker(&waker);
195 let mut changed = pin!(rx.changed());
196 req!(changed.as_mut().poll(&mut cx).is_pending(), true);
197 res!(tx.send(String::from("stop")));
198 req!(woken.0.load(Ordering::SeqCst), true);
199 match changed.as_mut().poll(&mut cx) {
200 Poll::Ready(r) => res!(r),
201 Poll::Pending => return Err(err!("changed() still pending after send."; Test)),
202 }
203 }
204 req!(res!(rx.borrow()).as_str(), "stop");
205 // Seen: the next changed() waits again.
206 let (_woken, waker) = flag();
207 let mut cx = Context::from_waker(&waker);
208 req!(pin!(rx.changed()).poll(&mut cx).is_pending(), true);
209 // Across threads, with a parking executor.
210 let handle = thread::spawn(move || -> Outcome<()> {
211 res!(tx.send(String::from("again")));
212 Ok(())
213 });
214 res!(block_on(rx.changed()));
215 req!(res!(rx.borrow()).as_str(), "again");
216 match handle.join() {
217 Ok(r) => res!(r),
218 Err(_) => return Err(err!("Sender thread panicked."; Test)),
219 }
220 Ok(())
221}
222
223/// An abandoned wait (its task ended, or a select or timeout dropped it) must not leave its waker
224/// behind: a Stop cell that is rarely sent would otherwise grow without bound.
225#[test]
226fn watch_abandoned_waits_leave_no_waker() -> Outcome<()> {
227 let (tx, mut rx) = watch(0u8);
228 for _ in 0..16 {
229 let (_woken, waker) = flag();
230 let mut cx = Context::from_waker(&waker);
231 let mut changed = pin!(rx.changed());
232 req!(changed.as_mut().poll(&mut cx).is_pending(), true);
233 // A re-poll with another waker replaces, never adds.
234 let (_woken2, waker2) = flag();
235 let mut cx2 = Context::from_waker(&waker2);
236 req!(changed.as_mut().poll(&mut cx2).is_pending(), true);
237 req!(res!(tx.waiters()), 1);
238 }
239 req!(res!(tx.waiters()), 0);
240 Ok(())
241}
242
243#[test]
244fn watch_closes_when_sender_drops() -> Outcome<()> {
245 let (tx, mut rx) = watch(1u8);
246 let (woken, waker) = flag();
247 let mut cx = Context::from_waker(&waker);
248 {
249 let mut changed = pin!(rx.changed());
250 req!(changed.as_mut().poll(&mut cx).is_pending(), true);
251 res!(tx.send(2));
252 drop(tx);
253 req!(woken.0.load(Ordering::SeqCst), true);
254 // The last value sent before the drop is still delivered.
255 match changed.as_mut().poll(&mut cx) {
256 Poll::Ready(r) => res!(r),
257 Poll::Pending => return Err(err!("changed() pending after send."; Test)),
258 }
259 }
260 req!(*res!(rx.borrow()), 2);
261 req!(res!(rx.is_closed()), true);
262 req!(block_on(rx.changed()).is_err(), true);
263 Ok(())
264}
265
266/// The actor runs single-threaded (spawn_local on wasm, LocalSet natively), so a watch must carry a
267/// value that is not `Send`. This compiling and passing is why there is no separate non-`Send`
268/// variant.
269#[test]
270fn watch_carries_non_send_value() -> Outcome<()> {
271 let (tx, mut rx) = watch(Rc::new(0u8));
272 res!(tx.send(Rc::new(7)));
273 res!(block_on(rx.changed()));
274 req!(**res!(rx.borrow()), 7);
275 Ok(())
276}
277
278#[test]
279fn oneshot_delivers_value() -> Outcome<()> {
280 let (tx, rx) = oneshot::<u64>();
281 res!(tx.send(42));
282 let got = res!(block_on(rx.recv()));
283 req!(got, 42);
284 Ok(())
285}
286
287#[test]
288fn oneshot_dropped_sender_is_error() -> Outcome<()> {
289 let (tx, rx) = oneshot::<u64>();
290 drop(tx);
291 let got = block_on(rx.recv());
292 req!(got.is_err(), true);
293 Ok(())
294}
295
296#[test]
297fn oneshot_waits_for_sender_thread() -> Outcome<()> {
298 let (tx, rx) = oneshot::<&'static str>();
299 let handle = thread::spawn(move || tx.send("done"));
300 let got = res!(block_on(rx.recv()));
301 req!(got, "done");
302 match handle.join() {
303 Ok(r) => res!(r),
304 Err(_) => return Err(err!("Sender thread panicked."; Test)),
305 }
306 Ok(())
307}