aws_smithy_async/test_util/
manual_time.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6use crate::time::TimeSource;
7use std::sync::{Arc, Mutex};
8use std::time::{Duration, SystemTime};
9
10/// Manually controlled time source
11#[derive(Debug, Clone)]
12pub struct ManualTimeSource {
13    pub(super) start_time: SystemTime,
14    pub(super) log: Arc<Mutex<Vec<Duration>>>,
15}
16
17impl ManualTimeSource {
18    /// Get the number of seconds since the UNIX Epoch as an f64.
19    ///
20    /// ## Panics
21    ///
22    /// This will panic if `self.now()` returns a time that's before the UNIX Epoch.
23    pub fn seconds_since_unix_epoch(&self) -> f64 {
24        self.now()
25            .duration_since(SystemTime::UNIX_EPOCH)
26            .unwrap()
27            .as_secs_f64()
28    }
29
30    /// Creates a new [`ManualTimeSource`]
31    pub fn new(start_time: SystemTime) -> ManualTimeSource {
32        Self {
33            start_time,
34            log: Default::default(),
35        }
36    }
37
38    /// Advances the time of this time source by `duration`.
39    pub fn advance(&self, duration: Duration) -> SystemTime {
40        let mut log = self.log.lock().unwrap();
41        log.push(duration);
42        self._now(&log)
43    }
44
45    fn _now(&self, log: &[Duration]) -> SystemTime {
46        self.start_time + log.iter().sum::<Duration>()
47    }
48
49    /// Sets the `time` of this manual time source.
50    ///
51    /// # Panics
52    /// This function panics if `time` < `now()`
53    pub fn set_time(&self, time: SystemTime) {
54        let mut log = self.log.lock().unwrap();
55        let now = self._now(&log);
56        if time < now {
57            panic!("Cannot move time backwards!");
58        }
59        log.push(time.duration_since(now).unwrap());
60    }
61}
62
63impl TimeSource for ManualTimeSource {
64    fn now(&self) -> SystemTime {
65        self._now(&self.log.lock().unwrap())
66    }
67}