Skip to content

Commit 2f8f5d7

Browse files
committed
from and as RangeBounds
1 parent a2d2c65 commit 2f8f5d7

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/range.rs

+43
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
1717
use std::cmp::Ordering;
1818
use std::fmt;
19+
use std::ops::{Bound, RangeBounds};
1920

2021
use crate::internal::small_vec::SmallVec;
2122
use crate::version::Version;
@@ -85,6 +86,31 @@ impl<V: Version> Range<V> {
8586
Self::none()
8687
}
8788
}
89+
90+
/// Construct a simple range from anything that impls `RangeBounds` like `v1..v2`
91+
pub fn from_range_bounds<'a, R, IV: 'a>(bounds: &'a R) -> Self
92+
where
93+
R: RangeBounds<IV>,
94+
&'a IV: Into<V>,
95+
{
96+
let start = match bounds.start_bound() {
97+
Bound::Included(s) => s.into(),
98+
Bound::Excluded(s) => s.into().bump(),
99+
Bound::Unbounded => V::lowest(),
100+
};
101+
let end = match bounds.end_bound() {
102+
Bound::Included(e) => Some(e.into().bump()),
103+
Bound::Excluded(e) => Some(e.into()),
104+
Bound::Unbounded => None,
105+
};
106+
if end.is_some() && end.as_ref() <= Some(&start) {
107+
Self::none()
108+
} else {
109+
Self {
110+
segments: SmallVec::one((start, end)),
111+
}
112+
}
113+
}
88114
}
89115

90116
// Set operations.
@@ -260,6 +286,23 @@ impl<V: Version> Range<V> {
260286
pub fn lowest_version(&self) -> Option<V> {
261287
self.segments.first().map(|(start, _)| start).cloned()
262288
}
289+
290+
/// Conver to somthing that can be used with BTreeMap::range
291+
/// All versions contained in self, will be in the output,
292+
/// but there may be versions in the output that are not contained in self.
293+
/// returns None if the range is empty.
294+
pub fn as_range_bounds(&self) -> Option<impl RangeBounds<&V>> {
295+
self.segments.first().map(|(start, _)| {
296+
let end = {
297+
self.segments
298+
.last()
299+
.and_then(|(_, l)| l.as_ref())
300+
.map(Bound::Excluded)
301+
.unwrap_or(Bound::Unbounded)
302+
};
303+
(Bound::Included(start), end)
304+
})
305+
}
263306
}
264307

265308
// REPORT ######################################################################

0 commit comments

Comments
 (0)