Skip to content

Commit

Permalink
Merge pull request #39 from moia-oss/tw_overlap
Browse files Browse the repository at this point in the history
  • Loading branch information
urmaul authored Oct 13, 2023
2 parents 6fcc735 + 360df22 commit c69ee73
Showing 1 changed file with 58 additions and 1 deletion.
59 changes: 58 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
//! ```
use core::fmt;
use std::cmp::max;
use std::cmp::min;
use std::cmp::Ordering;
use std::error::Error;
use std::fmt::Debug;
Expand Down Expand Up @@ -551,7 +552,6 @@ impl TimeWindow {
/// # Examples
///
/// ```
/// # use tinytime::Time;
/// # use tinytime::TimeWindow;
/// let mut x = TimeWindow::from_seconds(5, 10);
/// assert!(x.overlaps(&TimeWindow::from_seconds(5, 10)));
Expand All @@ -568,6 +568,63 @@ impl TimeWindow {
self.start < that.end && that.start < self.end
}

/// Returns time window that is an intersection between this time window and
/// another one. Returns None if time windows don't overlap.
/// # Examples
///
/// ```
/// # use tinytime::TimeWindow;
/// let x = TimeWindow::from_seconds(5, 10);
/// assert_eq!(
/// Some(TimeWindow::from_seconds(5, 10)),
/// x.intersect(&TimeWindow::from_seconds(5, 10)),
/// "time windows are equal"
/// );
/// assert_eq!(
/// Some(TimeWindow::from_seconds(5, 10)),
/// x.intersect(&TimeWindow::from_seconds(3, 12)),
/// "that contains x"
/// );
/// assert_eq!(
/// Some(TimeWindow::from_seconds(6, 9)),
/// x.intersect(&TimeWindow::from_seconds(6, 9)),
/// "x contains that"
/// );
/// assert_eq!(
/// Some(TimeWindow::from_seconds(6, 10)),
/// x.intersect(&TimeWindow::from_seconds(6, 12))
/// );
/// assert_eq!(
/// Some(TimeWindow::from_seconds(5, 9)),
/// x.intersect(&TimeWindow::from_seconds(3, 9))
/// );
/// assert_eq!(
/// None,
/// x.intersect(&TimeWindow::from_seconds(1, 4)),
/// "that is before x"
/// );
/// assert_eq!(
/// Some(TimeWindow::from_seconds(5, 5)),
/// x.intersect(&TimeWindow::from_seconds(1, 5)),
/// "single-point intersection"
/// );
/// assert_eq!(
/// Some(TimeWindow::from_seconds(10, 10)),
/// x.intersect(&TimeWindow::from_seconds(10, 15)),
/// "single-point intersection"
/// );
/// assert_eq!(
/// None,
/// x.intersect(&TimeWindow::from_seconds(11, 15)),
/// "that is after x"
/// );
/// ```
pub fn intersect(&self, that: &TimeWindow) -> Option<TimeWindow> {
let start = max(self.start, that.start);
let end = min(self.end, that.end);
(start <= end).then(|| TimeWindow::new(start, end))
}

/// Shifts this time window by `duration` into the future. Affects both
/// `start` and `end` equally.
///
Expand Down

0 comments on commit c69ee73

Please sign in to comment.