diff --git a/Cargo.toml b/Cargo.toml index 7e310026..d7f5ae07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,11 +18,16 @@ sha-1 = { version = "0.8", default-features = false } sha2 = { version = "0.8", default-features = false } sha3 = { version = "0.8", default-features = false } unsigned-varint = "0.3" +quickcheck = { version = "0.9.2", optional = true } +rand = { version = "0.7.3", optional = true } [dev-dependencies] criterion = "0.3" -rand = "0.7" quickcheck = "0.9.2" +rand = "0.7.3" + +[features] +test = ["quickcheck", "rand"] [[bench]] name = "multihash" diff --git a/src/arb.rs b/src/arb.rs new file mode 100644 index 00000000..f645e2ba --- /dev/null +++ b/src/arb.rs @@ -0,0 +1,31 @@ +use crate::{Code, Code::*, Multihash}; +use quickcheck::{Arbitrary, Gen}; +use rand::seq::SliceRandom; + +const HASHES: [Code; 16] = [ + Identity, Sha1, Sha2_256, Sha2_512, Sha3_512, Sha3_384, Sha3_256, Sha3_224, Keccak224, + Keccak256, Keccak384, Keccak512, Blake2b256, Blake2b512, Blake2s128, Blake2s256, +]; + +/// Generates a random hash algorithm. +/// +/// The more exotic ones will be generated just as frequently as the common ones. +impl Arbitrary for Code { + fn arbitrary(g: &mut G) -> Self { + *HASHES.choose(g).unwrap() + } +} + +/// Generates a random valid multihash. +/// +/// This is done by encoding a random piece of data. +impl Arbitrary for Multihash { + fn arbitrary(g: &mut G) -> Self { + let code: Code = Arbitrary::arbitrary(g); + let data: Vec = Arbitrary::arbitrary(g); + // encoding an actual random piece of data might be better than just choosing + // random numbers of the appropriate size, since some hash algos might produce + // a limited set of values + code.hasher().unwrap().digest(&data) + } +} diff --git a/src/lib.rs b/src/lib.rs index afd6cdbc..14bacd07 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,6 +13,9 @@ mod errors; mod hashes; mod storage; +#[cfg(any(test, feature = "test"))] +mod arb; + pub use digests::{wrap, Multihash, MultihashDigest, MultihashRef}; pub use errors::{DecodeError, DecodeOwnedError, EncodeError}; pub use hashes::*;