-
-
Save dylanede/429876ee918140e09a8e8ae445a24c26 to your computer and use it in GitHub Desktop.
Static string hash map optimisations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cell::RefCell; | |
use std::collections::HashMap; | |
use std::hash::{ Hash, SipHasher, Hasher }; | |
thread_local!(static SYMBOL_HASHES: RefCell<HashMap<(*const u8, usize), u64>> = RefCell::new(HashMap::new())); | |
struct StaticSymbol { | |
string: &'static str, | |
hash: u64, | |
} | |
impl StaticSymbol { | |
fn new(string: &'static str) -> StaticSymbol { | |
let hash = SYMBOL_HASHES.with(|map| { | |
*map.borrow_mut().entry((string.as_ptr(), string.len())) | |
.or_insert_with(|| { | |
let mut hasher = SipHasher::new(); | |
string.hash(&mut hasher); | |
hasher.finish() | |
}) | |
}); | |
StaticSymbol { | |
string: string, | |
hash: hash | |
} | |
} | |
} | |
impl PartialEq for StaticSymbol { | |
fn eq(&self, other: &StaticSymbol) -> bool { | |
(self.string.as_ptr() == other.string.as_ptr() | |
&& self.string.len() == other.string.len()) | |
|| self.string == other.string | |
} | |
} | |
impl Eq for StaticSymbol { | |
} | |
impl Hash for StaticSymbol { | |
fn hash<H: Hasher>(&self, state: &mut H) { | |
state.write_u64(self.hash); | |
} | |
} | |
fn main() { | |
let s = StaticSymbol::new("foo"); | |
println!("Hello, world!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment