A content hash algorithm which works across multiple encodings (JSON, Protobufs, etc).
This crate provides a Rust implementation of an algorithm originally created by Ben Laurie.
You will need to select a supported cryptography library to use as ObjectHash's backend. The following backend libraries are supported:
Please make sure to add a crypto backend crate or the objecthash
crate will not work!
ObjectHashes can be used to compute a content hash of a deeply nested structure. The intended use is to first deserialize data into a nested structure, then perform an ObjectHash digest of its contents. This way, the same content hash to be computed regardless of how the data is serialized, which allows the data to be transcoded between formats without having to recompute the content hash.
This crate defines a trait called ObjectHash:
rust
pub trait ObjectHash {
fn objecthash<H: ObjectHasher>(&self, hasher: &mut H);
}
There are built-in implementations of the ObjectHash
trait for the
following types:
Vec<T: ObjectHash>
HashMap<K: ObjectHash, V: ObjectHash>
str
String
i8
i16
i32
i64
u8
u16
u32
u64
isize
usize
To calculate the ObjectHash digest of some data, call the following:
rust
let digest: Vec<u8> = objecthash::digest(42);
This will compute a digest (using the SHA-256 algorithm) of the given value, provided the type of the value given implements the ObjectHash trait.
The objecthash_struct!
macro is designed to simplify implementing the ObjectHash trait on structs, producing
a dict-type hash across their keys and values:
rust
impl ObjectHash for MyStruct {
#[inline]
fn objecthash<H: ObjectHasher>(&self, hasher: &mut H) {
objecthash_struct!(
hasher,
"foo" => self.foo,
"bar" => self.bar,
"baz" => self.baz
)
}
}
Copyright (c) 2016 Tony Arcieri. Distributed under the Apache 2.0 License. See LICENSE file for further details.