use crate::{TimeBound, TimeValidityError};
use itertools::chain;
use std::ops::{Bound, Deref, RangeBounds};
use web_time_compat as time;
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct TimeRangeBound<T> {
obj: T,
start: Option<time::SystemTime>,
end: Option<time::SystemTime>,
}
pub type TimeRange = TimeRangeBound<()>;
#[deprecated = "use the new name, TimeRangeBound, instead"]
pub type TimerangeBound<T> = TimeRangeBound<T>;
fn unwrap_bound(b: Bound<&'_ time::SystemTime>) -> Option<time::SystemTime> {
match b {
Bound::Included(x) => Some(*x),
Bound::Excluded(x) => Some(*x),
_ => None,
}
}
impl<T> TimeRangeBound<T> {
pub fn new<U>(obj: T, range: U) -> Self
where
U: RangeBounds<time::SystemTime>,
{
let start = unwrap_bound(range.start_bound());
let end = unwrap_bound(range.end_bound());
Self { obj, start, end }
}
pub fn new_from_start_end(
obj: T,
start: Option<time::SystemTime>,
end: Option<time::SystemTime>,
) -> Self {
Self { obj, start, end }
}
#[must_use]
pub fn extend_start_bound(self, d: time::Duration) -> Self {
let start = match self.start {
Some(t) => t.checked_sub(d),
_ => None,
};
Self { start, ..self }
}
#[must_use]
pub fn extend_end_bound(self, d: time::Duration) -> Self {
let end = match self.end {
Some(t) => t.checked_add(d),
_ => None,
};
Self { end, ..self }
}
#[deprecated = "use extend_start_bound instead"]
#[must_use]
pub fn extend_pre_tolerance(self, d: time::Duration) -> Self {
self.extend_start_bound(d)
}
#[deprecated = "use extend_end_bound instead"]
#[must_use]
pub fn extend_tolerance(self, d: time::Duration) -> Self {
self.extend_end_bound(d)
}
#[must_use]
pub fn dangerously_map<F, U>(self, f: F) -> TimeRangeBound<U>
where
F: FnOnce(T) -> U,
{
TimeRangeBound {
obj: f(self.obj),
start: self.start,
end: self.end,
}
}
pub fn dangerously_into_parts(self) -> (T, TimeRange) {
let bounds = self.bounds();
(self.obj, bounds)
}
pub fn dangerously_peek(&self) -> &T {
&self.obj
}
pub fn as_ref(&self) -> TimeRangeBound<&T> {
TimeRangeBound {
obj: &self.obj,
start: self.start,
end: self.end,
}
}
pub fn as_deref(&self) -> TimeRangeBound<&T::Target>
where
T: Deref,
{
self.as_ref().dangerously_map(|t| &**t)
}
pub fn bounds_start_end(&self) -> (Option<time::SystemTime>, Option<time::SystemTime>) {
(self.start, self.end)
}
pub fn intersect_bounds(&mut self, bounds: TimeRange) {
self.start = chain!(self.start, bounds.start()).max();
self.end = chain!(self.end, bounds.end()).min();
}
pub fn build_intersect<Error, Logic>(logic: Logic) -> Result<Self, Error>
where
Logic: FnOnce(&mut TimeRangeBoundBuilder) -> Result<T, Error>,
{
let mut builder = TimeRangeBoundBuilder(TimeRange::new_range(..));
let output = logic(&mut builder)?;
Ok(builder.0.apply_to(output))
}
}
impl TimeRange {
pub fn new_range<U>(range: U) -> Self
where
U: RangeBounds<time::SystemTime>,
{
Self::new((), range)
}
pub fn apply_to<T>(self, t: T) -> TimeRangeBound<T> {
TimeRangeBound::new(t, self.bounds())
}
pub fn start(&self) -> Option<time::SystemTime> {
self.start
}
pub fn end(&self) -> Option<time::SystemTime> {
self.end
}
}
pub struct TimeRangeBoundBuilder(TimeRange);
impl TimeRangeBoundBuilder {
pub fn incorporate_unwrap<Component: TimeBound>(
&mut self,
component: Component,
) -> Component::Inner {
self.intersect_bounds(component.bounds());
component.dangerously_assume_timely()
}
pub fn intersect_bounds(&mut self, bounds: TimeRange) {
self.as_mut_range().intersect_bounds(bounds);
}
pub fn as_mut_range(&mut self) -> &mut TimeRange {
&mut self.0
}
}
impl<T> RangeBounds<time::SystemTime> for TimeRangeBound<T> {
fn start_bound(&self) -> Bound<&time::SystemTime> {
self.start
.as_ref()
.map(Bound::Included)
.unwrap_or(Bound::Unbounded)
}
fn end_bound(&self) -> Bound<&time::SystemTime> {
self.end
.as_ref()
.map(Bound::Included)
.unwrap_or(Bound::Unbounded)
}
}
macro_rules! impl_from_range { { $R:ty } => {
impl From<$R> for TimeRange {
fn from(r: $R) -> TimeRange {
TimeRange::new_range(r)
}
}
} }
impl_from_range! { std::ops::RangeFrom<time::SystemTime> }
impl_from_range! { std::ops::RangeFull }
impl_from_range! { std::ops::RangeInclusive<time::SystemTime> }
impl_from_range! { std::ops::RangeToInclusive<time::SystemTime> }
impl<T> crate::TimeBound for TimeRangeBound<T> {
type Inner = T;
fn bounds(&self) -> TimeRange {
TimeRangeBound {
obj: (),
start: self.start,
end: self.end,
}
}
fn check_valid_at(&self, t: &time::SystemTime) -> Result<(), TimeValidityError> {
use crate::TimeValidityError;
if let Some(start) = self.start {
if let Ok(d) = start.duration_since(*t)
&& d > time::Duration::ZERO
{
return Err(TimeValidityError::NotYetValid(d));
}
}
if let Some(end) = self.end {
if let Ok(d) = t.duration_since(end)
&& d > time::Duration::ZERO
{
return Err(TimeValidityError::Expired(d));
}
}
Ok(())
}
fn dangerously_assume_timely(self) -> T {
self.obj
}
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::string_slice)] use super::*;
use crate::{TimeBound, TimeValidityError};
use humantime::parse_rfc3339;
use tor_basic_utils::rangebounds::RangeBoundsExt as _;
use web_time_compat::{Duration, SystemTime, SystemTimeExt};
#[test]
fn test_bounds() {
#![allow(clippy::unwrap_used)]
let one_day = Duration::new(86400, 0);
let mixminion_v0_0_1 = parse_rfc3339("2003-01-07T00:00:00Z").unwrap();
let tor_v0_0_2pre13 = parse_rfc3339("2003-10-19T00:00:00Z").unwrap();
let cussed_nougat = parse_rfc3339("2008-08-02T00:00:00Z").unwrap();
let tor_v0_4_4_5 = parse_rfc3339("2020-09-15T00:00:00Z").unwrap();
let today = parse_rfc3339("2020-09-22T00:00:00Z").unwrap();
let tr = TimeRangeBound::new((), ..tor_v0_4_4_5);
assert_eq!(tr.start, None);
assert_eq!(tr.end, Some(tor_v0_4_4_5));
assert!(tr.check_valid_at(&mixminion_v0_0_1).is_ok());
assert!(tr.check_valid_at(&tor_v0_0_2pre13).is_ok());
assert_eq!(
tr.check_valid_at(&today),
Err(TimeValidityError::Expired(7 * one_day))
);
let tr = TimeRangeBound::new((), tor_v0_0_2pre13..=tor_v0_4_4_5);
assert_eq!(tr.start, Some(tor_v0_0_2pre13));
assert_eq!(tr.end, Some(tor_v0_4_4_5));
assert_eq!(
tr.check_valid_at(&mixminion_v0_0_1),
Err(TimeValidityError::NotYetValid(285 * one_day))
);
assert!(tr.check_valid_at(&cussed_nougat).is_ok());
assert_eq!(
tr.check_valid_at(&today),
Err(TimeValidityError::Expired(7 * one_day))
);
let tr = tr
.extend_start_bound(5 * one_day)
.extend_end_bound(2 * one_day);
assert_eq!(tr.start, Some(tor_v0_0_2pre13 - 5 * one_day));
assert_eq!(tr.end, Some(tor_v0_4_4_5 + 2 * one_day));
let tr = tr
.extend_start_bound(Duration::MAX)
.extend_end_bound(Duration::MAX);
assert_eq!(tr.start, None);
assert_eq!(tr.end, None);
let tr = TimeRangeBound::new((), tor_v0_4_4_5..);
assert_eq!(tr.start, Some(tor_v0_4_4_5));
assert_eq!(tr.end, None);
assert_eq!(
tr.check_valid_at(&cussed_nougat),
Err(TimeValidityError::NotYetValid(4427 * one_day))
);
assert!(tr.check_valid_at(&today).is_ok());
}
#[test]
fn test_checking() {
let de = humantime::parse_rfc3339("1990-10-03T00:00:00Z").unwrap();
let cz_sk = humantime::parse_rfc3339("1993-01-01T00:00:00Z").unwrap();
let eu = humantime::parse_rfc3339("1993-11-01T00:00:00Z").unwrap();
let za = humantime::parse_rfc3339("1994-04-27T00:00:00Z").unwrap();
let tr = TimeRangeBound::new("Hello world", cz_sk..eu);
assert!(tr.if_valid_at(&za).is_err());
let tr = TimeRangeBound::new("Hello world", cz_sk..za);
assert_eq!(tr.if_valid_at(&eu), Ok("Hello world"));
#[allow(clippy::disallowed_methods)]
{
let tr = TimeRangeBound::new("hello world", de..);
assert_eq!(tr.if_valid_now(), Ok("hello world"));
let tr = TimeRangeBound::new("hello world", ..za);
assert!(tr.if_valid_now().is_err());
}
let tr = TimeRangeBound::new("hello world", de..);
#[allow(deprecated)]
{
assert_eq!(tr.check_valid_at_opt(None), Ok("hello world"));
let tr = TimeRangeBound::new("hello world", de..);
assert_eq!(
tr.check_valid_at_opt(Some(SystemTime::get())),
Ok("hello world")
);
let tr = TimeRangeBound::new("hello world", ..za);
assert!(tr.check_valid_at_opt(None).is_err());
}
let tr = TimeRangeBound::new("Hello world", de..eu);
let nano = Duration::from_nanos(1);
assert!(tr.check_valid_at(&(de - nano)).is_err());
assert!(tr.check_valid_at(&de).is_ok());
assert!(tr.check_valid_at(&(de + nano)).is_ok());
assert!(tr.check_valid_at(&(eu - nano)).is_ok());
assert!(tr.check_valid_at(&eu).is_ok());
assert!(tr.check_valid_at(&(eu + nano)).is_err());
}
#[test]
fn test_dangerous() {
let t1 = SystemTime::get();
let t2 = t1 + Duration::from_secs(60 * 525600);
let tr = TimeRangeBound::new("cups of coffee", t1..=t2);
assert_eq!(tr.dangerously_peek(), &"cups of coffee");
let (a, b) = tr.dangerously_into_parts();
assert_eq!(a, "cups of coffee");
assert_eq!(b.start(), Some(t1));
assert_eq!(b.end(), Some(t2));
}
#[test]
fn test_map() {
let t1 = SystemTime::get();
let min = Duration::from_secs(60);
let tb = TimeRangeBound::new(17_u32, t1..t1 + 5 * min);
let tb = tb.dangerously_map(|v| v * v);
assert!(tb.check_valid_at(&(t1 + 1 * min)).is_ok());
assert!(tb.check_valid_at(&(t1 + 10 * min)).is_err());
let val = tb.if_valid_at(&(t1 + 1 * min)).unwrap();
assert_eq!(val, 289);
}
#[test]
fn test_as_ref() {
let t1 = SystemTime::get();
let min = Duration::from_secs(60);
let tb1: TimeRangeBound<String> = TimeRangeBound::new("hi".into(), t1..t1 + 5 * min);
let tb2: TimeRangeBound<&String> = tb1.as_ref();
let tb3: TimeRangeBound<&str> = tb1.as_deref();
assert_eq!(tb1, tb2.dangerously_map(|s| s.clone()));
assert_eq!(tb1, tb3.dangerously_map(|s| s.to_owned()));
}
#[test]
fn test_intersect_bounds() {
let bounds = || {
chain!(
[None],
(0..=10)
.map(|days| {
parse_rfc3339("2000-01-01T00:00:01Z").unwrap()
+ Duration::from_secs(days * 86400)
})
.map(Some),
)
};
for a_start in bounds() {
for a_end in bounds() {
for b_start in bounds() {
for b_end in bounds() {
let mut a = TimeRange::new_from_start_end((), a_start, a_end);
let b = TimeRange::new_from_start_end((), b_start, b_end);
let exp = a.intersect(&b).map(TimeRange::new_range);
a.intersect_bounds(b);
if let Some(exp) = exp {
assert_eq!(a, exp);
} else {
assert!(a.start() > a.end());
}
}
}
}
}
}
}