Skip to content

Instantly share code, notes, and snippets.

Created April 26, 2016 12:59

Revisions

  1. @invalid-email-address Anonymous created this gist Apr 26, 2016.
    50 changes: 50 additions & 0 deletions playground.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    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!");
    }