feat: add fallible conversion to Range and len_ranges method (#15)

This commit is contained in:
sinu.eth
2024-01-30 11:13:11 -08:00
committed by GitHub
parent 85f498e98a
commit c9a8c0b5a5

View File

@@ -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))
@@ -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() {