-
Notifications
You must be signed in to change notification settings - Fork 305
Closed
Description
Hi, I was writing a simple program and I discovered that getting a hex output of a generic hash is harder than I thought.
I expected that something like this would work:
extern crate sha2;
use sha2::Digest;
fn example<D: Digest>() {
let mut hasher = D::new();
hasher.input(b"hello world");
let hash = hasher.result();
println!("{:x}", hash);
}However, the above code generates the following error:
error[E0277]: cannot add `<D as sha2::Digest>::OutputSize` to `<D as sha2::Digest>::OutputSize`
--> src/main.rs:103:22
|
99 | fn example<D: Digest>() {
| - help: consider further restricting the associated type: `where <D as sha2::Digest>::OutputSize: std::ops::Add`
...
103 | println!("{:x}", hash);
| ^^^^ no implementation for `<D as sha2::Digest>::OutputSize + <D as sha2::Digest>::OutputSize`
|
= help: the trait `std::ops::Add` is not implemented for `<D as sha2::Digest>::OutputSize`
= note: required because of the requirements on the impl of `std::fmt::LowerHex` for `sha2::digest::generic_array::GenericArray<u8, <D as sha2::Digest>::OutputSize>`
= note: required by `std::fmt::LowerHex::fmt`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
After some experimentation, I discovered that the following code does work:
extern crate sha2;
use sha2::Digest;
fn example<D: Digest>() where <D as sha2::Digest>::OutputSize: std::ops::Add, <<D as sha2::Digest>::OutputSize as std::ops::Add>::Output: sha2::digest::generic_array::ArrayLength<u8> {
let mut hasher = D::new();
hasher.input(b"hello world");
let hash = hasher.result();
println!("{:x}", hash);
}So, I think that the Digest trait should be changed to make the extra code unecessary.
Metadata
Metadata
Assignees
Labels
No labels