use std::fs;
use std::io;
use std::path::Path;
use xxhash_rust::xxh3::xxh3_64;

pub fn hash_file(path: &Path) -> io::Result<u64> {
    let contents = fs::read(path)?;
    Ok(xxh3_64(&contents))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn identical_files_have_same_hash() {
        let mut f1 = NamedTempFile::new().unwrap();
        let mut f2 = NamedTempFile::new().unwrap();
        write!(f1, "hello world").unwrap();
        write!(f2, "hello world").unwrap();

        let h1 = hash_file(f1.path()).unwrap();
        let h2 = hash_file(f2.path()).unwrap();
        assert_eq!(h1, h2);
    }

    #[test]
    fn different_files_have_different_hash() {
        let mut f1 = NamedTempFile::new().unwrap();
        let mut f2 = NamedTempFile::new().unwrap();
        write!(f1, "hello").unwrap();
        write!(f2, "world").unwrap();

        let h1 = hash_file(f1.path()).unwrap();
        let h2 = hash_file(f2.path()).unwrap();
        assert_ne!(h1, h2);
    }
}
