Skip to main content

ntex_util/channel/
condition.rs

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)]
9/// Result produced by a [`Condition`] waiter.
10pub enum ConditionResult<T> {
11    /// The condition delivered a value.
12    Value(T),
13    /// The condition has been locked and will not deliver more values.
14    Locked,
15    /// The last handle to the condition was dropped.
16    Dropped,
17}
18
19#[derive(Copy, Clone, PartialEq, Eq, Debug)]
20enum State {
21    Normal,
22    Locked,
23    Dropped,
24}
25
26/// A condition that can wake several waiting tasks at once.
27///
28/// Notifications are not queued. A waiter must have been polled and registered
29/// its waker before [`notify`](Self::notify) is called, otherwise it misses that
30/// value. Use [`notify_and_lock`](Self::notify_and_lock) when no later
31/// notifications should be accepted.
32pub struct Condition<T = ()> {
33    inner: Cell<Inner<T>>,
34}
35
36/// A task waiting for a [`Condition`] notification.
37pub 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
53/// Delivers a result from `make` to every registered waiter.
54///
55/// `make`, value drops and waker callbacks may reenter the condition, adding
56/// or removing waiters and reallocating the slab, so they run without a
57/// borrow of `inner`. Waiters added during delivery may be skipped.
58fn 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        // the formatter may reenter the condition, so no borrow of `inner` is held
101        let state = self.inner.get_ref().state;
102        f.debug_struct("Condition").field("state", &state).finish()
103    }
104}
105
106impl<T> Condition<T> {
107    /// Creates an unlocked condition with no waiters.
108    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    /// Creates a new waiter.
121    ///
122    /// The waiter starts listening when it is first polled, not when this
123    /// method returns.
124    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    /// Sends `val` to every waiter that is currently being polled.
133    ///
134    /// The value is cloned for each registered waiter. Unpolled waiters do not
135    /// receive it, and the value is not retained for future waiters.
136    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    /// Notifies the current waiters and permanently locks the condition.
143    ///
144    /// Registered waiters receive `val`. Later readiness checks return
145    /// [`ConditionResult::Locked`], and later calls to [`notify`](Self::notify)
146    /// do not deliver another value.
147    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    /// Sends `T::default()` to every waiter that is currently being polled.
155    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    /// Waits for the next condition result.
180    pub async fn ready(&self) -> ConditionResult<T> {
181        poll_fn(|cx| self.poll_ready(cx)).await
182    }
183
184    /// Polls for the next condition result.
185    ///
186    /// The first poll registers this waiter. While the condition remains
187    /// unlocked, later notifications wake the registered task.
188    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        // waker callbacks may reenter the condition, so the item is looked up
207        // again after each one
208        let registered = LocalWaker::register_in(|| &self.item().waker, cx.waker());
209
210        // an unset waker on a registered item means a result was delivered
211        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        // `poll_ready` initializes this waiter's item before any access
220        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    /// STATEMENT: Condition waiters receive notifications and observe the condition's drop.
270    ///
271    /// HOW:
272    /// - Poll a waiter pending, notify its default value, and check its result and debug output.
273    /// - Drop the condition with two pending cloned waiters and verify both report `Dropped`.
274    #[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    /// STATEMENT: Polling consumes a condition notification but keeps drop results repeatable.
305    ///
306    /// HOW:
307    /// - Notify and await a waiter, then poll it and its clone repeatedly as pending.
308    /// - Drop the condition and verify repeated polls of both return `Dropped`.
309    #[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    /// STATEMENT: Conditions deliver supplied values and report drop after the value is consumed.
343    ///
344    /// HOW:
345    /// - Notify a string and verify the waiter receives that value.
346    /// - Poll the waiter and its clone before and after dropping the condition.
347    #[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    /// STATEMENT: Awaiting a condition value does not require the value to implement `Default`.
384    ///
385    /// HOW:
386    /// - Create a condition for a cloneable non-default type and poll its waiter pending.
387    /// - Notify a concrete value and verify awaiting the waiter returns it.
388    #[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    /// STATEMENT: Locking a condition delivers its final value once and rejects later notifications.
402    ///
403    /// HOW:
404    /// - Notify and lock a pending waiter, then check its value followed by repeated `Locked` results.
405    /// - Notify again and create another waiter, verifying neither escapes the locked state.
406    #[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    /// STATEMENT: Notify-and-lock delivers the final value to every existing waiter.
439    ///
440    /// HOW:
441    /// - Register two pending waiters, lock with a string value, and consume it from each.
442    /// - Verify subsequent polls and a newly created waiter report `Locked`.
443    #[ntex::test]
444    async fn notify_with_and_lock_ready() {
445        // with
446        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    /// STATEMENT: A default notification cannot unlock an already locked condition.
482    ///
483    /// HOW:
484    /// - Lock the condition, create a waiter, and issue a default notification.
485    /// - Poll the waiter as a future and verify it still reports `Locked`.
486    #[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    /// STATEMENT: Waiters stored in the shared slab observe values, locking and the
499    /// condition's drop without undefined behavior.
500    ///
501    /// HOW:
502    /// - Poll two waiters pending with `Waker::noop`, notify `1`, and check both get it.
503    /// - Lock a cloned condition with `2`, check the waiter returns it, then `Locked`.
504    /// - Check a new waiter of the locked condition is immediately `Locked`.
505    /// - Drop both condition handles and check the remaining waiter reports `Dropped`.
506    #[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    /// STATEMENT: `notify` delivers to a waiter whose wake callback reallocates the waiter slab.
542    ///
543    /// HOW:
544    /// - Register a waiter with `hook_waker`, then set an `ON_WAKE` hook that creates 64 waiters.
545    /// - Call `notify` and check the hook ran and the waiter is ready with the value.
546    #[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    /// STATEMENT: The first `poll_ready` registers its waiter even when the waker clone reallocates the waiter slab.
569    ///
570    /// HOW:
571    /// - Set an `ON_CLONE` hook that creates 64 waiters, then poll a new waiter with `hook_waker`.
572    /// - Check the poll is pending, then `notify` and check the waiter is ready with the value.
573    #[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    /// STATEMENT: Formatting a condition with `Debug` holds no borrow of its state while the formatter's writer reenters the condition.
596    ///
597    /// HOW:
598    /// - Format the condition into a writer that clones the condition and calls `notify_and_lock` on every write.
599    /// - Check the output reports the state read before formatting, and that the condition is locked afterwards.
600    #[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}