text_fx/hash.rs
1/// Computes a hash for a UTF-8 string slice using the method described by Bruno Haible.
2///
3/// This function iterates over each byte of the string, updating the hash value at each step.
4/// It is suitable for hashing Rust string slices (`&str`), not raw C pointers.
5///
6/// See: <https://www.haible.de/bruno/hashfunc.html>
7///
8/// # Examples
9///
10/// ```
11/// use text_fx::hash::string_hash;
12///
13/// let hash = string_hash("hello");
14/// assert_eq!(hash, string_hash("hello"));
15/// assert_ne!(hash, string_hash("world"));
16/// ```
17pub fn string_hash(s: &str) -> usize {
18 let mut h = 0;
19 for &b in s.as_bytes() {
20 h = b as usize + (h << 9) | (h >> (usize::BITS - 9));
21 }
22 h
23}
24
25#[cfg(test)]
26mod tests {
27 use super::*;
28
29 #[test]
30 fn test_string_hash() {
31 assert_eq!(string_hash("hello"), string_hash("hello"));
32 assert_ne!(string_hash("hello"), string_hash("world"));
33 }
34}