Skip to content

Instantly share code, notes, and snippets.

Created April 26, 2016 12:59
Show Gist options
  • Save anonymous/9414fd147328f96a7e153d454a2a10e4 to your computer and use it in GitHub Desktop.
Save anonymous/9414fd147328f96a7e153d454a2a10e4 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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