Skip to content

Commit

Permalink
Impl Index for PhfMap and PhfOrderedMap
Browse files Browse the repository at this point in the history
  • Loading branch information
sfackler committed Jul 19, 2014
1 parent 5c59a7a commit 3995dbc
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
12 changes: 12 additions & 0 deletions phf/src/lib.rs
Expand Up @@ -83,6 +83,12 @@ impl<K: fmt::Show, V: fmt::Show> fmt::Show for PhfMap<K, V> {
}
}

impl<K: Hash+Eq, V> Index<K, V> for PhfMap<K, V> {
fn index<'a>(&'a self, k: &K) -> &'a V {
self.find(k).expect("invalid key")
}
}

impl<K: Hash+Eq, V> PhfMap<K, V> {
fn get_entry<'a, T: Hash>(&'a self, key: &T, check: |&K| -> bool)
-> Option<&'a (K, V)> {
Expand Down Expand Up @@ -404,6 +410,12 @@ impl<'a, K: Hash+Eq, V> Map<K, V> for PhfOrderedMap<K, V> {
}
}

impl<K: Hash+Eq, V> Index<K, V> for PhfOrderedMap<K, V> {
fn index<'a>(&'a self, k: &K) -> &'a V {
self.find(k).expect("invalid key")
}
}

impl<K: Hash+Eq, V> PhfOrderedMap<K, V> {
fn find_entry<'a>(&'a self, key: &K) -> Option<&'a (K, V)> {
let (g, f1, f2) = shared::hash(key, self.k1, self.k2);
Expand Down
34 changes: 34 additions & 0 deletions phf/src/test.rs
Expand Up @@ -115,6 +115,23 @@ mod map {
assert_eq!(Some(&0), map.find_equiv(&"a".to_string().as_slice()));
}

#[test]
fn test_index_ok() {
static map: PhfMap<&'static str, int> = phf_map!(
"a" => 0,
);
assert_eq!(0, map["a"]);
}

#[test]
#[should_fail]
fn test_index_fail() {
static map: PhfMap<&'static str, int> = phf_map!(
"a" => 0,
);
map["b"];
}

macro_rules! test_key_type(
($t:ty, $($k:expr => $v:expr),+) => ({
static map: PhfMap<$t, int> = phf_map! {
Expand Down Expand Up @@ -283,6 +300,23 @@ mod ordered_map {
let vec = MAP.values().map(|&v| v).collect::<Vec<_>>();
assert_eq!(vec, vec!(10i, 11, 12));
}

#[test]
fn test_index_ok() {
static map: PhfOrderedMap<&'static str, int> = phf_ordered_map!(
"a" => 0,
);
assert_eq!(0, map["a"]);
}

#[test]
#[should_fail]
fn test_index_fail() {
static map: PhfOrderedMap<&'static str, int> = phf_ordered_map!(
"a" => 0,
);
map["b"];
}
}

mod ordered_set {
Expand Down

0 comments on commit 3995dbc

Please sign in to comment.