backon/blocking_sleep.rs
1use core::time::Duration;
2
3/// A sleeper is used sleep for a specified duration.
4pub trait BlockingSleeper: 'static {
5 /// sleep for a specified duration.
6 fn sleep(&self, dur: Duration);
7}
8
9/// A stub trait allowing non-[`BlockingSleeper`] types to be used as a generic parameter in [`BlockingRetry`][crate::BlockingRetry].
10/// It does not provide actual functionality.
11#[doc(hidden)]
12pub trait MaybeBlockingSleeper: 'static {}
13
14/// All `BlockingSleeper` will implement `MaybeBlockingSleeper`, but not vice versa.
15impl<T: BlockingSleeper + ?Sized> MaybeBlockingSleeper for T {}
16
17/// All `Fn(Duration)` implements `Sleeper`.
18impl<F: Fn(Duration) + 'static> BlockingSleeper for F {
19 fn sleep(&self, dur: Duration) {
20 self(dur)
21 }
22}
23
24/// The default implementation of `Sleeper` when no features are enabled.
25///
26/// It will fail to compile if a containing [`Retry`][crate::Retry] is `.await`ed without calling [`Retry::sleep`][crate::Retry::sleep] to provide a valid sleeper.
27#[cfg(not(feature = "std-blocking-sleep"))]
28pub type DefaultBlockingSleeper = PleaseEnableAFeatureOrProvideACustomSleeper;
29/// The default implementation of `Sleeper` while feature `std-blocking-sleep` enabled.
30///
31/// it uses [`std::thread::sleep`].
32#[cfg(feature = "std-blocking-sleep")]
33pub type DefaultBlockingSleeper = StdSleeper;
34
35/// A placeholder type that does not implement [`Sleeper`] and will therefore fail to compile if used as one.
36///
37/// Users should enable a feature of this crate that provides a valid [`Sleeper`] implementation when this type appears in compilation errors. Alternatively, a custom [`Sleeper`] implementation should be provided where necessary, such as in [`crate::Retry::sleeper`].
38#[doc(hidden)]
39#[derive(Clone, Copy, Debug, Default)]
40pub struct PleaseEnableAFeatureOrProvideACustomSleeper;
41
42/// Implement `MaybeSleeper` but not `Sleeper`.
43impl MaybeBlockingSleeper for PleaseEnableAFeatureOrProvideACustomSleeper {}
44
45/// The implementation of `StdSleeper` uses [`std::thread::sleep`].
46#[cfg(feature = "std-blocking-sleep")]
47#[derive(Clone, Copy, Debug, Default)]
48pub struct StdSleeper;
49
50#[cfg(feature = "std-blocking-sleep")]
51impl BlockingSleeper for StdSleeper {
52 fn sleep(&self, dur: Duration) {
53 std::thread::sleep(dur)
54 }
55}