use joda_rs::{Duration, LocalDate, LocalDateTime, LocalTime};
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
#[derive(Debug, Clone)]
pub struct DateTimeRange {
start: LocalDateTime,
end: LocalDateTime,
}
impl DateTimeRange {
pub fn of(start: LocalDateTime, end: LocalDateTime) -> Self {
Self { start, end }
}
pub fn from_time_range_on_date(start_time: LocalTime, end_time: LocalTime, date: LocalDate) -> Self {
if end_time < start_time {
Self {
start: date.at_time(start_time),
end: date.plus_days(1).at_time(end_time),
}
} else {
Self {
start: date.at_time(start_time),
end: date.at_time(end_time),
}
}
}
pub fn all_day(date: LocalDate) -> Self {
Self {
start: date.at_start_of_day(),
end: date.plus_days(1).at_start_of_day(),
}
}
pub fn start(&self) -> LocalDateTime {
self.start
}
pub fn end(&self) -> LocalDateTime {
self.end
}
pub fn duration(&self) -> Duration {
self.end - self.start
}
pub fn overlaps(&self, other: &DateTimeRange) -> bool {
self.start <= other.end && self.end >= other.start
}
pub fn overlaps_exclusive(&self, other: &DateTimeRange) -> bool {
self.start < other.end && self.end > other.start
}
pub fn overlaps_completely(&self, other: &DateTimeRange) -> bool {
other.start >= self.start && other.end <= self.end
}
pub fn overlap_duration(&self, other: &DateTimeRange) -> Duration {
self.overlap_range(other)
.map(|r| r.duration())
.unwrap_or_else(|| Duration::of_seconds(0))
}
pub fn overlap_range(&self, other: &DateTimeRange) -> Option<DateTimeRange> {
if !self.overlaps(other) {
return None;
}
let start = self.start.max(other.start);
let end = self.end.min(other.end);
Some(Self::of(start, end))
}
pub fn contains(&self, dt: LocalDateTime) -> bool {
dt >= self.start && dt <= self.end
}
pub fn contains_exclusive(&self, dt: LocalDateTime) -> bool {
dt > self.start && dt < self.end
}
}
impl PartialEq for DateTimeRange {
fn eq(&self, other: &Self) -> bool {
self.start == other.start && self.end == other.end
}
}
impl Eq for DateTimeRange {}
impl Hash for DateTimeRange {
fn hash<H: Hasher>(&self, state: &mut H) {
self.start.hash(state);
self.end.hash(state);
}
}
impl PartialOrd for DateTimeRange {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for DateTimeRange {
fn cmp(&self, other: &Self) -> Ordering {
match self.start.cmp(&other.start) {
Ordering::Equal => self.end.cmp(&other.end),
ord => ord,
}
}
}
pub trait PeriodIndexing {
fn start_index(&self) -> i32;
fn end_index(&self) -> i32;
fn index_range(&self) -> (i32, i32);
fn number_of_periods(&self) -> i32;
fn period_length_in_minutes(&self) -> i32;
}
pub trait PeriodIteration {
type Item;
type Iter: Iterator<Item = Self::Item>;
fn iter(&self) -> Self::Iter;
}
const MINUTES_PER_HOUR: i32 = 60;
const MINUTES_PER_DAY: i32 = 1440;
#[derive(Debug, Copy, Clone)]
pub struct WithPeriod<'a> {
range: &'a DateTimeRange,
period_length_minutes: i32,
}
impl DateTimeRange {
pub fn with_period_len(&self, period_length_minutes: i32) -> WithPeriod<'_> {
WithPeriod { range: self, period_length_minutes }
}
}
pub struct DateTimeRangeIterator {
current: LocalDateTime,
end: LocalDateTime,
step_minutes: i32,
}
impl DateTimeRangeIterator {
fn new(range: &DateTimeRange, period_minutes: i32) -> Self {
Self {
current: range.start(),
end: range.end(),
step_minutes: period_minutes,
}
}
}
impl Iterator for DateTimeRangeIterator {
type Item = LocalDateTime;
fn next(&mut self) -> Option<Self::Item> {
if self.current > self.end {
None
} else {
let result = self.current;
self.current = self.current.plus_minutes(self.step_minutes as i64);
Some(result)
}
}
}
impl<'a> WithPeriod<'a> {
pub fn date_time_range(&self) -> &DateTimeRange { self.range }
pub fn start_index(&self) -> i32 {
let st = self.range.start();
let st_time = st.to_local_time();
let minutes_from_midnight = st_time.hour() as i32 * MINUTES_PER_HOUR + st_time.minute() as i32;
minutes_from_midnight / self.period_length_minutes
}
pub fn end_index(&self) -> i32 {
let sd = self.range.start();
let ed = self.range.end();
let sd_date = sd.to_local_date();
let ed_date = ed.to_local_date();
let ed_time = ed.to_local_time();
let mut end_index = ed_time.hour() as i32 * MINUTES_PER_HOUR + ed_time.minute() as i32;
if ed_date > sd_date {
end_index += MINUTES_PER_DAY;
}
end_index / self.period_length_minutes
}
pub fn index_range(&self) -> (i32, i32) { (self.start_index(), self.end_index() - 1) }
pub fn number_of_periods(&self) -> i32 {
let mut count = 0;
let mut t = self.range.start();
let step = self.period_length_minutes as i64;
while t.plus_minutes(step) <= self.range.end() {
count += 1;
t = t.plus_minutes(step);
}
count
}
pub fn period_length_in_minutes(&self) -> i32 { self.period_length_minutes }
}
impl<'a> PeriodIndexing for WithPeriod<'a> {
fn start_index(&self) -> i32 { Self::start_index(self) }
fn end_index(&self) -> i32 { Self::end_index(self) }
fn index_range(&self) -> (i32, i32) { Self::index_range(self) }
fn number_of_periods(&self) -> i32 { Self::number_of_periods(self) }
fn period_length_in_minutes(&self) -> i32 { Self::period_length_in_minutes(self) }
}
impl<'a> PeriodIteration for WithPeriod<'a> {
type Item = LocalDateTime;
type Iter = DateTimeRangeIterator;
fn iter(&self) -> Self::Iter {
DateTimeRangeIterator::new(self.range, self.period_length_minutes)
}
}
#[cfg(test)]
mod tests {
use super::DateTimeRange;
use joda_rs::{Duration, LocalDate, LocalDateTime, LocalTime};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn d(y: i32, m: i32, day: i32) -> LocalDate {
LocalDate::of(y, m, day)
}
fn t(h: i32, m: i32, s: i32) -> LocalTime {
LocalTime::of(h, m, s)
}
fn dt(y: i32, m: i32, day: i32, h: i32, mi: i32, s: i32) -> LocalDateTime {
LocalDateTime::of(y, m, day, h, mi, s)
}
#[test]
fn of_constructs_and_duration_is_end_minus_start() {
let start = dt(2023, 3, 10, 8, 30, 0);
let end = dt(2023, 3, 10, 17, 0, 0);
let r = DateTimeRange::of(start, end);
assert_eq!(r.start(), start);
assert_eq!(r.end(), end);
assert_eq!(r.duration(), Duration::of_seconds(8*3600 + 30*60));
}
#[test]
fn from_time_range_on_date_same_day_and_cross_midnight() {
let r1 = DateTimeRange::from_time_range_on_date(t(9, 0, 0), t(17, 0, 0), d(2023, 3, 1));
assert_eq!(r1.start(), dt(2023, 3, 1, 9, 0, 0));
assert_eq!(r1.end(), dt(2023, 3, 1, 17, 0, 0));
assert_eq!(r1.duration(), Duration::of_seconds(8*3600));
let r2 = DateTimeRange::from_time_range_on_date(t(22, 0, 0), t(6, 0, 0), d(2023, 3, 1));
assert_eq!(r2.start(), dt(2023, 3, 1, 22, 0, 0));
assert_eq!(r2.end(), dt(2023, 3, 2, 6, 0, 0));
assert_eq!(r2.duration(), Duration::of_seconds(8*3600));
}
#[test]
fn all_day_builds_midnight_to_next_midnight_24h() {
let r = DateTimeRange::all_day(d(2024, 2, 29)); assert_eq!(r.start(), dt(2024, 2, 29, 0, 0, 0));
assert_eq!(r.end(), dt(2024, 3, 1, 0, 0, 0));
assert_eq!(r.duration(), Duration::of_seconds(24*3600));
}
#[test]
fn contains_and_contains_exclusive_respect_boundaries() {
let r = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 17, 0, 0));
assert!(r.contains(dt(2023, 1, 1, 9, 0, 0))); assert!(r.contains(dt(2023, 1, 1, 17, 0, 0))); assert!(r.contains_exclusive(dt(2023, 1, 1, 12, 0, 0)));
assert!(!r.contains_exclusive(dt(2023, 1, 1, 9, 0, 0)));
assert!(!r.contains_exclusive(dt(2023, 1, 1, 17, 0, 0)));
}
#[test]
fn overlaps_variants_and_overlap_range_duration() {
let a = DateTimeRange::of(dt(2023, 5, 10, 9, 0, 0), dt(2023, 5, 10, 12, 0, 0));
let b = DateTimeRange::of(dt(2023, 5, 10, 11, 0, 0), dt(2023, 5, 10, 13, 0, 0));
let c_touch_right = DateTimeRange::of(dt(2023, 5, 10, 12, 0, 0), dt(2023, 5, 10, 14, 0, 0));
let d_disjoint = DateTimeRange::of(dt(2023, 5, 10, 14, 0, 1), dt(2023, 5, 10, 15, 0, 0));
assert!(a.overlaps(&b));
assert!(a.overlaps(&c_touch_right)); assert!(!a.overlaps(&d_disjoint));
assert!(a.overlaps_exclusive(&b));
assert!(!a.overlaps_exclusive(&c_touch_right));
let inner = DateTimeRange::of(dt(2023, 5, 10, 9, 30, 0), dt(2023, 5, 10, 11, 0, 0));
assert!(a.overlaps_completely(&inner));
assert!(!inner.overlaps_completely(&a));
let r = a.overlap_range(&b).unwrap();
assert_eq!(r.start(), dt(2023, 5, 10, 11, 0, 0));
assert_eq!(r.end(), dt(2023, 5, 10, 12, 0, 0));
assert_eq!(a.overlap_duration(&b), Duration::of_seconds(3600));
let r2 = a.overlap_range(&c_touch_right).unwrap();
assert_eq!(r2.start(), dt(2023, 5, 10, 12, 0, 0));
assert_eq!(r2.end(), dt(2023, 5, 10, 12, 0, 0));
assert_eq!(a.overlap_duration(&c_touch_right), Duration::of_seconds(0));
assert!(a.overlap_range(&d_disjoint).is_none());
assert_eq!(a.overlap_duration(&d_disjoint), Duration::of_seconds(0));
}
#[test]
fn ordering_and_equality_and_hash() {
let a = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 10, 0, 0));
let b = DateTimeRange::of(dt(2023, 1, 1, 8, 0, 0), dt(2023, 1, 1, 9, 30, 0));
let c = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 10, 0, 0));
let d_shorter_end = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 9, 30, 0));
let e_longer_end = DateTimeRange::of(dt(2023, 1, 1, 9, 0, 0), dt(2023, 1, 1, 10, 30, 0));
assert_eq!(a, c);
assert_ne!(a, b);
let mut v = vec![a.clone(), b.clone()];
v.sort();
assert_eq!(v, vec![b, a.clone()]);
assert!(d_shorter_end < a); assert!(e_longer_end > a);
let mut ha = DefaultHasher::new();
let mut hc = DefaultHasher::new();
a.hash(&mut ha);
c.hash(&mut hc);
assert_eq!(ha.finish(), hc.finish());
}
#[test]
fn with_period_indexing_and_iteration_behave_like_previous_type() {
use super::PeriodIteration;
let r = DateTimeRange::of(dt(2023, 5, 1, 9, 15, 0), dt(2023, 5, 1, 16, 45, 0));
let w = r.with_period_len(60);
assert_eq!(w.start_index(), 9); assert_eq!(w.end_index(), 16); assert_eq!(w.index_range(), (9, 15));
assert_eq!(w.number_of_periods(), 7); assert_eq!(w.period_length_in_minutes(), 60);
let via_iter: Vec<_> = w.iter().collect();
assert_eq!(via_iter.first().copied().unwrap(), dt(2023,5,1,9,15,0));
assert_eq!(via_iter.last().copied().unwrap(), dt(2023,5,1,16,15,0));
}
}