1//! type-erased time provider
23use std::future::Future;
4use std::mem::{self, MaybeUninit};
5use std::pin::Pin;
6use std::time::{Duration, Instant, SystemTime};
78use dyn_clone::DynClone;
9use educe::Educe;
10use paste::paste;
1112use crate::{CoarseInstant, CoarseTimeProvider, SleepProvider};
1314//-------------------- handle PreferredRuntime maybe not existing ----------
1516// TODO use this more widely, eg in tor-rtcompat/lib.rs
1718/// See the other implementation
19#[allow(unused_macros)] // Will be redefined if there *is* a preferred runtime
20macro_rules! if_preferred_runtime {{ [$($y:tt)*] [$($n:tt)*] } => { $($n)* }}
21#[cfg(all(
22 any(feature = "native-tls", feature = "rustls"),
23 any(feature = "async-std", feature = "tokio")
24))]
25/// `if_preferred_runtime!{[ Y ] [ N ]}` expands to `Y` (if there's `PreferredRuntime`) or `N`
26macro_rules! if_preferred_runtime {{ [$($y:tt)*] [$($n:tt)*] } => { $($y)* }}
2728if_preferred_runtime! {[
29use crate::PreferredRuntime;
30] [
31/// Dummy value that makes the variant uninhabited
32#[derive(Clone, Debug)]
33enum PreferredRuntime {}
34]}
35/// `with_preferred_runtime!( R; EXPR )` expands to `EXPR`, or to `match *R {}`.
36macro_rules! with_preferred_runtime {{ $p:ident; $($then:tt)* } => {
37if_preferred_runtime!([ $($then)* ] [ match *$p {} ])
38}}
3940//---------- principal types ----------
4142/// Convenience alias for a boxed sleep future
43type DynSleepFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
4445/// Object-safe version of `SleepProvider` and `CoarseTimeProvider`
46///
47/// The methods mirror those in `SleepProvider` and `CoarseTimeProvider`
48#[allow(clippy::missing_docs_in_private_items)]
49trait DynProvider: DynClone + Send + Sync + 'static {
50// SleepProvider principal methods
51fn dyn_now(&self) -> Instant;
52fn dyn_wallclock(&self) -> SystemTime;
53fn dyn_sleep(&self, duration: Duration) -> DynSleepFuture;
5455// SleepProvider testing stuff
56fn dyn_block_advance(&self, reason: String);
57fn dyn_release_advance(&self, _reason: String);
58fn dyn_allow_one_advance(&self, duration: Duration);
5960// CoarseTimeProvider
61fn dyn_now_coarse(&self) -> CoarseInstant;
62}
6364dyn_clone::clone_trait_object!(DynProvider);
6566/// Type-erased `SleepProvider` and `CoarseTimeProvider`
67///
68/// Useful where time is needed, but we don't want a runtime type parameter.
69#[derive(Clone, Debug)]
70pub struct DynTimeProvider(Impl);
7172/// Actual contents of a `DynTimeProvider`
73///
74/// We optimise the `PreferredRuntime` case.
75/// We *could*, instead, just use `Box<dyn DynProvider>` here.
76///
77/// The reason for doing it this way is that we expect this to be on many hot paths.
78/// Putting a message in a queue is extremely common, and we'd like to save a dyn dispatch,
79/// and reference to a further heap entry (which might be distant in the cache).
80///
81/// (Also, it's nice to avoid boxing when we crate new types that use this,
82/// including our memory-quota-tracked mpsc streams, see `tor-memquota::mq_queue`.
83///
84/// The downside is that this means:
85/// * This enum instead of a simple type
86/// * The `unsafe` inside `downcast_value`.
87/// * `match` statements in method shims
88#[derive(Clone, Educe)]
89#[educe(Debug)]
90enum Impl {
91/// Just (a handle to) the preferred runtime
92Preferred(PreferredRuntime),
93/// Some other runtime
94Dyn(#[educe(Debug(ignore))] Box<dyn DynProvider>),
95}
9697impl DynTimeProvider {
98/// Create a new `DynTimeProvider` from a concrete runtime type
99pub fn new<R: SleepProvider + CoarseTimeProvider>(runtime: R) -> Self {
100let imp = match downcast_value(runtime) {
101Ok(preferred) => Impl::Preferred(preferred),
102Err(other) => Impl::Dyn(Box::new(other) as _),
103 };
104 DynTimeProvider(imp)
105 }
106}
107108//---------- impl DynProvider for any SleepProvider + CoarseTimeProvider ----------
109110/// Define ordinary methods in `impl DynProvider`
111///
112/// This macro exists mostly to avoid copypaste mistakes where we (for example)
113/// implement `block_advance` by calling `release_advance`.
114macro_rules! dyn_impl_methods { { $(
115fn $name:ident(
116 ,
117 $( $param:ident: $ptype:ty ),*
118 ) -> $ret:ty;
119)* } => { paste! { $(
120fn [<dyn_ $name>](
121&self,
122 $( $param: $ptype, )*
123 )-> $ret {
124self.$name( $($param,)* )
125 }
126)* } } }
127128impl<R: SleepProvider + CoarseTimeProvider> DynProvider for R {
129dyn_impl_methods! {
130fn now(,) -> Instant;
131fn wallclock(,) -> SystemTime;
132133fn block_advance(, reason: String) -> ();
134fn release_advance(, reason: String) -> ();
135fn allow_one_advance(, duration: Duration) -> ();
136137fn now_coarse(,) -> CoarseInstant;
138 }
139140fn dyn_sleep(&self, duration: Duration) -> DynSleepFuture {
141 Box::pin(self.sleep(duration))
142 }
143}
144145//---------- impl SleepProvider and CoarseTimeProvider for DynTimeProvider ----------
146147/// Define ordinary methods in `impl .. for DynTimeProvider`
148///
149/// This macro exists mostly to avoid copypaste mistakes where we (for example)
150/// implement `block_advance` by calling `release_advance`.
151macro_rules! pub_impl_methods { { $(
152fn $name:ident $( [ $($generics:tt)* ] )? (
153 ,
154 $( $param:ident: $ptype:ty ),*
155 ) -> $ret:ty;
156)* } => { paste! { $(
157fn $name $( < $($generics)* > )?(
158&self,
159 $( $param: $ptype, )*
160 )-> $ret {
161match &self.0 {
162 Impl::Preferred(p) => with_preferred_runtime!(p; p.$name( $($param,)* )),
163 Impl::Dyn(p) => p.[<dyn_ $name>]( $($param .into() ,)? ),
164 }
165 }
166)* } } }
167168impl SleepProvider for DynTimeProvider {
169pub_impl_methods! {
170fn now(,) -> Instant;
171fn wallclock(,) -> SystemTime;
172173fn block_advance[R: Into<String>](, reason: R) -> ();
174fn release_advance[R: Into<String>](, reason: R) -> ();
175fn allow_one_advance(, duration: Duration) -> ();
176 }
177178type SleepFuture = DynSleepFuture;
179180fn sleep(&self, duration: Duration) -> DynSleepFuture {
181match &self.0 {
182 Impl::Preferred(p) => with_preferred_runtime!(p; Box::pin(p.sleep(duration))),
183 Impl::Dyn(p) => p.dyn_sleep(duration),
184 }
185 }
186}
187188impl CoarseTimeProvider for DynTimeProvider {
189pub_impl_methods! {
190fn now_coarse(,) -> CoarseInstant;
191 }
192}
193194//---------- downcast_value ----------
195196// TODO expose this, maybe in tor-basic-utils ?
197198/// Try to cast `I` (which is presumably a TAIT) to `O` (presumably a concrete type)
199///
200/// We use runtime casting, but typically the answer is known at compile time.
201///
202/// Astonishingly, this isn't in any of the following:
203/// * `std`
204/// * `match-downcast`
205/// * `better_any` (`downcast:move` comes close but doesn't give you your `self` back)
206/// * `castaway`
207/// * `mopa`
208/// * `as_any`
209fn downcast_value<I: std::any::Any, O: Sized + 'static>(input: I) -> Result<O, I> {
210// `MaybeUninit` makes it possible to to use `downcast_mut`
211 // and, if it's successful, *move* out of the reference.
212 //
213 // It might be possible to write this function using `mme::transmute` instead.
214 // That might be simpler on the surface, but `mem:transmute` is a very big hammer,
215 // and doing it that way would make it quite easy to accidentally
216 // use the wrong type for the dynamic type check, or mess up lifetimes in I or O.
217 // (Also if we try to transmute the *value*, it might not be possible to
218 // persuade the compiler that the two layouts were necessarily the same.)
219 //
220 // The technique we use is:
221 // * Put the input into `MaybeUninit`, giving us manual control of `I`'s ownership.
222 // * Try to downcast `&mut I` (from the `MaybeUninit`) to `&mut O`.
223 // * If the downcast is successful, move out of the `&mut O`;
224 // this invalidates the `MaybeUninit` (making it uninitialised).
225 // * If the downcast is unsuccessful, reocver the original `I`,
226 // which hasn't in fact have invalidated.
227228let mut input = MaybeUninit::new(input);
229// SAFETY: the MaybeUninit is initialised just above
230let mut_ref: &mut I = unsafe { input.assume_init_mut() };
231match <dyn std::any::Any>::downcast_mut(mut_ref) {
232Some::<&mut O>(output) => {
233let output = output as *mut O;
234// SAFETY:
235 // output is properly aligned and points to a properly initialised
236 // O, because it came from a mut reference
237 // Reading this *invalidates* the MaybeUninit, since the value isn't Copy.
238 // It also invalidates mut_ref, which we therefore mustn't use again.
239let output: O = unsafe { output.read() };
240// Prove that the MaybeUninit is live up to here, and then isn't used any more
241#[allow(clippy::drop_non_drop)] // Yes, we know
242mem::drop::<MaybeUninit<I>>(input);
243Ok(output)
244 }
245None => Err(
246// SAFETY: Indeed, it was just initialised, and downcast_mut didn't change that
247unsafe { input.assume_init() },
248 ),
249 }
250}
251252#[cfg(test)]
253mod test {
254// @@ begin test lint list maintained by maint/add_warning @@
255#![allow(clippy::bool_assert_comparison)]
256 #![allow(clippy::clone_on_copy)]
257 #![allow(clippy::dbg_macro)]
258 #![allow(clippy::mixed_attributes_style)]
259 #![allow(clippy::print_stderr)]
260 #![allow(clippy::print_stdout)]
261 #![allow(clippy::single_char_pattern)]
262 #![allow(clippy::unwrap_used)]
263 #![allow(clippy::unchecked_duration_subtraction)]
264 #![allow(clippy::useless_vec)]
265 #![allow(clippy::needless_pass_by_value)]
266//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
267#![allow(clippy::useless_format)]
268use super::*;
269270use std::fmt::{Debug, Display};
271use std::hint::black_box;
272273fn try_downcast_string<S: Display + Debug + 'static>(x: S) -> Result<String, S> {
274 black_box(downcast_value(black_box(x)))
275 }
276277#[test]
278fn check_downcast_value() {
279// This and the one in check_downcast_dropcount are not combined, with generics,
280 // so that the types of everything are as clear as they can be.
281assert_eq!(try_downcast_string(format!("hi")).unwrap(), format!("hi"));
282assert_eq!(try_downcast_string("hi").unwrap_err().to_string(), "hi");
283 }
284285#[test]
286fn check_downcast_dropcount() {
287#[derive(Debug, derive_more::Display)]
288 #[display("{self:?}")]
289struct DropCounter(u32);
290291fn try_downcast_dc(x: impl Debug + 'static) -> Result<DropCounter, impl Debug + 'static> {
292 black_box(downcast_value(black_box(x)))
293 }
294295impl Drop for DropCounter {
296fn drop(&mut self) {
297let _: u32 = self.0.checked_sub(1).unwrap();
298 }
299 }
300301let dc = DropCounter(0);
302let mut dc: DropCounter = try_downcast_dc(dc).unwrap();
303assert_eq!(dc.0, 0);
304 dc.0 = 1;
305306let dc = DropCounter(0);
307let mut dc: DropCounter = try_downcast_string(dc).unwrap_err();
308assert_eq!(dc.0, 0);
309 dc.0 = 1;
310 }
311}