af_core/time/
span.rs

1// Copyright © 2021 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use crate::prelude::*;
8
9/// An inclusive span between a start and end time.
10#[derive(Debug, Clone, Copy, Eq, PartialEq)]
11pub struct Span {
12  start: Time,
13  end: Time,
14}
15
16impl Span {
17  /// Creates a new span between two given times.
18  ///
19  /// The earlier time becomes the start time, and the later time becomes the
20  /// end time.
21  pub fn new(a: Time, b: Time) -> Self {
22    Self::from(a) + b
23  }
24
25  /// Returns `true` if a given time is contained with the span.
26  pub fn contains(&self, time: Time) -> bool {
27    time >= self.start && time <= self.end
28  }
29
30  /// Returns a [`Duration`] equal to the time span in length.
31  pub fn duration(&self) -> Duration {
32    self.end - self.start
33  }
34
35  /// Returns the end time of the span.
36  pub fn end(&self) -> Time {
37    self.end
38  }
39
40  /// Returns `true` if the span overlaps another given span.
41  pub fn overlaps(&self, rhs: Span) -> bool {
42    self.start <= rhs.end && rhs.start <= self.end
43  }
44
45  /// Returns the start time of the span.
46  pub fn start(&self) -> Time {
47    self.start
48  }
49}
50
51impl Add<Self> for Span {
52  type Output = Self;
53
54  fn add(mut self, rhs: Self) -> Self::Output {
55    self += rhs;
56    self
57  }
58}
59
60impl AddAssign<Self> for Span {
61  fn add_assign(&mut self, rhs: Self) {
62    self.start = cmp::min(self.start, rhs.start);
63    self.end = cmp::max(self.end, rhs.end);
64  }
65}
66
67impl Add<Time> for Span {
68  type Output = Self;
69
70  fn add(mut self, rhs: Time) -> Self::Output {
71    self += rhs;
72    self
73  }
74}
75
76impl AddAssign<Time> for Span {
77  fn add_assign(&mut self, rhs: Time) {
78    self.start = cmp::min(self.start, rhs);
79    self.end = cmp::max(self.end, rhs);
80  }
81}
82
83impl Display for Span {
84  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85    Display::fmt(&self.start, f)?;
86    write!(f, " — ")?;
87    Display::fmt(&self.end, f)
88  }
89}
90
91impl From<Time> for Span {
92  fn from(time: Time) -> Self {
93    Self { start: time, end: time }
94  }
95}
96
97impl From<Range<Time>> for Span {
98  fn from(range: Range<Time>) -> Self {
99    Self::new(range.start, range.end)
100  }
101}
102
103impl From<RangeInclusive<Time>> for Span {
104  fn from(range: RangeInclusive<Time>) -> Self {
105    let (start, end) = range.into_inner();
106
107    Self::new(start, end)
108  }
109}