qubit_lock/monitor/timeout_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 timeout condition-wait capability.
11
12use std::time::Duration;
13
14use crate::monitor::{
15 ConditionWaiter,
16 WaitTimeoutResult,
17};
18
19/// Waits for predicates over protected state with relative timeouts.
20pub trait TimeoutConditionWaiter: ConditionWaiter {
21 /// Blocks until the predicate becomes true or the timeout expires.
22 ///
23 /// # Arguments
24 ///
25 /// * `timeout` - Maximum relative duration to wait.
26 /// * `predicate` - Predicate that returns `true` when the state is ready.
27 /// * `action` - Action to run after the predicate becomes true.
28 ///
29 /// # Returns
30 ///
31 /// [`WaitTimeoutResult::Ready`] with the action result, or
32 /// [`WaitTimeoutResult::TimedOut`] when the timeout expires first.
33 fn wait_until_for<R, P, F>(
34 &self,
35 timeout: Duration,
36 mut predicate: P,
37 action: F,
38 ) -> WaitTimeoutResult<R>
39 where
40 P: FnMut(&Self::State) -> bool,
41 F: FnOnce(&mut Self::State) -> R,
42 {
43 self.wait_while_for(timeout, move |state| !predicate(state), action)
44 }
45
46 /// Blocks while the predicate remains true or until the timeout expires.
47 ///
48 /// # Arguments
49 ///
50 /// * `timeout` - Maximum relative duration to wait.
51 /// * `predicate` - Predicate that returns `true` while waiting should
52 /// continue.
53 /// * `action` - Action to run after the predicate becomes false.
54 ///
55 /// # Returns
56 ///
57 /// [`WaitTimeoutResult::Ready`] with the action result, or
58 /// [`WaitTimeoutResult::TimedOut`] when the timeout expires first.
59 fn wait_while_for<R, P, F>(
60 &self,
61 timeout: Duration,
62 predicate: P,
63 action: F,
64 ) -> WaitTimeoutResult<R>
65 where
66 P: FnMut(&Self::State) -> bool,
67 F: FnOnce(&mut Self::State) -> R;
68}