3

I'm trying to Sha256 hash a struct to generate a GUID for that struct based on its contents.

use sha2::{Digest, Sha256};
use std::hash::{Hash, Hasher};

#[derive(Hash)]
struct Person {
  firstName: String;
  lastName: String;
}

let a = Person {
   firstName: "bob".to_string(),
   lastName: "the builder".to_string()
}

let mut s = Sha256::new();
a.hash(&mut s);
println!("{}", s.finsih());

My stretch goal would be to simply use a.id() which would hash all the properties on that struct. Is this a impl Person { id() -> String }?

I tried using impl x for y but that threw a impl doesn't use types inside crate

impl Hasher for Sha256 {
    fn finish(&self) -> u64 {
        self.0.result()
    }

    fn write(&mut self, msg: &[u8]) {
        self.0.input(msg)
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Marais Rossouw
  • 937
  • 1
  • 10
  • 29
  • 1
    Idiomatic Rust uses `snake_case` for variables, methods, macros, fields and modules; `UpperCamelCase` for types and enum variants; and `SCREAMING_SNAKE_CASE` for statics and constants. Use `first_name` and `last_name` instead, please. – Shepmaster May 19 '19 at 14:45
  • 1
    The code you have provided isn't valid Rust syntax and contains typos, which demonstrates that you haven't even attempted to run the code. – Shepmaster May 19 '19 at 14:47

1 Answers1

8

You can't implement an external trait for an external type.

Your issue is that the digest types, like Sha256, don't implement Hasher - because they're different kinds of hashes. The Hasher trait is for types which hash data into a 64 bit hash value, for use in Rust's own code, like HashMap. Sha256, on the other hand, gives a hash of 32 bytes.

To use Sha256, you need to manually feed it the bytes you want to compute the hash of - you can do this in an impl block.

impl Person {
    fn id(&self) -> sha2::digest::generic_array::GenericArray<u8, <Sha256 as Digest>::OutputSize> {
        let mut s = Sha256::new();
        s.input(self.firstName.as_bytes());
        s.input(self.lastName.as_bytes());
        s.result()
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Isaac van Bakel
  • 1,772
  • 10
  • 22