From 08da611448d6d234fb7912bd897031015db2c6f3 Mon Sep 17 00:00:00 2001 From: Richard Chien Date: Tue, 16 Jan 2024 18:08:47 +0800 Subject: [PATCH] feat(common): add `cmp_by` to `Sentinelled` (#14578) Signed-off-by: Richard Chien --- src/common/src/types/sentinel.rs | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/common/src/types/sentinel.rs b/src/common/src/types/sentinel.rs index 864ec4ca54d67..e220f1d210cca 100644 --- a/src/common/src/types/sentinel.rs +++ b/src/common/src/types/sentinel.rs @@ -37,6 +37,23 @@ impl Sentinelled { 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 PartialOrd for Sentinelled @@ -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) } }