use crate::{Bound, Step, UpperBound};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct UpperBoundedRange<T> {
pub end: UpperBound<T>,
}
impl<T> From<std::ops::RangeTo<T>> for UpperBoundedRange<T> {
fn from(r: std::ops::RangeTo<T>) -> Self {
Self {
end: UpperBound::excluded(r.end),
}
}
}
impl<T> From<std::ops::RangeToInclusive<T>> for UpperBoundedRange<T> {
fn from(r: std::ops::RangeToInclusive<T>) -> Self {
Self {
end: UpperBound::included(r.end),
}
}
}
impl<T> From<UpperBoundedRange<T>> for std::ops::RangeTo<T>
where
T: Copy + Step,
{
fn from(r: UpperBoundedRange<T>) -> Self {
match r.end.to_bound() {
Bound::Excluded(t) => ..t,
Bound::Included(t) => ..Step::forward(t, 1),
}
}
}
impl<T> From<UpperBoundedRange<T>> for std::ops::RangeToInclusive<T>
where
T: Copy + Step,
{
fn from(r: UpperBoundedRange<T>) -> Self {
match r.end.to_bound() {
Bound::Excluded(t) => ..=Step::backward(t, 1),
Bound::Included(t) => ..=t,
}
}
}
impl<T: Copy + Ord> UpperBoundedRange<T> {
pub fn new(end: UpperBound<T>) -> Self {
Self { end }
}
pub fn contains(&self, t: T) -> bool {
match self.end.0 {
Bound::Excluded(x) => t < x,
Bound::Included(i) => t <= i,
}
}
}