RustCrypto / hashes

Collection of cryptographic hash functions written in pure Rust
1.82k stars 247 forks source link

std::io::Write is not implemented for DynDigest #430

Closed guyru closed 1 year ago

guyru commented 1 year ago

Hi,

It seems like you can't use std::io::copy when working with DynDigest objects. For example:

let mut hasher: Box<dyn DynDigest> = Box::new(Md5::default());
std::io::copy(&mut buffer, &mut hasher).unwrap();

will fail to compile and complain about

the trait `std::io::Write` is not implemented for `dyn DynDigest`

Any way around that?
guyru commented 1 year ago

The solution is to define a supertrait

trait MyDigest: DynDigest + Write {}
impl<T: DynDigest + Write> MyDigest for T {}

and have the Box refer to it:

let mut hasher: Box<dyn MyDigest> = Box::new(Md5::default());
newpavlov commented 1 year ago

Yeah, the issue is that currently we are not allowed to write impls like this:

impl<T: DynDigest> std::io::Write for T { .. }

And there is a good reason for that, since such impl would conflict with impls on the wrapper types.

Ideally, Rust would allow you to write Box<dyn DynDigest + io::Write>, but alas I don't think this feature will be implemented and stabilized in the near future.