Skip to content

Commit

Permalink
Merge pull request #3301 from jld/vec-truncate
Browse files Browse the repository at this point in the history
Add vec::truncate, for efficiently shortening a vector.
  • Loading branch information
catamorphism committed Aug 29, 2012
2 parents 5eef15d + 3e4b558 commit ec9c68c
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/libcore/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export push, push_all, push_all_move;
export grow;
export grow_fn;
export grow_set;
export truncate;
export map;
export mapi;
export map2;
Expand Down Expand Up @@ -611,6 +612,20 @@ fn push_all_move<T>(&v: ~[const T], -rhs: ~[const T]) {
}
}

/// Shorten a vector, dropping excess elements.
fn truncate<T>(&v: ~[const T], newlen: uint) {
do as_buf(v) |p, oldlen| {
assert(newlen <= oldlen);
unsafe {
// This loop is optimized out for non-drop types.
for uint::range(newlen, oldlen) |i| {
let _dropped <- *ptr::offset(p, i);
}
unsafe::set_len(v, newlen);
}
}
}

// Appending
#[inline(always)]
pure fn append<T: copy>(+lhs: ~[T], rhs: &[const T]) -> ~[T] {
Expand Down Expand Up @@ -2166,6 +2181,15 @@ mod tests {
assert (v[4] == 5);
}

#[test]
fn test_truncate() {
let mut v = ~[@6,@5,@4];
truncate(v, 1);
assert(v.len() == 1);
assert(*(v[0]) == 6);
// If the unsafe block didn't drop things properly, we blow up here.
}

#[test]
fn test_map() {
// Test on-stack map.
Expand Down

0 comments on commit ec9c68c

Please sign in to comment.