1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#![doc = include_str!("../README.md")]
use async_std::task::sleep;
use std::future::Future;
use std::time::Duration;

mod instant;
pub use instant::Instant;
mod timeout_error;
pub use timeout_error::TimeoutError;

#[cfg(feature = "mock")]
pub use async_time_mock_core as core;

#[cfg(feature = "interval")]
mod interval;
#[cfg(feature = "interval")]
pub use interval::Interval;

#[derive(Clone)]
pub enum MockableClock {
	Real,
	#[cfg(feature = "mock")]
	Mock(std::sync::Arc<async_time_mock_core::TimerRegistry>),
}

pub enum TimeHandlerGuard {
	Real,
	#[cfg(feature = "mock")]
	Mock(async_time_mock_core::TimeHandlerGuard),
}

#[cfg(feature = "mock")]
impl From<async_time_mock_core::TimeHandlerGuard> for TimeHandlerGuard {
	fn from(guard: async_time_mock_core::TimeHandlerGuard) -> Self {
		Self::Mock(guard)
	}
}

impl MockableClock {
	#[cfg(feature = "mock")]
	pub fn mock() -> (Self, std::sync::Arc<async_time_mock_core::TimerRegistry>) {
		let timer_registry = std::sync::Arc::new(async_time_mock_core::TimerRegistry::default());
		(Self::Mock(timer_registry.clone()), timer_registry)
	}

	pub fn now(&self) -> Instant {
		use MockableClock::*;
		match self {
			Real => std::time::Instant::now().into(),
			#[cfg(feature = "mock")]
			Mock(registry) => registry.now().into(),
		}
	}

	pub async fn sleep(&self, duration: Duration) -> TimeHandlerGuard {
		use MockableClock::*;
		match self {
			Real => {
				sleep(duration).await;
				TimeHandlerGuard::Real
			}
			#[cfg(feature = "mock")]
			Mock(registry) => registry.sleep(duration).await.into(),
		}
	}

	// AFAIK, async-std doesn't have any functionality equivalent to sleep_until

	#[cfg(feature = "interval")]
	pub fn interval(&self, period: Duration) -> Interval {
		use MockableClock::*;
		match self {
			Real => async_std::stream::interval(period).into(),
			#[cfg(feature = "mock")]
			Mock(registry) => registry.interval(period).into(),
		}
	}

	pub async fn timeout<F, T>(&self, duration: Duration, future: F) -> Result<T, TimeoutError>
	where
		F: Future<Output = T>,
	{
		use MockableClock::*;
		match self {
			Real => async_std::future::timeout(duration, future).await.map_err(Into::into),
			#[cfg(feature = "mock")]
			Mock(registry) => registry.timeout(duration, future).await.map_err(Into::into),
		}
	}

	// AFAIK, async-std doesn't have any functionality equivalent to timeout_at
}