From 38e39b7086bbd5747dc61a84faf54ec9a58fa535 Mon Sep 17 00:00:00 2001 From: Kris Nuttycombe Date: Fri, 15 Mar 2024 09:17:12 -0600 Subject: [PATCH] Implement `{PartialOrd, Ord, Hash}` for `DiversifierIndex` --- CHANGELOG.md | 3 +++ src/lib.rs | 30 +++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43a4030..63af005 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this library adheres to Rust's notion of ## [Unreleased] +### Added +- `impl {PartialOrd, Ord, Hash}` for `zip32::DiversifierIndex` + ## [0.1.1] - 2024-03-14 ### Added diff --git a/src/lib.rs b/src/lib.rs index 68aed68..f0122c4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -149,7 +149,7 @@ impl ChainCode { } /// The index for a particular diversifier. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct DiversifierIndex([u8; 11]); impl Default for DiversifierIndex { @@ -214,6 +214,26 @@ impl From for u128 { } } +impl PartialOrd for DiversifierIndex { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for DiversifierIndex { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + self.0 + .iter() + .rev() + .zip(other.0.iter().rev()) + .find_map(|(a, b)| match a.cmp(b) { + core::cmp::Ordering::Equal => None, + ineq => Some(ineq), + }) + .unwrap_or(core::cmp::Ordering::Equal) + } +} + impl DiversifierIndex { /// Constructs the zero index. pub fn new() -> Self { @@ -375,4 +395,12 @@ mod tests { assert_matches!(di.increment(), Err(_)); } + + #[test] + fn diversifier_index_ord() { + assert!(DiversifierIndex::from(1u64) < DiversifierIndex::from(2u64)); + assert!(DiversifierIndex::from(u64::MAX - 1) < DiversifierIndex::from(u64::MAX)); + assert!(DiversifierIndex::from(3u64) == DiversifierIndex::from(3u64)); + assert!(DiversifierIndex::from(u64::MAX) == DiversifierIndex::from(u64::MAX)); + } }