odbc_api/
sleep.rs

1use std::future::Future;
2
3use crate::handles::SqlResult;
4
5/// Governs the behaviour of of polling in async functions.
6///
7/// There is a generic implementation for any function retuning a future. This allows e.g. to pass
8/// `|| tokio::time::sleep(Duration::from_millis(50))` to functions expecting sleep. That is if
9/// you use `tokio` as your async runtime, of course.
10pub trait Sleep {
11    type Poll: Future;
12
13    /// Between each poll next poll is executed, and the resulting future is awaited.
14    fn next_poll(&mut self) -> Self::Poll;
15}
16
17impl<S, F> Sleep for S
18where
19    S: FnMut() -> F,
20    F: Future,
21{
22    type Poll = F;
23
24    fn next_poll(&mut self) -> Self::Poll {
25        (self)()
26    }
27}
28
29pub async fn wait_for<F, O>(mut f: F, sleep: &mut impl Sleep) -> SqlResult<O>
30where
31    F: FnMut() -> SqlResult<O>,
32{
33    let mut ret = (f)();
34    // Wait for operation to finish, using polling method
35    while matches!(ret, SqlResult::StillExecuting) {
36        sleep.next_poll().await;
37        ret = (f)();
38    }
39    ret
40}