Skip to main content

qubit_lock/monitor/
condition_waiter.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 *    SPDX-License-Identifier: Apache-2.0
6 *
7 *    Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Blocking condition-wait capability.
11
12/// Waits for predicates over protected monitor state.
13pub trait ConditionWaiter {
14    /// State protected by the monitor.
15    type State;
16
17    /// Blocks until the predicate becomes true, then runs an action.
18    ///
19    /// The predicate and action run while the monitor state is locked.
20    ///
21    /// # Arguments
22    ///
23    /// * `predicate` - Predicate that returns `true` when the state is ready.
24    /// * `action` - Action to run after the predicate becomes true.
25    ///
26    /// # Returns
27    ///
28    /// The value returned by `action`.
29    fn wait_until<R, P, F>(&self, mut predicate: P, action: F) -> R
30    where
31        P: FnMut(&Self::State) -> bool,
32        F: FnOnce(&mut Self::State) -> R,
33    {
34        self.wait_while(move |state| !predicate(state), action)
35    }
36
37    /// Blocks while the predicate remains true, then runs an action.
38    ///
39    /// The predicate and action run while the monitor state is locked.
40    ///
41    /// # Arguments
42    ///
43    /// * `predicate` - Predicate that returns `true` while waiting should
44    ///   continue.
45    /// * `action` - Action to run after the predicate becomes false.
46    ///
47    /// # Returns
48    ///
49    /// The value returned by `action`.
50    fn wait_while<R, P, F>(&self, predicate: P, action: F) -> R
51    where
52        P: FnMut(&Self::State) -> bool,
53        F: FnOnce(&mut Self::State) -> R;
54}