1
//! type-erased time provider
2

            
3
use std::future::Future;
4
use std::mem::{self, MaybeUninit};
5
use std::pin::Pin;
6
use std::time::{Duration, Instant, SystemTime};
7

            
8
use dyn_clone::DynClone;
9
use educe::Educe;
10
use paste::paste;
11

            
12
use crate::{CoarseInstant, CoarseTimeProvider, SleepProvider};
13

            
14
//-------------------- handle PreferredRuntime maybe not existing ----------
15

            
16
// TODO use this more widely, eg in tor-rtcompat/lib.rs
17

            
18
/// See the other implementation
19
#[allow(unused_macros)] // Will be redefined if there *is* a preferred runtime
20
macro_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`
26
macro_rules! if_preferred_runtime {{ [$($y:tt)*] [$($n:tt)*] } => { $($y)* }}
27

            
28
if_preferred_runtime! {[
29
    use crate::PreferredRuntime;
30
] [
31
    /// Dummy value that makes the variant uninhabited
32
    #[derive(Clone, Debug)]
33
    enum PreferredRuntime {}
34
]}
35
/// `with_preferred_runtime!( R; EXPR )` expands to `EXPR`, or to `match *R {}`.
36
macro_rules! with_preferred_runtime {{ $p:ident; $($then:tt)* } => {
37
    if_preferred_runtime!([ $($then)* ] [ match *$p {} ])
38
}}
39

            
40
//---------- principal types ----------
41

            
42
/// Convenience alias for a boxed sleep future
43
type DynSleepFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
44

            
45
/// 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)]
49
trait DynProvider: DynClone + Send + Sync + 'static {
50
    // SleepProvider principal methods
51
    fn dyn_now(&self) -> Instant;
52
    fn dyn_wallclock(&self) -> SystemTime;
53
    fn dyn_sleep(&self, duration: Duration) -> DynSleepFuture;
54

            
55
    // SleepProvider testing stuff
56
    fn dyn_block_advance(&self, reason: String);
57
    fn dyn_release_advance(&self, _reason: String);
58
    fn dyn_allow_one_advance(&self, duration: Duration);
59

            
60
    // CoarseTimeProvider
61
    fn dyn_now_coarse(&self) -> CoarseInstant;
62
}
63

            
64
dyn_clone::clone_trait_object!(DynProvider);
65

            
66
/// 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)]
70
pub struct DynTimeProvider(Impl);
71

            
72
/// 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)]
90
enum Impl {
91
    /// Just (a handle to) the preferred runtime
92
    Preferred(PreferredRuntime),
93
    /// Some other runtime
94
    Dyn(#[educe(Debug(ignore))] Box<dyn DynProvider>),
95
}
96

            
97
impl DynTimeProvider {
98
    /// Create a new `DynTimeProvider` from a concrete runtime type
99
1804
    pub fn new<R: SleepProvider + CoarseTimeProvider>(runtime: R) -> Self {
100
1804
        let imp = match downcast_value(runtime) {
101
2
            Ok(preferred) => Impl::Preferred(preferred),
102
1802
            Err(other) => Impl::Dyn(Box::new(other) as _),
103
        };
104
1804
        DynTimeProvider(imp)
105
1804
    }
106
}
107

            
108
//---------- impl DynProvider for any SleepProvider + CoarseTimeProvider ----------
109

            
110
/// 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`.
114
macro_rules! dyn_impl_methods { { $(
115
    fn $name:ident(
116
        ,
117
        $( $param:ident: $ptype:ty ),*
118
    ) -> $ret:ty;
119
)* } => { paste! { $(
120
8150
    fn [<dyn_ $name>](
121
8150
        &self,
122
8150
        $( $param: $ptype, )*
123
8150
    )-> $ret {
124
8150
        self.$name( $($param,)* )
125
8150
    }
126
)* } } }
127

            
128
impl<R: SleepProvider + CoarseTimeProvider> DynProvider for R {
129
    dyn_impl_methods! {
130
        fn now(,) -> Instant;
131
        fn wallclock(,) -> SystemTime;
132

            
133
        fn block_advance(, reason: String) -> ();
134
        fn release_advance(, reason: String) -> ();
135
        fn allow_one_advance(, duration: Duration) -> ();
136

            
137
        fn now_coarse(,) -> CoarseInstant;
138
    }
139

            
140
    fn dyn_sleep(&self, duration: Duration) -> DynSleepFuture {
141
        Box::pin(self.sleep(duration))
142
    }
143
}
144

            
145
//---------- impl SleepProvider and CoarseTimeProvider for DynTimeProvider ----------
146

            
147
/// 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`.
151
macro_rules! pub_impl_methods { { $(
152
    fn $name:ident $( [ $($generics:tt)* ] )? (
153
        ,
154
        $( $param:ident: $ptype:ty ),*
155
    ) -> $ret:ty;
156
)* } => { paste! { $(
157
195314
    fn $name $( < $($generics)* > )?(
158
195314
        &self,
159
195314
        $( $param: $ptype, )*
160
195314
    )-> $ret {
161
195314
        match &self.0 {
162
49
            Impl::Preferred(p) => with_preferred_runtime!(p; p.$name( $($param,)* )),
163
195265
            Impl::Dyn(p) => p.[<dyn_ $name>]( $($param .into() ,)? ),
164
        }
165
195314
    }
166
)* } } }
167

            
168
impl SleepProvider for DynTimeProvider {
169
    pub_impl_methods! {
170
        fn now(,) -> Instant;
171
        fn wallclock(,) -> SystemTime;
172

            
173
        fn block_advance[R: Into<String>](, reason: R) -> ();
174
        fn release_advance[R: Into<String>](, reason: R) -> ();
175
        fn allow_one_advance(, duration: Duration) -> ();
176
    }
177

            
178
    type SleepFuture = DynSleepFuture;
179

            
180
    fn sleep(&self, duration: Duration) -> DynSleepFuture {
181
        match &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
}
187

            
188
impl CoarseTimeProvider for DynTimeProvider {
189
    pub_impl_methods! {
190
        fn now_coarse(,) -> CoarseInstant;
191
    }
192
}
193

            
194
//---------- downcast_value ----------
195

            
196
// TODO expose this, maybe in tor-basic-utils ?
197

            
198
/// 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`
209
1812
fn downcast_value<I: std::any::Any, O: Sized + 'static>(input: I) -> Result<O, I> {
210
1812
    // `MaybeUninit` makes it possible to to use `downcast_mut`
211
1812
    // and, if it's successful, *move* out of the reference.
212
1812
    //
213
1812
    // It might be possible to write this function using `mme::transmute` instead.
214
1812
    // That might be simpler on the surface, but `mem:transmute` is a very big hammer,
215
1812
    // and doing it that way would make it quite easy to accidentally
216
1812
    // use the wrong type for the dynamic type check, or mess up lifetimes in I or O.
217
1812
    // (Also if we try to transmute the *value*, it might not be possible to
218
1812
    // persuade the compiler that the two layouts were necessarily the same.)
219
1812
    //
220
1812
    // The technique we use is:
221
1812
    //    * Put the input into `MaybeUninit`, giving us manual control of `I`'s ownership.
222
1812
    //    * Try to downcast `&mut I` (from the `MaybeUninit`) to `&mut O`.
223
1812
    //    * If the downcast is successful, move out of the `&mut O`;
224
1812
    //      this invalidates the `MaybeUninit` (making it uninitialised).
225
1812
    //    * If the downcast is unsuccessful, reocver the original `I`,
226
1812
    //      which hasn't in fact have invalidated.
227
1812

            
228
1812
    let mut input = MaybeUninit::new(input);
229
1812
    // SAFETY: the MaybeUninit is initialised just above
230
1812
    let mut_ref: &mut I = unsafe { input.assume_init_mut() };
231
1812
    match <dyn std::any::Any>::downcast_mut(mut_ref) {
232
6
        Some::<&mut O>(output) => {
233
6
            let output = output as *mut O;
234
6
            // SAFETY:
235
6
            //  output is properly aligned and points to a properly initialised
236
6
            //    O, because it came from a mut reference
237
6
            //  Reading this *invalidates* the MaybeUninit, since the value isn't Copy.
238
6
            //  It also invalidates mut_ref, which we therefore mustn't use again.
239
6
            let output: O = unsafe { output.read() };
240
6
            // Prove that the MaybeUninit is live up to here, and then isn't used any more
241
6
            #[allow(clippy::drop_non_drop)] // Yes, we know
242
6
            mem::drop::<MaybeUninit<I>>(input);
243
6
            Ok(output)
244
        }
245
1806
        None => Err(
246
1806
            // SAFETY: Indeed, it was just initialised, and downcast_mut didn't change that
247
1806
            unsafe { input.assume_init() },
248
1806
        ),
249
    }
250
1812
}
251

            
252
#[cfg(test)]
253
mod 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)]
268
    use super::*;
