Skip to content

Commit 17531a6

Browse files
committed
Correct code for operations on empty Vecs
1 parent d86b6f6 commit 17531a6

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/libcollections/vec.rs

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -473,8 +473,10 @@ impl<T> Vec<T> {
473473
let begin = ptr as *const T;
474474
let end = if mem::size_of::<T>() == 0 {
475475
(ptr as usize + self.len()) as *const T
476+
} else if self.cap == 0 {
477+
begin
476478
} else {
477-
ptr.offset(self.len() as isize) as *const T
479+
begin.offset(self.len() as isize)
478480
};
479481
mem::forget(self);
480482
IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
@@ -772,6 +774,8 @@ impl<T> Vec<T> {
772774
let begin = *self.ptr as *const T;
773775
let end = if mem::size_of::<T>() == 0 {
774776
(*self.ptr as usize + self.len()) as *const T
777+
} else if self.cap == 0 {
778+
begin
775779
} else {
776780
(*self.ptr).offset(self.len() as isize) as *const T
777781
};
@@ -883,16 +887,23 @@ impl<T> Vec<T> {
883887
//
884888
// 2) If the size of the elements in the vector is >1, the `usize` ->
885889
// `isize` conversion can't overflow.
886-
let offset = vec.len() as isize;
887890
let start = vec.as_mut_ptr();
888891

892+
let end = if vec.cap == 0 {
893+
start
894+
} else {
895+
unsafe {
896+
start.offset(vec.len() as isize)
897+
}
898+
};
899+
889900
let mut pv = PartialVecNonZeroSized {
890901
vec: vec,
891902

892903
start_t: start,
893904
// This points inside the vector, as the vector has length
894905
// `offset`.
895-
end_t: unsafe { start.offset(offset) },
906+
end_t: end,
896907
start_u: start as *mut U,
897908
end_u: start as *mut U,
898909

@@ -1054,17 +1065,18 @@ impl<T> Vec<T> {
10541065
assert!(at <= self.len(), "`at` out of bounds");
10551066

10561067
let other_len = self.len - at;
1068+
let ptr = if self.cap == 0 {
1069+
self.as_ptr()
1070+
} else {
1071+
self.as_ptr().offset(at as isize)
1072+
};
10571073
let mut other = Vec::with_capacity(other_len);
10581074

10591075
// Unsafely `set_len` and copy items to `other`.
10601076
unsafe {
10611077
self.set_len(at);
10621078
other.set_len(other_len);
1063-
1064-
ptr::copy_nonoverlapping(
1065-
self.as_ptr().offset(at as isize),
1066-
other.as_mut_ptr(),
1067-
other.len());
1079+
ptr::copy_nonoverlapping(ptr, other.as_mut_ptr(), other.len());
10681080
}
10691081
other
10701082
}

0 commit comments

Comments
 (0)