about summary refs log tree commit diff
diff options
context:
space:
mode:
authorblake2-ppc <blake2-ppc>2013-09-26 09:19:26 +0200
committerblake2-ppc <blake2-ppc>2013-09-26 09:25:32 +0200
commit57757a8051101eb64eb7a330d7c673422e06a57b (patch)
treee05530055e219f0726c5a06ca9ac19492b0f9919
parent5adfa1038787cb042ca5bbe634082201d71a3b72 (diff)
downloadrust-57757a8051101eb64eb7a330d7c673422e06a57b.tar.gz
rust-57757a8051101eb64eb7a330d7c673422e06a57b.zip
extra::ringbuf: Implement method `.swap(uint, uint)` just like vector
RingBuf::swap(&mut self, i, j) swaps the element at indices `i` and `j`
if both elements are in bounds, otherwise it fails.
-rw-r--r--src/libextra/ringbuf.rs21
1 files changed, 21 insertions, 0 deletions
diff --git a/src/libextra/ringbuf.rs b/src/libextra/ringbuf.rs
index ea8537caeb5..1e396291405 100644
--- a/src/libextra/ringbuf.rs
+++ b/src/libextra/ringbuf.rs
@@ -143,6 +143,19 @@ impl<T> RingBuf<T> {
         }
     }
 
+    /// Swap elements at indices `i` and `j`
+    ///
+    /// `i` and `j` may be equal.
+    ///
+    /// Fails if there is no element with the given index
+    pub fn swap(&mut self, i: uint, j: uint) {
+        assert!(i < self.len());
+        assert!(j < self.len());
+        let ri = self.raw_index(i);
+        let rj = self.raw_index(j);
+        self.elts.swap(ri, rj);
+    }
+
     /// Return index in underlying vec for a given logical element index
     fn raw_index(&self, idx: uint) -> uint {
         raw_index(self.lo, self.elts.len(), idx)
@@ -605,6 +618,14 @@ mod tests {
     }
 
     #[test]
+    fn test_swap() {
+        let mut d: RingBuf<int> = range(0, 5).collect();
+        d.pop_front();
+        d.swap(0, 3);
+        assert_eq!(d.iter().map(|&x|x).collect::<~[int]>(), ~[4, 2, 3, 1]);
+    }
+
+    #[test]
     fn test_iter() {
         let mut d = RingBuf::new();
         assert_eq!(d.iter().next(), None);