1use std::{cell, fmt, future::Future, future::poll_fn, pin::Pin, task::Context, task::Poll};
2
3use slab::Slab;
4
5use super::cell::Cell;
6use crate::task::LocalWaker;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum ConditionResult<T> {
11 Value(T),
13 Locked,
15 Dropped,
17}
18
19#[derive(Copy, Clone, PartialEq, Eq, Debug)]
20enum State {
21 Normal,
22 Locked,
23 Dropped,
24}
25
26pub struct Condition<T = ()> {
33 inner: Cell<Inner<T>>,
34}
35
36pub struct Waiter<T = ()> {
38 token: usize,
39 inner: Cell<Inner<T>>,
40}
41
42struct Inner<T> {
43 data: Slab<Option<Item<T>>>,
44 count: usize,
45 state: State,
46}
47
48struct Item<T> {
49 val: cell::Cell<ConditionResult<T>>,
50 waker: LocalWaker,
51}
52
53fn deliver<T>(inner: &Cell<Inner<T>>, mut make: impl FnMut() -> ConditionResult<T>) {
59 let end = inner.get_ref().data.capacity();
60 for key in 0..end {
61 let registered = matches!(
62 inner.get_ref().data.get(key),
63 Some(Some(item)) if item.waker.is_set()
64 );
65 if !registered {
66 continue;
67 }
68
69 let val = make();
70 let delivered = match inner.get_ref().data.get(key) {
71 Some(Some(item)) => match item.waker.take_local() {
72 Some(waker) => Ok((waker, item.val.replace(val))),
73 None => Err(val),
74 },
75 _ => Err(val),
76 };
77 if let Ok((waker, prev)) = delivered {
78 drop(prev);
79 waker.wake();
80 }
81 }
82}
83
84impl Default for Condition<()> {
85 fn default() -> Self {
86 Self::new()
87 }
88}
89
90impl<T> Clone for Condition<T> {
91 fn clone(&self) -> Self {
92 let inner = self.inner.clone();
93 inner.get_mut().count += 1;
94 Self { inner }
95 }
96}
97
98impl<T> fmt::Debug for Condition<T> {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 let state = self.inner.get_ref().state;
102 f.debug_struct("Condition").field("state", &state).finish()
103 }
104}
105
106impl<T> Condition<T> {
107 pub fn new() -> Condition<T> {
109 Condition {
110 inner: Cell::new(Inner {
111 data: Slab::new(),
112 count: 1,
113 state: State::Normal,
114 }),
115 }
116 }
117}
118
119impl<T: Clone> Condition<T> {
120 pub fn wait(&self) -> Waiter<T> {
125 let token = self.inner.get_mut().data.insert(None);
126 Waiter {
127 token,
128 inner: self.inner.clone(),
129 }
130 }
131
132 pub fn notify(&self, val: T) {
137 if self.inner.get_ref().state == State::Normal {
138 deliver(&self.inner, || ConditionResult::Value(val.clone()));
139 }
140 }
141
142 pub fn notify_and_lock(&self, val: T) {
148 self.notify(val);
149 self.inner.get_mut().state = State::Locked;
150 }
151}
152
153impl<T: Default> Condition<T> {
154 pub fn notify_default(&self) {
156 if self.inner.get_ref().state == State::Normal {
157 deliver(&self.inner, || ConditionResult::Value(T::default()));
158 }
159 }
160}
161
162impl<T> Drop for Condition<T> {
163 fn drop(&mut self) {
164 let dropped = {
165 let inner = self.inner.get_mut();
166 inner.count -= 1;
167 if inner.count == 0 {
168 inner.state = State::Dropped;
169 }
170 inner.count == 0
171 };
172 if dropped {
173 deliver(&self.inner, || ConditionResult::Dropped);
174 }
175 }
176}
177
178impl<T> Waiter<T> {
179 pub async fn ready(&self) -> ConditionResult<T> {
181 poll_fn(|cx| self.poll_ready(cx)).await
182 }
183
184 pub fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<ConditionResult<T>> {
189 let new = {
190 let parent = self.inner.get_mut();
191 let slot = &mut parent.data[self.token];
192 if slot.is_none() {
193 if parent.state != State::Normal {
194 return self.poll_state();
195 }
196 *slot = Some(Item {
197 waker: LocalWaker::default(),
198 val: cell::Cell::new(ConditionResult::Locked),
199 });
200 true
201 } else {
202 false
203 }
204 };
205
206 let registered = LocalWaker::register_in(|| &self.item().waker, cx.waker());
209
210 if new || registered {
212 self.poll_state()
213 } else {
214 Poll::Ready(self.item().val.replace(ConditionResult::Locked))
215 }
216 }
217
218 fn item(&self) -> &Item<T> {
219 self.inner.get_ref().data[self.token].as_ref().unwrap()
221 }
222
223 fn poll_state(&self) -> Poll<ConditionResult<T>> {
224 match self.inner.get_ref().state {
225 State::Normal => Poll::Pending,
226 State::Locked => Poll::Ready(ConditionResult::Locked),
227 State::Dropped => Poll::Ready(ConditionResult::Dropped),
228 }
229 }
230}
231
232impl<T> Clone for Waiter<T> {
233 fn clone(&self) -> Self {
234 let token = self.inner.get_mut().data.insert(None);
235 Waiter {
236 token,
237 inner: self.inner.clone(),
238 }
239 }
240}
241
242impl<T> Future for Waiter<T> {
243 type Output = ConditionResult<T>;
244
245 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
246 self.get_mut().poll_ready(cx)
247 }
248}
249
250impl<T> fmt::Debug for Waiter<T> {
251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252 f.debug_struct("Waiter").finish()
253 }
254}
255
256impl<T> Drop for Waiter<T> {
257 fn drop(&mut self) {
258 let item = self.inner.get_mut().data.remove(self.token);
259 drop(item);
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266 use crate::future::lazy;
267 use crate::task::hooks::{ON_CLONE, ON_WAKE, hook_waker};
268
269 #[ntex::test]
275 #[allow(clippy::unit_cmp)]
276 async fn test_condition() {
277 let cond = Condition::<()>::new();
278 let mut waiter = cond.wait();
279 assert_eq!(
280 lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
281 Poll::Pending
282 );
283 cond.notify_default();
284 assert!(format!("{cond:?}").contains("Condition"));
285 assert!(format!("{waiter:?}").contains("Waiter"));
286 assert_eq!(waiter.await, ConditionResult::Value(()));
287
288 let mut waiter = cond.wait();
289 assert_eq!(
290 lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
291 Poll::Pending
292 );
293 let mut waiter2 = waiter.clone();
294 assert_eq!(
295 lazy(|cx| Pin::new(&mut waiter2).poll(cx)).await,
296 Poll::Pending
297 );
298
299 drop(cond);
300 assert_eq!(waiter.await, ConditionResult::Dropped);
301 assert_eq!(waiter2.await, ConditionResult::Dropped);
302 }
303
304 #[ntex::test]
310 async fn test_condition_poll() {
311 let cond = Condition::default().clone();
312 let waiter = cond.wait();
313 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
314 cond.notify_default();
315 waiter.ready().await;
316
317 let waiter2 = waiter.clone();
318 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
319 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
320 assert_eq!(lazy(|cx| waiter2.poll_ready(cx)).await, Poll::Pending);
321 assert_eq!(lazy(|cx| waiter2.poll_ready(cx)).await, Poll::Pending);
322
323 drop(cond);
324 assert_eq!(
325 lazy(|cx| waiter.poll_ready(cx)).await,
326 Poll::Ready(ConditionResult::Dropped)
327 );
328 assert_eq!(
329 lazy(|cx| waiter.poll_ready(cx)).await,
330 Poll::Ready(ConditionResult::Dropped)
331 );
332 assert_eq!(
333 lazy(|cx| waiter2.poll_ready(cx)).await,
334 Poll::Ready(ConditionResult::Dropped)
335 );
336 assert_eq!(
337 lazy(|cx| waiter2.poll_ready(cx)).await,
338 Poll::Ready(ConditionResult::Dropped)
339 );
340 }
341
342 #[ntex::test]
348 async fn test_condition_with() {
349 let cond = Condition::<String>::new();
350 let waiter = cond.wait();
351 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
352 cond.notify("TEST".into());
353 assert_eq!(
354 waiter.ready().await,
355 ConditionResult::Value("TEST".to_string())
356 );
357
358 let waiter2 = waiter.clone();
359 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
360 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
361 assert_eq!(lazy(|cx| waiter2.poll_ready(cx)).await, Poll::Pending);
362 assert_eq!(lazy(|cx| waiter2.poll_ready(cx)).await, Poll::Pending);
363
364 drop(cond);
365 assert_eq!(
366 lazy(|cx| waiter.poll_ready(cx)).await,
367 Poll::Ready(ConditionResult::Dropped)
368 );
369 assert_eq!(
370 lazy(|cx| waiter.poll_ready(cx)).await,
371 Poll::Ready(ConditionResult::Dropped)
372 );
373 assert_eq!(
374 lazy(|cx| waiter2.poll_ready(cx)).await,
375 Poll::Ready(ConditionResult::Dropped)
376 );
377 assert_eq!(
378 lazy(|cx| waiter2.poll_ready(cx)).await,
379 Poll::Ready(ConditionResult::Dropped)
380 );
381 }
382
383 #[ntex::test]
389 async fn waiter_future_does_not_require_default() {
390 #[derive(Clone, Debug, PartialEq, Eq)]
391 struct Value(&'static str);
392
393 let cond = Condition::<Value>::new();
394 let waiter = cond.wait();
395 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
396
397 cond.notify(Value("ready"));
398 assert_eq!(waiter.await, ConditionResult::Value(Value("ready")));
399 }
400
401 #[ntex::test]
407 async fn notify_ready() {
408 let cond = Condition::default().clone();
409 let waiter = cond.wait();
410 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
411
412 cond.notify_and_lock(());
413 assert_eq!(
414 lazy(|cx| waiter.poll_ready(cx)).await,
415 Poll::Ready(ConditionResult::Value(()))
416 );
417 assert_eq!(
418 lazy(|cx| waiter.poll_ready(cx)).await,
419 Poll::Ready(ConditionResult::Locked)
420 );
421 assert_eq!(
422 lazy(|cx| waiter.poll_ready(cx)).await,
423 Poll::Ready(ConditionResult::Locked)
424 );
425 cond.notify(());
426 assert_eq!(
427 lazy(|cx| waiter.poll_ready(cx)).await,
428 Poll::Ready(ConditionResult::Locked)
429 );
430
431 let waiter2 = cond.wait();
432 assert_eq!(
433 lazy(|cx| waiter2.poll_ready(cx)).await,
434 Poll::Ready(ConditionResult::Locked)
435 );
436 }
437
438 #[ntex::test]
444 async fn notify_with_and_lock_ready() {
445 let cond = Condition::<String>::new();
447 let waiter = cond.wait();
448 let waiter2 = cond.wait();
449 assert_eq!(lazy(|cx| waiter.poll_ready(cx)).await, Poll::Pending);
450 assert_eq!(lazy(|cx| waiter2.poll_ready(cx)).await, Poll::Pending);
451
452 cond.notify_and_lock("TEST".into());
453 assert_eq!(
454 lazy(|cx| waiter.poll_ready(cx)).await,
455 Poll::Ready(ConditionResult::Value("TEST".into()))
456 );
457 assert_eq!(
458 lazy(|cx| waiter.poll_ready(cx)).await,
459 Poll::Ready(ConditionResult::Locked)
460 );
461 assert_eq!(
462 lazy(|cx| waiter.poll_ready(cx)).await,
463 Poll::Ready(ConditionResult::Locked)
464 );
465 assert_eq!(
466 lazy(|cx| waiter2.poll_ready(cx)).await,
467 Poll::Ready(ConditionResult::Value("TEST".into()))
468 );
469 assert_eq!(
470 lazy(|cx| waiter2.poll_ready(cx)).await,
471 Poll::Ready(ConditionResult::Locked)
472 );
473
474 let waiter2 = cond.wait();
475 assert_eq!(
476 lazy(|cx| waiter2.poll_ready(cx)).await,
477 Poll::Ready(ConditionResult::Locked)
478 );
479 }
480
481 #[ntex::test]
487 async fn notify_default_locked() {
488 let cond = Condition::<()>::new();
489 cond.notify_and_lock(());
490 let mut waiter = cond.wait();
491 cond.notify_default();
492 assert_eq!(
493 lazy(|cx| Pin::new(&mut waiter).poll(cx)).await,
494 Poll::Ready(ConditionResult::Locked)
495 );
496 }
497
498 #[test]
507 fn miri_waiters_follow_notify_lock_and_drop() {
508 let mut cx = Context::from_waker(std::task::Waker::noop());
509 let cond = Condition::<String>::new();
510 let w1 = cond.wait();
511 let w2 = w1.clone();
512 assert!(w1.poll_ready(&mut cx).is_pending());
513 assert!(w2.poll_ready(&mut cx).is_pending());
514
515 cond.notify("1".to_string());
516 let one = Poll::Ready(ConditionResult::Value("1".to_string()));
517 assert_eq!(w1.poll_ready(&mut cx), one);
518 assert_eq!(w2.poll_ready(&mut cx), one);
519 assert!(w1.poll_ready(&mut cx).is_pending());
520
521 let cond2 = cond.clone();
522 cond2.notify_and_lock("2".to_string());
523 assert!(format!("{cond2:?}").contains("Locked"));
524 let two = Poll::Ready(ConditionResult::Value("2".to_string()));
525 assert_eq!(w1.poll_ready(&mut cx), two);
526 assert_eq!(w1.poll_ready(&mut cx), Poll::Ready(ConditionResult::Locked));
527 drop(w1);
528
529 let w3 = cond.wait();
530 assert_eq!(w3.poll_ready(&mut cx), Poll::Ready(ConditionResult::Locked));
531
532 assert_eq!(w2.poll_ready(&mut cx), two);
533 drop(cond);
534 drop(cond2);
535 assert_eq!(
536 w2.poll_ready(&mut cx),
537 Poll::Ready(ConditionResult::Dropped)
538 );
539 }
540
541 #[test]
547 fn miri_notify_with_reentrant_wake() {
548 let cond = Condition::<usize>::new();
549 let waiter = cond.wait();
550 let waker = hook_waker();
551 let mut cx = Context::from_waker(&waker);
552 assert!(waiter.poll_ready(&mut cx).is_pending());
553
554 let extra = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
555 let (c, e) = (cond.clone(), extra.clone());
556 ON_WAKE.set(Some(Box::new(move || {
557 e.borrow_mut().extend((0..64).map(|_| c.wait()));
558 })));
559 cond.notify(1);
560
561 assert_eq!(extra.borrow().len(), 64);
562 assert_eq!(
563 waiter.poll_ready(&mut cx),
564 Poll::Ready(ConditionResult::Value(1))
565 );
566 }
567
568 #[test]
574 fn miri_first_poll_with_reentrant_clone() {
575 let cond = Condition::<usize>::new();
576 let waiter = cond.wait();
577 let waker = hook_waker();
578 let mut cx = Context::from_waker(&waker);
579
580 let extra = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
581 let (c, e) = (cond.clone(), extra.clone());
582 ON_CLONE.set(Some(Box::new(move || {
583 e.borrow_mut().extend((0..64).map(|_| c.wait()));
584 })));
585 assert!(waiter.poll_ready(&mut cx).is_pending());
586 assert_eq!(extra.borrow().len(), 64);
587
588 cond.notify(1);
589 assert_eq!(
590 waiter.poll_ready(&mut cx),
591 Poll::Ready(ConditionResult::Value(1))
592 );
593 }
594
595 #[test]
601 fn miri_debug_with_reentrant_writer() {
602 struct W<'a>(&'a Condition<()>, String);
603 impl fmt::Write for W<'_> {
604 fn write_str(&mut self, s: &str) -> fmt::Result {
605 drop(self.0.clone());
606 self.0.notify_and_lock(());
607 self.1.push_str(s);
608 Ok(())
609 }
610 }
611
612 let cond = Condition::<()>::new();
613 let mut w = W(&cond, String::new());
614 fmt::write(&mut w, format_args!("{cond:?}")).unwrap();
615 assert_eq!(w.1, "Condition { state: Normal }");
616 assert!(matches!(
617 cond.wait()
618 .poll_ready(&mut Context::from_waker(std::task::Waker::noop())),
619 Poll::Ready(ConditionResult::Locked)
620 ));
621 }
622}