Encapsulated data in slice

Hi Rustaceans !

For learning purposes I'm writing a custom hash function, similarly to what's discussed in this post: How to implement its own hash function. I choose a trivial algorithm (FNV 1A) to concentrate on integration with traits. As mentionned in the post, I have implemented Hasher and BuildHasher traits. I think I have done things correctly so I don't post the code here, but I can do it if requested.

I'm now trying to use it, by using hash() method on struct that implement the hash trait :

mod fnv_hash;
use fnv_hash::fnv::*;
use std::hash::{Hash, Hasher};

fn main() {
    let mut hasher = FNV1a64Hasher::new();
    let s = b"Vanity search!";

    s.hash(&mut hasher);

    println!("Hashed msg gives : {:X}", hasher.finish());

Everything worked correctly excepted that the output hash wasn't the expected one (the implementation was numerically checked). I put a trace in my Hasher write(...) method and get this output:

write : [14, 0, 0, 0, 0, 0, 0, 0]
write : [86, 97, 110, 105, 116, 121, 32, 115, 101, 97, 114, 99, 104, 33]
Hashed msg gives : 9F7F879853EB6FF7

My write method has been called two times. The 14 is clearly the length of my slice so the first write call is made on slice's structure (u32 length / u32 offset ?), the second one is made on the encapsulated data, so the hash, is a hash of the whole structure, not on the embedded data, which is nice. Nevertheless, I would like to be able to perform a hash on the s slice (embedded data), but I have no idea how to do it. I tried to look for 'as_ptr()ยด like method, without success. I have got the feeling that the solution is easy, but I don't get it. Any ideas ?

Rust's Hash trait is for approximate structural equality for hash maps, not for getting reliable digests of the data you want.

If you want to hash specific bytes, use a different interface that gives you more direct access to the hashing algorithm. Hash/Hasher isn't for general-purpose hashing.

It hashes its length as usize first.

Thanks for this fast answer. In the meantime, I found that using :

Hash::hash_slice(s, &mut hasher);

in place of

s.hash(&mut hasher);

gave the correct output. My ultimate goal (!) wasn't to compute reliable digests on my data, but to have a custom hash algorithm, that can be used with hash_table for example. It would be useless for sure, but it proved that I managed to use traits the right way. Just an exercise.

You are right. I shouldn't be that shy and jump to the sources sooner :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.