From 27e6be5ae563f09bf7bba47f73573f19d71c3767 Mon Sep 17 00:00:00 2001 From: Gareth Daniel Smith Date: Sun, 25 Nov 2012 13:28:16 +0000 Subject: [PATCH] Add insert and remove methods to vecs - as proposed in issue #4028. --- src/libcore/vec.rs | 86 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 8e99317468def..7ea63ae40a2b9 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -419,6 +419,34 @@ pub fn unshift(v: &mut ~[T], x: T) { v.push_all_move(move vv); } +/// Insert an element at position i within v, shifting all +/// elements after position i one position to the right. +pub fn insert(v: &mut ~[T], i: uint, x: T) { + let len = v.len(); + assert i <= len; + + v.push(move x); + let mut j = len; + while j > i { + v[j] <-> v[j - 1]; + j -= 1; + } +} + +/// Remove and return the element at position i within v, shifting +/// all elements after position i one position to the left. +pub fn remove(v: &mut ~[T], i: uint) -> T { + let len = v.len(); + assert i < len; + + let mut j = i; + while j < len - 1 { + v[j] <-> v[j + 1]; + j += 1; + } + move v.pop() +} + pub fn consume(v: ~[T], f: fn(uint, v: T)) unsafe { let mut v = move v; // FIXME(#3488) @@ -1685,6 +1713,8 @@ pub trait MutableVector { fn pop(&mut self) -> T; fn shift(&mut self) -> T; fn unshift(&mut self, x: T); + fn insert(&mut self, i: uint, x:T); + fn remove(&mut self, i: uint) -> T; fn swap_remove(&mut self, index: uint) -> T; fn truncate(&mut self, newlen: uint); fn retain(&mut self, f: pure fn(t: &T) -> bool); @@ -1722,6 +1752,14 @@ impl ~[T]: MutableVector { unshift(self, move x) } + fn insert(&mut self, i: uint, x:T) { + insert(self, i, move x) + } + + fn remove(&mut self, i: uint) -> T { + remove(self, i) + } + fn swap_remove(&mut self, index: uint) -> T { swap_remove(self, index) } @@ -2925,6 +2963,54 @@ mod tests { assert x == ~[0, 1, 2, 3]; } + #[test] + fn test_insert() { + let mut a = ~[1, 2, 4]; + a.insert(2, 3); + assert a == ~[1, 2, 3, 4]; + + let mut a = ~[1, 2, 3]; + a.insert(0, 0); + assert a == ~[0, 1, 2, 3]; + + let mut a = ~[1, 2, 3]; + a.insert(3, 4); + assert a == ~[1, 2, 3, 4]; + + let mut a = ~[]; + a.insert(0, 1); + assert a == ~[1]; + } + + #[test] + #[should_fail] + fn test_insert_oob() { + let mut a = ~[1, 2, 3]; + a.insert(4, 5); + } + + #[test] + fn test_remove() { + let mut a = ~[1, 2, 3, 4]; + a.remove(2); + assert a == ~[1, 2, 4]; + + let mut a = ~[1, 2, 3]; + a.remove(0); + assert a == ~[2, 3]; + + let mut a = ~[1]; + a.remove(0); + assert a == ~[]; + } + + #[test] + #[should_fail] + fn test_remove_oob() { + let mut a = ~[1, 2, 3]; + a.remove(3); + } + #[test] fn test_capacity() { let mut v = ~[0u64];