]> git.lizzy.rs Git - rust.git/commitdiff
Implement Index for RingBuf
authorP1start <rewi-github@whanau.org>
Sat, 2 Aug 2014 06:39:39 +0000 (18:39 +1200)
committerP1start <rewi-github@whanau.org>
Tue, 12 Aug 2014 03:32:56 +0000 (15:32 +1200)
This also deprecates RingBuf::get. Use indexing instead.

src/libcollections/ringbuf.rs

index 44b546f665688a069ca478a4f1198cf06ab643b7..8ab76e57b9358d5f08eb342eaafb7fea925215a2 100644 (file)
@@ -139,6 +139,8 @@ pub fn with_capacity(n: uint) -> RingBuf<T> {
     /// # Example
     ///
     /// ```rust
+    /// #![allow(deprecated)]
+    ///
     /// use std::collections::RingBuf;
     ///
     /// let mut buf = RingBuf::new();
@@ -147,6 +149,7 @@ pub fn with_capacity(n: uint) -> 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 @@ pub fn get<'a>(&'a self, i: uint) -> &'a 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 @@ pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut 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());
@@ -467,6 +470,21 @@ fn hash(&self, state: &mut S) {
     }
 }
 
+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();
@@ -644,6 +662,25 @@ fn test_push_front_grow() {
         }
     }
 
+    #[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(|| {