Skip to content

Change Sha2::Digest to make {:x} easier (hex format) #102

Description

@gjvnq

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions