Repo of no-std crates for my personal embedded projects
1//! This crate provides a `const` FNV32 hasher for the purpose of supporting the ESPHome/Home Assistant protocol where required.
2//!
3//! ```
4//! use sachy_fnv::fnv32_hash;
5//!
6//! let hash = fnv32_hash("water_pump_1");
7//!
8//! assert_eq!(hash, 3557162331);
9//! ```
10#![no_std]
11
12const FNV_OFFSET_BASIS_32: u32 = 0x811c9dc5;
13const FNV_PRIME_32: u32 = 0x01000193;
14
15/// `const` FNV32 hasher. Takes a `&str` and returns a `u32` hash.
16pub const fn fnv32_hash(str: &str) -> u32 {
17 let bytes = str.as_bytes();
18
19 let mut hash = FNV_OFFSET_BASIS_32;
20 let mut i = 0;
21 let len = bytes.len();
22
23 while i < len {
24 hash = hash.wrapping_mul(FNV_PRIME_32);
25 hash ^= bytes[i] as u32;
26 i += 1;
27 }
28
29 hash
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35
36 #[test]
37 fn it_works() {
38 let result = fnv32_hash("water_pump_1");
39 assert_eq!(result, 3557162331);
40 let result = fnv32_hash("pump_1_duration");
41 assert_eq!(result, 931766070);
42 }
43}