Implement `{PartialOrd, Ord, Hash}` for `DiversifierIndex`

This commit is contained in:
Kris Nuttycombe 2024-03-15 09:17:12 -06:00
parent 5805178fc7
commit 38e39b7086
2 changed files with 32 additions and 1 deletions

View File

@ -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

View File

@ -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<DiversifierIndex> for u128 {
}
}
impl PartialOrd for DiversifierIndex {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
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));
}
}