Skip to content

Commit

Permalink
range: make 'as_singleton' return a borrow
Browse files Browse the repository at this point in the history
It's cheaper this way if the caller only needs a `&V`. If the caller
needs a `V`, then they can clone it.

We can also move it to an impl block that only requires `Ord`, so that
it will work with `V` types that don't implement `Clone`.
  • Loading branch information
BurntSushi committed Feb 8, 2024
1 parent 1b150cd commit 5048817
Showing 1 changed file with 16 additions and 16 deletions.
32 changes: 16 additions & 16 deletions src/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,21 @@ impl<V: Clone> Range<V> {
}

impl<V: Ord> Range<V> {
/// If the range includes a single version, return it.
/// Otherwise, returns [None].
pub fn as_singleton(&self) -> Option<&V> {
match self.segments.as_slice() {
[(Included(v1), Included(v2))] => {
if v1 == v2 {
Some(v1)
} else {
None
}
}
_ => None,
}
}

/// Convert to something that can be used with
/// [BTreeMap::range](std::collections::BTreeMap::range).
/// All versions contained in self, will be in the output,
Expand Down Expand Up @@ -454,7 +469,7 @@ impl<V: Ord + Clone> Range<V> {
{
// Do not simplify singletons
if let Some(version) = self.as_singleton() {
return Self::singleton(version);
return Self::singleton(version.clone());
}

// Return the segment index in the range for each version in the range, None otherwise
Expand Down Expand Up @@ -496,21 +511,6 @@ impl<V: Ord + Clone> Range<V> {
Self { segments }.check_invariants()
}

/// If the range includes a single version, return it.
/// Otherwise, returns [None].
pub fn as_singleton(&self) -> Option<V> {
match self.segments.as_slice() {
[(Included(v1), Included(v2))] => {
if v1 == v2 {
Some(v1.clone())
} else {
None
}
}
_ => None,
}
}

/// Iterate over the parts of the range.
pub fn iter(&self) -> impl Iterator<Item = &(Bound<V>, Bound<V>)> {
self.segments.iter()
Expand Down

0 comments on commit 5048817

Please sign in to comment.