Skip to content

Commit 79af27a

Browse files
Expand on DynDigest example in README (#390)
1 parent e5d9356 commit 79af27a

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

README.md

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -175,20 +175,38 @@ hash_password::<Sha512>("my_password", "abcd", &mut buf2);
175175
If you want to use hash functions with trait objects, you can use the [`DynDigest`] trait:
176176

177177
```rust
178-
use sha2::{Sha256, Sha512, digest::DynDigest};
178+
use digest::DynDigest;
179179

180-
fn dyn_hash(hasher: &mut dyn DynDigest, data: &[u8]) -> Box<[u8]> {
180+
// Dynamic hash function
181+
fn use_hasher(hasher: &mut dyn DynDigest, data: &[u8]) -> Box<[u8]> {
181182
hasher.update(data);
182183
hasher.finalize_reset()
183184
}
184185

185-
let mut sha256_hasher = Sha256::default();
186-
let mut sha512_hasher = Sha512::default();
186+
// You can use something like this when parsing user input, CLI arguments, etc.
187+
// DynDigest needs to be boxed here, since function return should be sized.
188+
fn select_hasher(s: &str) -> Box<dyn DynDigest> {
189+
match s {
190+
"md5" => Box::new(md5::Md5::default()),
191+
"sha1" => Box::new(sha1::Sha1::default()),
192+
"sha224" => Box::new(sha2::Sha224::default()),
193+
"sha256" => Box::new(sha2::Sha256::default()),
194+
"sha384" => Box::new(sha2::Sha384::default()),
195+
"sha512" => Box::new(sha2::Sha512::default()),
196+
_ => unimplemented!("unsupported digest: {}", s),
197+
}
198+
}
199+
200+
let mut hasher1 = select_hasher("md5");
201+
let mut hasher2 = select_hasher("sha512");
202+
203+
// the `&mut *hasher` is to DerefMut the value out of the Box
204+
// this is equivalent to `DerefMut::deref_mut(&mut hasher)`
187205

188-
let hash1 = dyn_hash(&mut sha256_hasher, b"foo");
189-
let hash2 = dyn_hash(&mut sha256_hasher, b"bar");
190-
let hash3 = dyn_hash(&mut sha512_hasher, b"foo");
191-
let hash4 = dyn_hash(&mut sha512_hasher, b"bar");
206+
// can be reused due to `finalize_reset()`
207+
let hash1_1 = use_hasher(&mut *hasher1, b"foo");
208+
let hash1_2 = use_hasher(&mut *hasher1, b"bar");
209+
let hash2_1 = use_hasher(&mut *hasher2, b"foo");
192210
```
193211

194212
## License

0 commit comments

Comments
 (0)