Skip to content

Commit

Permalink
feat: add fallible conversion to Range and len_ranges method (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
sinui0 authored Jan 30, 2024
1 parent 85f498e commit c9a8c0b
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions utils/src/range/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ impl<T: Copy + Ord> RangeSet<T> {
}
}

/// Returns the number of ranges in the set.
pub fn len_ranges(&self) -> usize {
self.ranges.len()
}

/// Returns `true` if the set contains the given value.
pub fn contains(&self, value: &T) -> bool {
self.ranges.iter().any(|range| range.contains(value))
Expand Down Expand Up @@ -222,6 +227,20 @@ where
}
}

impl<T: Copy + Ord> TryFrom<RangeSet<T>> for Range<T> {
type Error = RangeSet<T>;

/// Attempts to convert a `RangeSet` into a single `Range`, returning the set if it
/// does not contain exactly one range.
fn try_from(set: RangeSet<T>) -> Result<Self, Self::Error> {
if set.len_ranges() == 1 {
Ok(set.ranges.into_iter().next().unwrap())
} else {
Err(set)
}
}
}

impl<T: Copy + Ord> From<Range<T>> for RangeSet<T> {
fn from(range: Range<T>) -> Self {
if range.is_empty() {
Expand Down

0 comments on commit c9a8c0b

Please sign in to comment.