diff --git a/phf/src/lib.rs b/phf/src/lib.rs index aeaa2f32..be5c53c3 100644 --- a/phf/src/lib.rs +++ b/phf/src/lib.rs @@ -83,6 +83,12 @@ impl fmt::Show for PhfMap { } } +impl Index for PhfMap { + fn index<'a>(&'a self, k: &K) -> &'a V { + self.find(k).expect("invalid key") + } +} + impl PhfMap { fn get_entry<'a, T: Hash>(&'a self, key: &T, check: |&K| -> bool) -> Option<&'a (K, V)> { @@ -404,6 +410,12 @@ impl<'a, K: Hash+Eq, V> Map for PhfOrderedMap { } } +impl Index for PhfOrderedMap { + fn index<'a>(&'a self, k: &K) -> &'a V { + self.find(k).expect("invalid key") + } +} + impl PhfOrderedMap { fn find_entry<'a>(&'a self, key: &K) -> Option<&'a (K, V)> { let (g, f1, f2) = shared::hash(key, self.k1, self.k2); diff --git a/phf/src/test.rs b/phf/src/test.rs index ee95a999..2587e31f 100644 --- a/phf/src/test.rs +++ b/phf/src/test.rs @@ -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! { @@ -283,6 +300,23 @@ mod ordered_map { let vec = MAP.values().map(|&v| v).collect::>(); 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 {