rangetools/
upper_bounded_range.rs1use crate::{Bound, Step, UpperBound};
2#[cfg(feature = "serde")]
3use serde::{Deserialize, Serialize};
4
5#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
18#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
19pub struct UpperBoundedRange<T> {
20 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 pub fn new(end: UpperBound<T>) -> Self {
75 Self { end }
76 }
77
78 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}