The problem I have is that I can't seem to figure out how to create one trait that allows UpperHex trait created from Digest output.
A simpler version of what I want to do: I want to allow hash algorithms were the upper hex values trait is supported.
Here is an example of a function that takes a hash algorithm (digest crate) and prints the upper hex value.
use digest::{generic_array::ArrayLength, Digest, OutputSizeUser};
use std::{fmt::UpperHex, ops::Add};
fn main() {}
// Can write a funciton like this
pub fn print_upper_hex<D: Digest>()
where
// needed for UpperHex trait.
<D as OutputSizeUser>::OutputSize: Add,
<<D as OutputSizeUser>::OutputSize as Add>::Output: ArrayLength<u8>,
{
// create hash
let mut hasher = D::new();
hasher.update(b"Hello world!");
let hash = hasher.finalize();
// This works
println!("{:X}", hash);
}
But now I have to write the where clause everywhere, where it is needed. So I want to make one trait that does the same:
pub trait CanUpperHex
where
Self: Digest + UpperHex,
<Self as OutputSizeUser>::OutputSize: Add,
<<Self as OutputSizeUser>::OutputSize as Add>::Output: ArrayLength<u8>,
{
}
impl<T> CanUpperHex for T
where
Self: Digest + UpperHex,
<Self as OutputSizeUser>::OutputSize: Add,
<<Self as OutputSizeUser>::OutputSize as Add>::Output: ArrayLength<u8>,
{
}
And so I want to recreate the print_upper_hex function with the CanUpperHex trait:
pub fn print_upper_hex_2<D: CanUpperHex>() {
// create hash
let mut hasher = D::new();
hasher.update(b"Hello world!");
let hash = hasher.finalize();
// Doesn't work / compile
println!("{:X}", hash);
}
But this doesn't work.
Terminal output:
error[E0277]: cannot add `<D as OutputSizeUser>::OutputSize` to `<D as OutputSizeUser>::OutputSize`
--> src/main.rs:48:29
|
48 | pub fn print_upper_hex_2<D: CanUpperHex>() {
| ^^^^^^^^^^^ no implementation for `<D as OutputSizeUser>::OutputSize + <D as OutputSizeUser>::OutputSize`
|
= help: the trait `Add` is not implemented for `<D as OutputSizeUser>::OutputSize`
note: required by a bound in `CanUpperHex`
--> src/main.rs:34:43
|
31 | pub trait CanUpperHex
| ----------- required by a bound in this
...
34 | <Self as OutputSizeUser>::OutputSize: Add,
| ^^^ required by this bound in `CanUpperHex`
help: consider further restricting the associated type
|
48 | pub fn print_upper_hex_2<D: CanUpperHex>() where <D as OutputSizeUser>::OutputSize: Add {
| ++++++++++++++++++++++++++++++++++++++++++++
For more information about this error, try `rustc --explain E0277`.
error: could not compile `ask_upper_hex_digest` due to previous error
If I do what the terminal says, I end up with the same version as at the beginning. (only now with CanUpperHex instead of Digest)
Am I overlooking something?
Is there an other way to solve this?
I have been trying to solve this multiple times but I can't seem to figure it out and I don't know where to go from here.
Any help would be appreciated.