Skip to content

Commit f73a232

Browse files
committed
Add arbitraries
Both for internal purposes and for use by other crates
1 parent 2a6373e commit f73a232

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

Cargo.toml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,16 @@ sha-1 = { version = "0.8", default-features = false }
1818
sha2 = { version = "0.8", default-features = false }
1919
sha3 = { version = "0.8", default-features = false }
2020
unsigned-varint = "0.3"
21+
quickcheck = { version = "0.9.2", optional = true }
22+
rand = { version = "0.7.3", optional = true }
2123

2224
[dev-dependencies]
2325
criterion = "0.3"
24-
rand = "0.7"
2526
quickcheck = "0.9.2"
27+
rand = "0.7.3"
28+
29+
[features]
30+
test = ["quickcheck", "rand"]
2631

2732
[[bench]]
2833
name = "multihash"

src/arb.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
use crate::hashes::{Hash, Hash::*};
2+
use crate::{encode, Multihash};
3+
use quickcheck::{Arbitrary, Gen};
4+
use rand::seq::SliceRandom;
5+
6+
const HASHES: [Hash; 16] = [
7+
Identity, SHA1, SHA2256, SHA2512, SHA3512, SHA3384, SHA3256, SHA3224, Keccak224, Keccak256,
8+
Keccak384, Keccak512, Blake2b256, Blake2b512, Blake2s128, Blake2s256,
9+
];
10+
11+
/// Generates a random hash algorithm.
12+
///
13+
/// The more exotic ones will be generated just as frequently as the common ones.
14+
impl Arbitrary for Hash {
15+
fn arbitrary<G: Gen>(g: &mut G) -> Self {
16+
*HASHES.choose(g).unwrap()
17+
}
18+
}
19+
20+
/// Generates a random valid multihash.
21+
///
22+
/// This is done by encoding a random piece of data.
23+
impl Arbitrary for Multihash {
24+
fn arbitrary<G: Gen>(g: &mut G) -> Self {
25+
let hash: Hash = Arbitrary::arbitrary(g);
26+
let data: Vec<u8> = Arbitrary::arbitrary(g);
27+
// encoding an actual random piece of data might be better than just choosing
28+
// random numbers of the appropriate size, since some hash algos might produce
29+
// a limited set of values
30+
encode(hash, &data).unwrap()
31+
}
32+
}

src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ mod errors;
1313
mod hashes;
1414
mod storage;
1515

16+
#[cfg(any(test, feature = "test"))]
17+
mod arb;
18+
1619
pub use digests::{wrap, Multihash, MultihashDigest, MultihashRef};
1720
pub use errors::{DecodeError, DecodeOwnedError, EncodeError};
1821
pub use hashes::*;

0 commit comments

Comments
 (0)