about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2014-08-12 05:11:18 +0000
committerbors <bors@rust-lang.org>2014-08-12 05:11:18 +0000
commite8204a84c7f365533c217b4882bbe0cbce5a34e3 (patch)
tree467838df5fcdd90f3fb47dcb95cf766ef4df3347
parent49a970f2449a78f28b6c301e542d38593094ca77 (diff)
parent8f71cb06bc019af707f119b5dda3d96a5ca1330c (diff)
downloadrust-e8204a84c7f365533c217b4882bbe0cbce5a34e3.tar.gz
rust-e8204a84c7f365533c217b4882bbe0cbce5a34e3.zip
auto merge of #16195 : P1start/rust/more-index, r=aturon
Implement `Index` for `RingBuf`, `HashMap`, `TreeMap`, `SmallIntMap`, and `TrieMap`.

If there’s anything that I missed or should be removed, let me know.
-rw-r--r--src/libcollections/ringbuf.rs43
-rw-r--r--src/libcollections/smallintmap.rs49
-rw-r--r--src/libcollections/treemap.rs36
-rw-r--r--src/libcollections/trie.rs38
-rw-r--r--src/librustdoc/html/format.rs12
-rw-r--r--src/librustdoc/html/render.rs4
-rw-r--r--src/librustdoc/visit_ast.rs2
-rw-r--r--src/libstd/collections/hashmap.rs54
8 files changed, 216 insertions, 22 deletions
diff --git a/src/libcollections/ringbuf.rs b/src/libcollections/ringbuf.rs
index 84b5c5bb998..736861a54a4 100644
--- a/src/libcollections/ringbuf.rs
+++ b/src/libcollections/ringbuf.rs
@@ -139,6 +139,8 @@ impl<T> RingBuf<T> {
     /// # Example
     ///
     /// ```rust
+    /// #![allow(deprecated)]
+    ///
     /// use std::collections::RingBuf;
     ///
     /// let mut buf = RingBuf::new();
@@ -147,6 +149,7 @@ impl<T> RingBuf<T> {
     /// buf.push(5);
     /// assert_eq!(buf.get(1), &4);
     /// ```
+    #[deprecated = "prefer using indexing, e.g., ringbuf[0]"]
     pub fn get<'a>(&'a self, i: uint) -> &'a T {
         let idx = self.raw_index(i);
         match *self.elts.get(idx) {
@@ -169,7 +172,7 @@ impl<T> RingBuf<T> {
     /// buf.push(4);
     /// buf.push(5);
     /// *buf.get_mut(1) = 7;
-    /// assert_eq!(buf.get(1), &7);
+    /// assert_eq!(buf[1], 7);
     /// ```
     pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut T {
         let idx = self.raw_index(i);
@@ -195,8 +198,8 @@ impl<T> RingBuf<T> {
     /// buf.push(4);
     /// buf.push(5);
     /// buf.swap(0, 2);
-    /// assert_eq!(buf.get(0), &5);
-    /// assert_eq!(buf.get(2), &3);
+    /// assert_eq!(buf[0], 5);
+    /// assert_eq!(buf[2], 3);
     /// ```
     pub fn swap(&mut self, i: uint, j: uint) {
         assert!(i < self.len());
@@ -476,6 +479,21 @@ impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
     }
 }
 
+impl<A> Index<uint, A> for RingBuf<A> {
+    #[inline]
+    fn index<'a>(&'a self, i: &uint) -> &'a A {
+        self.get(*i)
+    }
+}
+
+// FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
+/*impl<A> IndexMut<uint, A> for RingBuf<A> {
+    #[inline]
+    fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut A {
+        self.get_mut(*index)
+    }
+}*/
+
 impl<A> FromIterator<A> for RingBuf<A> {
     fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
         let (lower, _) = iterator.size_hint();
@@ -653,6 +671,25 @@ mod tests {
         }
     }
 
+    #[test]
+    fn test_index() {
+        let mut deq = RingBuf::new();
+        for i in range(1u, 4) {
+            deq.push_front(i);
+        }
+        assert_eq!(deq[1], 2);
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_index_out_of_bounds() {
+        let mut deq = RingBuf::new();
+        for i in range(1u, 4) {
+            deq.push_front(i);
+        }
+        deq[3];
+    }
+
     #[bench]
     fn bench_new(b: &mut test::Bencher) {
         b.iter(|| {
diff --git a/src/libcollections/smallintmap.rs b/src/libcollections/smallintmap.rs
index f567c5777b1..39244c7cd5f 100644
--- a/src/libcollections/smallintmap.rs
+++ b/src/libcollections/smallintmap.rs
@@ -209,12 +209,15 @@ impl<V> SmallIntMap<V> {
     /// # Example
     ///
     /// ```
+    /// #![allow(deprecated)]
+    ///
     /// use std::collections::SmallIntMap;
     ///
     /// let mut map = SmallIntMap::new();
     /// map.insert(1, "a");
     /// assert_eq!(map.get(&1), &"a");
     /// ```
+    #[deprecated = "prefer using indexing, e.g., map[0]"]
     pub fn get<'a>(&'a self, key: &uint) -> &'a V {
         self.find(key).expect("key not present")
     }
@@ -330,11 +333,11 @@ impl<V:Clone> SmallIntMap<V> {
     ///
     /// // Key does not exist, will do a simple insert
     /// assert!(map.update(1, vec![1i, 2], |old, new| old.append(new.as_slice())));
-    /// assert_eq!(map.get(&1), &vec![1i, 2]);
+    /// assert_eq!(map[1], vec![1i, 2]);
     ///
     /// // Key exists, update the value
     /// assert!(!map.update(1, vec![3i, 4], |old, new| old.append(new.as_slice())));
-    /// assert_eq!(map.get(&1), &vec![1i, 2, 3, 4]);
+    /// assert_eq!(map[1], vec![1i, 2, 3, 4]);
     /// ```
     pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool {
         self.update_with_key(key, newval, |_k, v, v1| ff(v,v1))
@@ -354,11 +357,11 @@ impl<V:Clone> SmallIntMap<V> {
     ///
     /// // Key does not exist, will do a simple insert
     /// assert!(map.update_with_key(7, 10, |key, old, new| (old + new) % key));
-    /// assert_eq!(map.get(&7), &10);
+    /// assert_eq!(map[7], 10);
     ///
     /// // Key exists, update the value
     /// assert!(!map.update_with_key(7, 20, |key, old, new| (old + new) % key));
-    /// assert_eq!(map.get(&7), &2);
+    /// assert_eq!(map[7], 2);
     /// ```
     pub fn update_with_key(&mut self,
                            key: uint,
@@ -416,6 +419,21 @@ impl<V> Extendable<(uint, V)> for SmallIntMap<V> {
     }
 }
 
+impl<V> Index<uint, V> for SmallIntMap<V> {
+    #[inline]
+    fn index<'a>(&'a self, i: &uint) -> &'a V {
+        self.get(i)
+    }
+}
+
+// FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
+/*impl<V> IndexMut<uint, V> for SmallIntMap<V> {
+    #[inline]
+    fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut V {
+        self.find_mut(i).expect("key not present")
+    }
+}*/
+
 macro_rules! iterator {
     (impl $name:ident -> $elem:ty, $getter:ident) => {
         impl<'a, T> Iterator<$elem> for $name<'a, T> {
@@ -843,6 +861,29 @@ mod test_map {
             assert_eq!(map.find(&k), Some(&v));
         }
     }
+
+    #[test]
+    fn test_index() {
+        let mut map: SmallIntMap<int> = SmallIntMap::new();
+
+        map.insert(1, 2);
+        map.insert(2, 1);
+        map.insert(3, 4);
+
+        assert_eq!(map[3], 4);
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_index_nonexistent() {
+        let mut map: SmallIntMap<int> = SmallIntMap::new();
+
+        map.insert(1, 2);
+        map.insert(2, 1);
+        map.insert(3, 4);
+
+        map[4];
+    }
 }
 
 #[cfg(test)]
diff --git a/src/libcollections/treemap.rs b/src/libcollections/treemap.rs
index 6299ecfc5fd..ae87411133f 100644
--- a/src/libcollections/treemap.rs
+++ b/src/libcollections/treemap.rs
@@ -246,6 +246,20 @@ impl<K: Ord, V> Default for TreeMap<K,V> {
     fn default() -> TreeMap<K, V> { TreeMap::new() }
 }
 
+impl<K: Ord, V> Index<K, V> for TreeMap<K, V> {
+    #[inline]
+    fn index<'a>(&'a self, i: &K) -> &'a V {
+        self.find(i).expect("no entry found for key")
+    }
+}
+
+/*impl<K: Ord, V> IndexMut<K, V> for TreeMap<K, V> {
+    #[inline]
+    fn index_mut<'a>(&'a mut self, i: &K) -> &'a mut V {
+        self.find_mut(i).expect("no entry found for key")
+    }
+}*/
+
 impl<K: Ord, V> TreeMap<K, V> {
     /// Create an empty `TreeMap`.
     ///
@@ -2149,6 +2163,28 @@ mod test_treemap {
         }
     }
 
+    #[test]
+    fn test_index() {
+        let mut map: TreeMap<int, int> = TreeMap::new();
+
+        map.insert(1, 2);
+        map.insert(2, 1);
+        map.insert(3, 4);
+
+        assert_eq!(map[2], 1);
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_index_nonexistent() {
+        let mut map: TreeMap<int, int> = TreeMap::new();
+
+        map.insert(1, 2);
+        map.insert(2, 1);
+        map.insert(3, 4);
+
+        map[4];
+    }
 }
 
 #[cfg(test)]
diff --git a/src/libcollections/trie.rs b/src/libcollections/trie.rs
index ec7ed919177..c3dcebfc815 100644
--- a/src/libcollections/trie.rs
+++ b/src/libcollections/trie.rs
@@ -502,6 +502,21 @@ impl<S: Writer, T: Hash<S>> Hash<S> for TrieMap<T> {
     }
 }
 
+impl<T> Index<uint, T> for TrieMap<T> {
+    #[inline]
+    fn index<'a>(&'a self, i: &uint) -> &'a T {
+        self.find(i).expect("key not present")
+    }
+}
+
+// FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
+/*impl<T> IndexMut<uint, T> for TrieMap<T> {
+    #[inline]
+    fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut T {
+        self.find_mut(i).expect("key not present")
+    }
+}*/
+
 /// A set implemented as a radix trie.
 ///
 /// # Example
@@ -1391,6 +1406,29 @@ mod test_map {
         assert!(map_str == "{1: a, 2: b}".to_string());
         assert_eq!(format!("{}", empty), "{}".to_string());
     }
+
+    #[test]
+    fn test_index() {
+        let mut map = TrieMap::new();
+
+        map.insert(1, 2i);
+        map.insert(2, 1i);
+        map.insert(3, 4i);
+
+        assert_eq!(map[2], 1);
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_index_nonexistent() {
+        let mut map = TrieMap::new();
+
+        map.insert(1, 2i);
+        map.insert(2, 1i);
+        map.insert(3, 4i);
+
+        map[4];
+    }
 }
 
 #[cfg(test)]
diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs
index 2fb3143b0bf..a1dd49bbf89 100644
--- a/src/librustdoc/html/format.rs
+++ b/src/librustdoc/html/format.rs
@@ -166,7 +166,7 @@ fn resolved_path(w: &mut fmt::Formatter, did: ast::DefId, p: &clean::Path,
             if ast_util::is_local(did) || cache.inlined.contains(&did) {
                 Some(("../".repeat(loc.len())).to_string())
             } else {
-                match *cache.extern_locations.get(&did.krate) {
+                match cache.extern_locations[did.krate] {
                     render::Remote(ref s) => Some(s.to_string()),
                     render::Local => {
                         Some(("../".repeat(loc.len())).to_string())
@@ -291,11 +291,11 @@ fn primitive_link(f: &mut fmt::Formatter,
             needs_termination = true;
         }
         Some(&cnum) => {
-            let path = m.paths.get(&ast::DefId {
+            let path = &m.paths[ast::DefId {
                 krate: cnum,
                 node: ast::CRATE_NODE_ID,
-            });
-            let loc = match *m.extern_locations.get(&cnum) {
+            }];
+            let loc = match m.extern_locations[cnum] {
                 render::Remote(ref s) => Some(s.to_string()),
                 render::Local => {
                     let loc = current_location_key.get().unwrap();
@@ -343,11 +343,11 @@ impl fmt::Show for clean::Type {
         match *self {
             clean::TyParamBinder(id) => {
                 let m = cache_key.get().unwrap();
-                f.write(m.typarams.get(&ast_util::local_def(id)).as_bytes())
+                f.write(m.typarams[ast_util::local_def(id)].as_bytes())
             }
             clean::Generic(did) => {
                 let m = cache_key.get().unwrap();
-                f.write(m.typarams.get(&did).as_bytes())
+                f.write(m.typarams[did].as_bytes())
             }
             clean::ResolvedPath{ did, ref typarams, ref path } => {
                 try!(resolved_path(f, did, path, false));
diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs
index eea59455039..4f511e390ff 100644
--- a/src/librustdoc/html/render.rs
+++ b/src/librustdoc/html/render.rs
@@ -1274,8 +1274,8 @@ impl<'a> Item<'a> {
         // located, then we return `None`.
         } else {
             let cache = cache_key.get().unwrap();
-            let path = cache.external_paths.get(&self.item.def_id);
-            let root = match *cache.extern_locations.get(&self.item.def_id.krate) {
+            let path = &cache.external_paths[self.item.def_id];
+            let root = match cache.extern_locations[self.item.def_id.krate] {
                 Remote(ref s) => s.to_string(),
                 Local => self.cx.root_path.clone(),
                 Unknown => return None,
diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs
index d28069da6ba..5b2a542ca96 100644
--- a/src/librustdoc/visit_ast.rs
+++ b/src/librustdoc/visit_ast.rs
@@ -229,7 +229,7 @@ impl<'a> RustdocVisitor<'a> {
             core::Typed(ref tcx) => tcx,
             core::NotTyped(_) => return false
         };
-        let def = tcx.def_map.borrow().get(&id).def_id();
+        let def = (*tcx.def_map.borrow())[id].def_id();
         if !ast_util::is_local(def) { return false }
         let analysis = match self.analysis {
             Some(analysis) => analysis, None => return false
diff --git a/src/libstd/collections/hashmap.rs b/src/libstd/collections/hashmap.rs
index e95a5305bc7..2de9db1cc93 100644
--- a/src/libstd/collections/hashmap.rs
+++ b/src/libstd/collections/hashmap.rs
@@ -26,6 +26,7 @@ use mem::replace;
 use num;
 use option::{Some, None, Option};
 use result::{Ok, Err};
+use ops::Index;
 
 mod table {
     use clone::Clone;
@@ -1341,7 +1342,7 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
     ///
     /// // Update and return the existing value
     /// assert_eq!(*map.insert_or_update_with("a", 9, |_key, val| *val = 7), 7);
-    /// assert_eq!(map.get(&"a"), &7);
+    /// assert_eq!(map["a"], 7);
     /// ```
     pub fn insert_or_update_with<'a>(
                                  &'a mut self,
@@ -1392,9 +1393,9 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
     /// }
     ///
     /// assert_eq!(map.len(), 3);
-    /// assert_eq!(map.get(&"a key"), &vec!["value", "new value"]);
-    /// assert_eq!(map.get(&"b key"), &vec!["new value"]);
-    /// assert_eq!(map.get(&"z key"), &vec!["new value", "value"]);
+    /// assert_eq!(map["a key"], vec!["value", "new value"]);
+    /// assert_eq!(map["b key"], vec!["new value"]);
+    /// assert_eq!(map["z key"], vec!["new value", "value"]);
     /// ```
     pub fn find_with_or_insert_with<'a, A>(&'a mut self,
                                            k: K,
@@ -1426,12 +1427,15 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
     /// # Example
     ///
     /// ```
+    /// #![allow(deprecated)]
+    ///
     /// use std::collections::HashMap;
     ///
     /// let mut map = HashMap::new();
     /// map.insert("a", 1i);
     /// assert_eq!(map.get(&"a"), &1);
     /// ```
+    #[deprecated = "prefer indexing instead, e.g., map[key]"]
     pub fn get<'a>(&'a self, k: &K) -> &'a V {
         match self.find(k) {
             Some(v) => v,
@@ -1458,11 +1462,11 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> {
     ///     let val = map.get_mut(&"a");
     ///     *val = 40;
     /// }
-    /// assert_eq!(map.get(&"a"), &40);
+    /// assert_eq!(map["a"], 40);
     ///
     /// // A more direct way could be:
     /// *map.get_mut(&"a") = -2;
-    /// assert_eq!(map.get(&"a"), &-2);
+    /// assert_eq!(map["a"], -2);
     /// ```
     pub fn get_mut<'a>(&'a mut self, k: &K) -> &'a mut V {
         match self.find_mut(k) {
@@ -1738,6 +1742,21 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S> + Default> Default for HashMap<K, V, H>
     }
 }
 
+impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> Index<K, V> for HashMap<K, V, H> {
+    #[inline]
+    fn index<'a>(&'a self, index: &K) -> &'a V {
+        self.get(index)
+    }
+}
+
+// FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
+/*impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> ops::IndexMut<K, V> for HashMap<K, V, H> {
+    #[inline]
+    fn index_mut<'a>(&'a mut self, index: &K) -> &'a mut V {
+        self.get_mut(index)
+    }
+}*/
+
 /// HashMap iterator
 pub type Entries<'a, K, V> = table::Entries<'a, K, V>;
 
@@ -2694,6 +2713,29 @@ mod test_map {
 
         assert_eq!(iter.size_hint(), (3, Some(3)));
     }
+
+    #[test]
+    fn test_index() {
+        let mut map: HashMap<int, int> = HashMap::new();
+
+        map.insert(1, 2);
+        map.insert(2, 1);
+        map.insert(3, 4);
+
+        assert_eq!(map[2], 1);
+    }
+
+    #[test]
+    #[should_fail]
+    fn test_index_nonexistent() {
+        let mut map: HashMap<int, int> = HashMap::new();
+
+        map.insert(1, 2);
+        map.insert(2, 1);
+        map.insert(3, 4);
+
+        map[4];
+    }
 }
 
 #[cfg(test)]