Trait merkletree::hash::Hashable
source · pub trait Hashable<H: Hasher> {
// Required method
fn hash(&self, state: &mut H);
// Provided method
fn hash_slice(data: &[Self], state: &mut H)
where Self: Sized { ... }
}
Expand description
A hashable type.
Types implementing Hashable
are able to be [hash
]ed with an instance of
Hasher
.
§Implementing Hashable
You can derive Hashable
with #[derive(Hashable)]
if all fields implement Hashable
.
The resulting hash will be the combination of the values from calling
[hash
] on each field.
#[macro_use]
extern crate merkletree_derive;
extern crate merkletree;
use merkletree::hash::Hashable;
fn main() {
#[derive(Hashable)]
struct Foo {
name: String,
country: String,
}
}
If you need more control over how a value is hashed, you can of course
implement the Hashable
trait yourself:
extern crate merkletree;
use merkletree::hash::Hashable;
use std::hash::Hasher;
use std::collections::hash_map::DefaultHasher;
fn main() {
struct Person {
id: u32,
name: String,
phone: u64,
}
impl<H: Hasher> Hashable<H> for Person {
fn hash(&self, state: &mut H) {
self.id.hash(state);
self.name.hash(state);
self.phone.hash(state);
}
}
let foo = Person{
id: 1,
name: String::from("blah"),
phone: 2,
};
let mut hr = DefaultHasher::new();
foo.hash(&mut hr);
assert_eq!(hr.finish(), 7101638158313343130)
}
§Hashable
and Eq
When implementing both Hashable
and Eq
, it is important that the following
property holds:
k1 == k2 -> hash(k1) == hash(k2)
In other words, if two keys are equal, their hashes must also be equal.