use crate::private::Sealed;
#[cfg(any(test, feature = "use-mocks"))]
use mockiato::mockable;
use std::fmt::Debug;
use std::time::{Duration, Instant};
#[cfg_attr(any(test, feature = "use-mocks"), mockable)]
pub trait InstantWrapper: Debug + Sealed {
fn duration_since(&self, earlier: &dyn InstantWrapper) -> Duration;
fn elapsed(&self) -> Duration;
fn to_inner(&self) -> Instant;
}
#[cfg(any(test, feature = "use-mocks"))]
impl Sealed for InstantWrapperMock<'_> {}
#[derive(Debug)]
pub struct InstantWrapperImpl {
instant: Instant,
}
impl InstantWrapperImpl {
pub fn new(instant: Instant) -> Self {
Self { instant }
}
}
impl Sealed for InstantWrapperImpl {}
impl InstantWrapper for InstantWrapperImpl {
fn duration_since(&self, earlier: &dyn InstantWrapper) -> Duration {
self.instant.duration_since(earlier.to_inner())
}
fn elapsed(&self) -> Duration {
self.instant.elapsed()
}
fn to_inner(&self) -> Instant {
self.instant
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread::sleep;
const MAX_DURATION: Duration = Duration::from_millis(20);
#[test]
fn returns_inner() {
let instant = Instant::now();
let wrapper = InstantWrapperImpl::new(instant);
assert_eq!(instant, wrapper.to_inner());
}
#[test]
fn duration_since_another_instant_wrapper_is_within_range() {
let early_wrapper = InstantWrapperImpl::new(Instant::now());
let sleep_duration = Duration::from_millis(15);
sleep(sleep_duration);
let late_wrapper = InstantWrapperImpl::new(Instant::now());
let elapsed_time = late_wrapper.duration_since(&early_wrapper);
assert!(elapsed_time >= sleep_duration && elapsed_time < MAX_DURATION);
}
#[test]
fn duration_since_another_instant_wrapper_is_within_range_after_second_sleep() {
let early_wrapper = InstantWrapperImpl::new(Instant::now());
let sleep_duration = Duration::from_millis(15);
sleep(sleep_duration);
let late_wrapper = InstantWrapperImpl::new(Instant::now());
sleep(MAX_DURATION);
let elapsed_time = late_wrapper.duration_since(&early_wrapper);
assert!(elapsed_time >= sleep_duration && elapsed_time < MAX_DURATION);
}
#[test]
fn elapsed_time_is_within_range() {
let wrapper = InstantWrapperImpl::new(Instant::now());
let sleep_duration = Duration::from_millis(15);
sleep(sleep_duration);
let elapsed_time = wrapper.elapsed();
assert!(elapsed_time >= sleep_duration && elapsed_time < MAX_DURATION);
}
}