use chematic_core::Molecule;
use chematic_smiles::canonical_smiles;
const FNV1A_OFFSET: u64 = 0xcbf29ce484222325;
const FNV1A_PRIME: u64 = 0x100000001b3;
pub fn mol_hash(mol: &Molecule) -> u64 {
let smiles = canonical_smiles(mol);
let mut hash = FNV1A_OFFSET;
for byte in smiles.as_bytes() {
hash ^= *byte as u64;
hash = hash.wrapping_mul(FNV1A_PRIME);
}
hash
}
pub fn are_identical(a: &Molecule, b: &Molecule) -> bool {
canonical_smiles(a) == canonical_smiles(b)
}
#[cfg(test)]
mod tests {
use super::*;
use chematic_smiles::parse;
fn mol(s: &str) -> Molecule {
parse(s).unwrap_or_else(|e| panic!("parse '{s}': {e}"))
}
#[test]
fn mol_hash_same_smiles_same_hash() {
let a = mol("CC");
let b = mol("CC");
assert_eq!(
mol_hash(&a),
mol_hash(&b),
"same SMILES should give same hash"
);
}
#[test]
fn mol_hash_different_smiles_likely_different_hash() {
let ethane = mol("CC");
let propane = mol("CCC");
assert_ne!(
mol_hash(ðane),
mol_hash(&propane),
"different SMILES should (very likely) differ"
);
}
#[test]
fn mol_hash_deterministic() {
let m = mol("c1ccccc1");
let hash1 = mol_hash(&m);
let hash2 = mol_hash(&m);
assert_eq!(hash1, hash2, "same molecule should produce same hash");
}
#[test]
fn are_identical_true_for_same_structure() {
let a = mol("CC");
let b = mol("CC");
assert!(
are_identical(&a, &b),
"identical structures should return true"
);
}
#[test]
fn are_identical_false_for_different() {
let a = mol("CC");
let b = mol("CCC");
assert!(
!are_identical(&a, &b),
"different structures should return false"
);
}
#[test]
fn are_identical_aspirin() {
let aspirin1 = mol("CC(=O)Oc1ccccc1C(=O)O");
let aspirin2 = mol("O=C(c1ccccc1OC(=O)C)O");
assert!(
are_identical(&aspirin1, &aspirin2),
"different notations of aspirin should be identical"
);
}
}