Skip to content

Commit

Permalink
Merge pull request #16 from zcash/diversifier_index_ord
Browse files Browse the repository at this point in the history
Implement `{PartialOrd, Ord, Hash}` for `DiversifierIndex`
  • Loading branch information
nuttycom authored Sep 11, 2024
2 parents 5805178 + 38e39b7 commit ea6a62c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 29 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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));
}
}

0 comments on commit ea6a62c

Please sign in to comment.