Skip to content

Commit

Permalink
add a pub method cmp_by to Sentinelled<T> for convenience
Browse files Browse the repository at this point in the history
Signed-off-by: Richard Chien <[email protected]>
  • Loading branch information
stdrc committed Jan 15, 2024
1 parent abfee42 commit 8019754
Showing 1 changed file with 18 additions and 10 deletions.
28 changes: 18 additions & 10 deletions src/common/src/types/sentinel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@ impl<T> Sentinelled<T> {
pub fn is_sentinel(&self) -> bool {
matches!(self, Self::Smallest | Self::Largest)
}

pub fn cmp_by(
&self,
other: &Self,
cmp_fn: impl FnOnce(&T, &T) -> std::cmp::Ordering,
) -> std::cmp::Ordering {
use Sentinelled::*;
match (self, other) {
(Smallest, Smallest) => std::cmp::Ordering::Equal,
(Smallest, _) => std::cmp::Ordering::Less,
(_, Smallest) => std::cmp::Ordering::Greater,
(Largest, Largest) => std::cmp::Ordering::Equal,
(Largest, _) => std::cmp::Ordering::Greater,
(_, Largest) => std::cmp::Ordering::Less,
(Normal(a), Normal(b)) => cmp_fn(a, b),
}
}
}

impl<T> PartialOrd for Sentinelled<T>
Expand All @@ -53,16 +70,7 @@ where
T: Ord,
{
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
use Sentinelled::*;
match (self, other) {
(Smallest, Smallest) => std::cmp::Ordering::Equal,
(Smallest, _) => std::cmp::Ordering::Less,
(_, Smallest) => std::cmp::Ordering::Greater,
(Largest, Largest) => std::cmp::Ordering::Equal,
(Largest, _) => std::cmp::Ordering::Greater,
(_, Largest) => std::cmp::Ordering::Less,
(Normal(a), Normal(b)) => a.cmp(b),
}
self.cmp_by(other, T::cmp)
}
}

Expand Down

0 comments on commit 8019754

Please sign in to comment.