Skip to content

Commit

Permalink
std: Make vec::from_elem failure-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
brson committed Aug 27, 2013
1 parent a8221bd commit 063d9ca
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions src/libstd/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,14 @@ pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> ~[T] {
let mut v = with_capacity(n_elts);
let p = raw::to_mut_ptr(v);
let mut i = 0u;
while i < n_elts {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), t.clone());
i += 1u;
do (|| {
while i < n_elts {
intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), t.clone());
i += 1u;
}
}).finally {
raw::set_len(&mut v, i);
}
raw::set_len(&mut v, n_elts);
v
}
}
Expand Down Expand Up @@ -3134,6 +3137,29 @@ mod tests {
};
}

#[test]
#[should_fail]
fn test_from_elem_fail() {
use cast;

struct S {
f: int,
boxes: (~int, @int)
}

impl Clone for S {
fn clone(&self) -> S {
let s = unsafe { cast::transmute_mut(self) };
s.f += 1;
if s.f == 10 { fail!() }
S { f: s.f, boxes: s.boxes.clone() }
}
}

let s = S { f: 0, boxes: (~0, @0) };
let _ = from_elem(100, s);
}

#[test]
#[should_fail]
fn test_build_fail() {
Expand Down

5 comments on commit 063d9ca

@bors
Copy link
Contributor

@bors bors commented on 063d9ca Aug 27, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

saw approval from thestinger
at brson@063d9ca

@bors
Copy link
Contributor

@bors bors commented on 063d9ca Aug 27, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging brson/rust/from_elem = 063d9ca into auto

@bors
Copy link
Contributor

@bors bors commented on 063d9ca Aug 27, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

brson/rust/from_elem = 063d9ca merged ok, testing candidate = 932d7b9

@bors
Copy link
Contributor

@bors bors commented on 063d9ca Aug 27, 2013

@bors
Copy link
Contributor

@bors bors commented on 063d9ca Aug 27, 2013

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding master to auto = 932d7b9

Please sign in to comment.