Skip to content

Commit

Permalink
Merge pull request #44 from moia-oss/tw_shrink
Browse files Browse the repository at this point in the history
  • Loading branch information
urmaul authored Oct 17, 2023
2 parents 5c88008 + 6375c8a commit 7bbd1ae
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,75 @@ impl TimeWindow {
}
}

/// Postpones the time window start so that the new duration matches the
/// given value. Is a No-Op if the new duration is smaller than the
/// current one. Negative durations set the result time window size to
/// zero.
///
/// # Examples
/// ```
/// # use tinytime::Duration;
/// # use tinytime::TimeWindow;
/// let x = TimeWindow::from_seconds(1, 3);
/// assert_eq!(
/// TimeWindow::from_seconds(3, 3),
/// x.shrink_towards_end_to(Duration::seconds(-1))
/// );
/// assert_eq!(
/// TimeWindow::from_seconds(3, 3),
/// x.shrink_towards_end_to(Duration::seconds(0))
/// );
/// assert_eq!(
/// TimeWindow::from_seconds(2, 3),
/// x.shrink_towards_end_to(Duration::seconds(1))
/// );
/// assert_eq!(
/// TimeWindow::from_seconds(1, 3),
/// x.shrink_towards_end_to(Duration::seconds(5))
/// );
/// ```
pub fn shrink_towards_end_to(self, new_duration: Duration) -> TimeWindow {
let duration = new_duration
.min(self.duration()) // Resize only if new duration is smaller than the current one
.max(Duration::ZERO); // Make sure the new duration is non-negative

TimeWindow::from_end(duration, self.end)
}

/// Prepones the time window end so that the new duration matches the given
/// value. Is a No-Op if the new duration is smaller than the current
/// one. Negative durations set the result time window size to zero.
///
/// # Examples
/// ```
/// # use tinytime::Duration;
/// # use tinytime::TimeWindow;
/// let x = TimeWindow::from_seconds(1, 3);
/// assert_eq!(
/// TimeWindow::from_seconds(1, 1),
/// x.shrink_towards_start_to(Duration::seconds(-1))
/// );
/// assert_eq!(
/// TimeWindow::from_seconds(1, 1),
/// x.shrink_towards_start_to(Duration::seconds(0))
/// );
/// assert_eq!(
/// TimeWindow::from_seconds(1, 2),
/// x.shrink_towards_start_to(Duration::seconds(1))
/// );
/// assert_eq!(
/// TimeWindow::from_seconds(1, 3),
/// x.shrink_towards_start_to(Duration::seconds(5))
/// );
/// ```
pub fn shrink_towards_start_to(self, new_duration: Duration) -> TimeWindow {
let duration = new_duration
.min(self.duration()) // Resize only if new duration is smaller than the current one
.max(Duration::ZERO); // Make sure the new duration is non-negative

TimeWindow::from_duration(self.start, duration)
}

/// Returns true if this time window contains the given time.
/// # Examples
///
Expand Down

0 comments on commit 7bbd1ae

Please sign in to comment.