269

            
270
    use std::fmt::{Debug, Display};
271
    use std::hint::black_box;
272

            
273
    fn try_downcast_string<S: Display + Debug + 'static>(x: S) -> Result<String, S> {
274
        black_box(downcast_value(black_box(x)))
275
    }
276

            
277
    #[test]
278
    fn 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.
281
        assert_eq!(try_downcast_string(format!("hi")).unwrap(), format!("hi"));
282
        assert_eq!(try_downcast_string("hi").unwrap_err().to_string(), "hi");
283
    }
284

            
285
    #[test]
286
    fn check_downcast_dropcount() {
287
        #[derive(Debug, derive_more::Display)]
288
        #[display("{self:?}")]
289
        struct DropCounter(u32);
290

            
291
        fn try_downcast_dc(x: impl Debug + 'static) -> Result<DropCounter, impl Debug + 'static> {
292
            black_box(downcast_value(black_box(x)))
293
        }
294

            
295
        impl Drop for DropCounter {
296
            fn drop(&mut self) {
297
                let _: u32 = self.0.checked_sub(1).unwrap();
298
            }
299
        }
300

            
301
        let dc = DropCounter(0);
302
        let mut dc: DropCounter = try_downcast_dc(dc).unwrap();
303
        assert_eq!(dc.0, 0);
304
        dc.0 = 1;
305

            
306
        let dc = DropCounter(0);
307
        let mut dc: DropCounter = try_downcast_string(dc).unwrap_err();
308
        assert_eq!(dc.0, 0);
309
        dc.0 = 1;
310
    }
311
}