rangetools/
upper_bounded_range.rs

1use crate::{Bound, Step, UpperBound};
2#[cfg(feature = "serde")]
3use serde::{Deserialize, Serialize};
4
5/// A range only bounded above (either inclusive or exclusive).
6///
7/// Generalizes over [`std::ops::RangeTo`] and [`std::ops::RangeToInclusive`].
8///
9/// While an `UpperoundedRange` can be constructed directly, it will most likely
10/// result from one or more range operations.
11/// ```
12/// use rangetools::{Rangetools, UpperBound, UpperBoundedRange};
13///
14/// let i = (..5).intersection(..=3);
15/// assert_eq!(i, UpperBoundedRange { end: UpperBound::included(3) });
16/// ```
17#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
18#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
19pub struct UpperBoundedRange<T> {
20    /// The upper bound of the range (can be inclusive or exclusive).
21    pub end: UpperBound<T>,
22}
23
24impl<T> From<std::ops::RangeTo<T>> for UpperBoundedRange<T> {
25    fn from(r: std::ops::RangeTo<T>) -> Self {
26        Self {
27            end: UpperBound::excluded(r.end),
28        }
29    }
30}
31
32impl<T> From<std::ops::RangeToInclusive<T>> for UpperBoundedRange<T> {
33    fn from(r: std::ops::RangeToInclusive<T>) -> Self {
34        Self {
35            end: UpperBound::included(r.end),
36        }
37    }
38}
39
40impl<T> From<UpperBoundedRange<T>> for std::ops::RangeTo<T>
41where
42    T: Copy + Step,
43{
44    fn from(r: UpperBoundedRange<T>) -> Self {
45        match r.end.to_bound() {
46            Bound::Excluded(t) => ..t,
47            Bound::Included(t) => ..Step::forward(t, 1),
48        }
49    }
50}
51
52impl<T> From<UpperBoundedRange<T>> for std::ops::RangeToInclusive<T>
53where
54    T: Copy + Step,
55{
56    fn from(r: UpperBoundedRange<T>) -> Self {
57        match r.end.to_bound() {
58            Bound::Excluded(t) => ..=Step::backward(t, 1),
59            Bound::Included(t) => ..=t,
60        }
61    }
62}
63
64impl<T: Copy + Ord> UpperBoundedRange<T> {
65    /// Constructs a new `UpperBoundedRange` from an upper bound.
66    ///
67    /// # Example
68    /// ```
69    /// use rangetools::{UpperBound, UpperBoundedRange};
70    ///
71    /// let r = UpperBoundedRange::new(UpperBound::included(10));
72    /// assert!(r.contains(5));
73    /// ```
74    pub fn new(end: UpperBound<T>) -> Self {
75        Self { end }
76    }
77
78    /// Returns true if the range contains `t`.
79    ///
80    /// # Example
81    /// ```
82    /// use rangetools::Rangetools;
83    ///
84    /// let i = (..5).intersection(..10);
85    /// assert!(i.contains(4));
86    /// assert!(!i.contains(9));
87    /// ```
88    pub fn contains(&self, t: T) -> bool {
89        match self.end.0 {
90            Bound::Excluded(x) => t < x,
91            Bound::Included(i) => t <= i,
92        }
93    }
94}