Skip to content

Commit

Permalink
Adjust post review
Browse files Browse the repository at this point in the history
- rename Hash -> CanonicalSerialize Ext according to [extension trait best practices](https://rust-lang.github.io/rfcs/0445-extension-trait-conventions.html#the-convention)
- add the same structure for hashing uncompressed bytes
  • Loading branch information
huitseeker committed Apr 22, 2021
1 parent ffeaf83 commit 2afbe5c
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions serialize/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,17 +115,25 @@ impl<'a, H: Digest> ark_std::io::Write for HashMarshaller<'a, H> {

/// The CanonicalSerialize induces a natural way to hash the
/// corresponding value, of which this is the convenience trait.
pub trait Hash: CanonicalSerialize {
pub trait CanonicalSerializeHashExt: CanonicalSerialize {
fn hash<H: Digest>(&self) -> GenericArray<u8, <H as Digest>::OutputSize> {
let mut hasher = H::new();
self.serialize(HashMarshaller(&mut hasher))
.expect("HashMarshaller::flush should be infaillible!");
hasher.finalize()
}

fn hash_uncompressed<H: Digest>(&self) -> GenericArray<u8, <H as Digest>::OutputSize> {
let mut hasher = H::new();
self.serialize_uncompressed(HashMarshaller(&mut hasher))
.expect("HashMarshaller::flush should be infaillible!");
hasher.finalize()
}
}

/// Hash is a (blanket) extension trait of CanonicalSerialize
impl<T: CanonicalSerialize> Hash for T {}
/// CanonicalSerializeHashExt is a (blanket) extension trait of
/// CanonicalSerialize
impl<T: CanonicalSerialize> CanonicalSerializeHashExt for T {}

/// Deserializer in little endian format allowing flags to be encoded.
pub trait CanonicalDeserializeWithFlags: Sized {
Expand Down Expand Up @@ -940,6 +948,16 @@ mod test {
let h2 = hash.finalize();

assert_eq!(h1, h2);

let h3 = data.hash_uncompressed::<H>();

let mut hash = H::new();
serialized = vec![0; data.uncompressed_size()];
data.serialize_uncompressed(&mut serialized[..]).unwrap();
hash.update(&serialized);
let h4 = hash.finalize();

assert_eq!(h3, h4);
}

// Serialize T, randomly mutate the data, and deserialize it.
Expand Down

0 comments on commit 2afbe5c

Please sign in to comment.