os_trait/notifier.rs
1use crate::{Duration, OsInterface, Timeout};
2
3/// This method should be able to call from task or ISR.
4/// The implementation should handle the different situations.
5pub trait NotifierInterface: Send + Clone {
6 fn notify(&self) -> bool;
7}
8
9pub trait NotifyWaiterInterface<OS: OsInterface>: Send {
10 /// Wait until notified or timeout occurs.
11 /// # Returns
12 /// - `true` notified
13 /// - `false` timeout occurred
14 fn wait(&self, timeout: &Duration<OS>) -> bool;
15
16 /// # Description
17 /// Wait for a notification, but it can split the total timeout into small timeout.
18 /// Your function will be called once immediately and after each small timeout.
19 /// It's useful when you want to check something while it's waiting.
20 ///
21 /// # Parameters
22 /// - `timeout`: Total timeout.
23 /// - `count`: How many times to split the total timeout.
24 /// If you’re not sure, set it to `1`. Do **NOT** set it to `0`.
25 /// - `f`: Your function. If it returns `Some()`, it will break out of the wait.
26 ///
27 /// # Returns
28 /// - `None`: It's timeout.
29 /// - `Some(x)`: The value returned by your function.
30 ///
31 /// # Note
32 /// It may call your function more times than expected and wait longer than expected.
33 #[inline]
34 fn wait_with<U>(
35 &self,
36 timeout: &Duration<OS>,
37 count: u32,
38 mut f: impl FnMut() -> Option<U>,
39 ) -> Option<U> {
40 assert!(count > 0);
41 let mut wait_t = Duration::<OS>::from_ticks(timeout.as_ticks() / count as u64);
42 let mut t = Timeout::<OS>::from(timeout);
43 loop {
44 if let Some(rst) = f() {
45 return Some(rst);
46 } else if t.timeout() {
47 return None;
48 }
49
50 let left = t.time_left();
51 if left < wait_t {
52 wait_t = left;
53 }
54 self.wait(&wait_t);
55 }
56 }
57}