Tuesday, April 7, 2020

Understanding hashing and applications of hashing - Rust

Rust hashing

Rust Hashing

I am seeing hashing everywhere like block chain, load balancing ,Cryptographic hash functions,Password Verification,key-value pair data structures in programming languages.

So thought of checking how to do hashing Rust and looks like its pretty easy to do in Rust as well.

#![allow(unused)]
fn main() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

#[derive(Hash)]
struct Person {
    id: u32,
    name: String,
    phone: u64,
}

let person1 = Person {
    id: 5,
    name: "Janet".to_string(),
    phone: 555_666_7777,
};
let person2 = Person {
    id: 5,
    name: "Bob".to_string(),
    phone: 555_666_7777,
};

assert!(calculate_hash(&person1) != calculate_hash(&person2));

fn calculate_hash<T: Hash>(t: &T) -> u64 {
    let mut s = DefaultHasher::new();
    t.hash(&mut s);
    println!("{:?}",s.finish());
    s.finish()
}
}

hashing code example in rust

No comments: