hashmatch/lib.rs
1//! More efficient `static &str` matching when match #arm > 30.
2//! ```
3//! use hashmatch::{hash_arm, hash_str};
4//! // to avoid hash conflict
5//! #[deny(unreachable_patterns)]
6//! let res = match hash_str("ABC") {
7//! hash_arm!("ABC") => 1,
8//! hash_arm!("AAA") | hash_arm!("BBB") => 2,
9//! _ => 3,
10//! };
11//! assert_eq!(res, 1);
12//! ```
13
14pub use hashmatch_macro::hash_arm;
15
16const HASHER: foldhash::fast::FixedState = foldhash::fast::FixedState::with_seed(41);
17/// Runtime hash with consistency of `hash_arm!` (`hash_arm!` is compling time)
18#[inline]
19pub fn hash_str<S: AsRef<str>>(t: S) -> u64 {
20 use std::hash::{BuildHasher, Hash, Hasher};
21 let mut hasher = HASHER.build_hasher();
22 t.as_ref().hash(&mut hasher);
23 hasher.finish()
24}
25
26#[test]
27fn demo() {
28 // to avoid hash conflict
29 #[deny(unreachable_patterns)]
30 let res = match hash_str("ABC") {
31 hash_arm!("ABC") => 1,
32 hash_arm!("AAA") | hash_arm!("BBB") => 2,
33 _ => 3,
34 };
35 assert_eq!(res, 1);
36}