Skip to content

Commit 6946495

Browse files
committed
Add ordering for Multihash and MultihashRef
This is just lexicographical byte ordering, which should be very fast in case of multihashes since they usually differ within the first 8 byte word. Ordering is useful to have if you e.g. want to output a set of multihashes in a deterministic way for debugging/testing purposes. Also, many possible storage engines work using lexicographical byte ordering.
1 parent 0ec803a commit 6946495

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/lib.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use unsigned_varint::{decode, encode};
2222

2323
pub use errors::{DecodeError, DecodeOwnedError, EncodeError};
2424
pub use hashes::Hash;
25-
use std::fmt;
25+
use std::{cmp, fmt};
2626
use storage::Storage;
2727

2828
// Helper macro for encoding input into output using sha1, sha2, tiny_keccak, or blake2
@@ -246,8 +246,14 @@ impl TryFrom<Vec<u8>> for Multihash {
246246
}
247247
}
248248

249+
impl PartialOrd for Multihash {
250+
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
251+
Some(self.as_ref().cmp(&other.as_ref()))
252+
}
253+
}
254+
249255
/// Represents a valid multihash.
250-
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
256+
#[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, Hash)]
251257
pub struct MultihashRef<'a> {
252258
bytes: &'a [u8],
253259
}
@@ -325,6 +331,12 @@ impl<'a> PartialEq<Multihash> for MultihashRef<'a> {
325331
}
326332
}
327333

334+
impl<'a> PartialOrd for MultihashRef<'a> {
335+
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
336+
Some(self.as_bytes().cmp(other.as_bytes()))
337+
}
338+
}
339+
328340
#[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
329341
fn as_u64(a: usize) -> u64 {
330342
a as u64

0 commit comments

Comments
 (0)