Skip to content

Commit f210a16

Browse files
committed
auto merge of #9520 : blake2-ppc/rust/ringbuf-swap, r=thestinger
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.
2 parents 47f2e80 + 57757a8 commit f210a16

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/libextra/ringbuf.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,19 @@ impl<T> RingBuf<T> {
143143
}
144144
}
145145

146+
/// Swap elements at indices `i` and `j`
147+
///
148+
/// `i` and `j` may be equal.
149+
///
150+
/// Fails if there is no element with the given index
151+
pub fn swap(&mut self, i: uint, j: uint) {
152+
assert!(i < self.len());
153+
assert!(j < self.len());
154+
let ri = self.raw_index(i);
155+
let rj = self.raw_index(j);
156+
self.elts.swap(ri, rj);
157+
}
158+
146159
/// Return index in underlying vec for a given logical element index
147160
fn raw_index(&self, idx: uint) -> uint {
148161
raw_index(self.lo, self.elts.len(), idx)
@@ -604,6 +617,14 @@ mod tests {
604617
assert_eq!(d.elts.capacity(), 64);
605618
}
606619

620+
#[test]
621+
fn test_swap() {
622+
let mut d: RingBuf<int> = range(0, 5).collect();
623+
d.pop_front();
624+
d.swap(0, 3);
625+
assert_eq!(d.iter().map(|&x|x).collect::<~[int]>(), ~[4, 2, 3, 1]);
626+
}
627+
607628
#[test]
608629
fn test_iter() {
609630
let mut d = RingBuf::new();

0 commit comments

Comments
 (0)