Skip to content

Optimize behavior of vec.split_off(0) (take all) #76682

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 15, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions library/alloc/src/vec.rs
Original file line number Diff line number Diff line change
@@ -1410,6 +1410,11 @@ impl<T> Vec<T> {
assert_failed(at, self.len());
}

if at == 0 {
// the new vector can take over the original buffer and avoid the copy
return mem::replace(self, Vec::with_capacity(self.capacity()));
}

let other_len = self.len - at;
let mut other = Vec::with_capacity(other_len);

4 changes: 4 additions & 0 deletions library/alloc/tests/string.rs
Original file line number Diff line number Diff line change
@@ -278,17 +278,21 @@ fn test_split_off_mid_char() {
#[test]
fn test_split_off_ascii() {
let mut ab = String::from("ABCD");
let orig_capacity = ab.capacity();
let cd = ab.split_off(2);
assert_eq!(ab, "AB");
assert_eq!(cd, "CD");
assert_eq!(ab.capacity(), orig_capacity);
}

#[test]
fn test_split_off_unicode() {
let mut nihon = String::from("日本語");
let orig_capacity = nihon.capacity();
let go = nihon.split_off("日本".len());
assert_eq!(nihon, "日本");
assert_eq!(go, "語");
assert_eq!(nihon.capacity(), orig_capacity);
}

#[test]
14 changes: 14 additions & 0 deletions library/alloc/tests/vec.rs
Original file line number Diff line number Diff line change
@@ -772,9 +772,23 @@ fn test_append() {
#[test]
fn test_split_off() {
let mut vec = vec![1, 2, 3, 4, 5, 6];
let orig_capacity = vec.capacity();
let vec2 = vec.split_off(4);
assert_eq!(vec, [1, 2, 3, 4]);
assert_eq!(vec2, [5, 6]);
assert_eq!(vec.capacity(), orig_capacity);
}

#[test]
fn test_split_off_take_all() {
let mut vec = vec![1, 2, 3, 4, 5, 6];
let orig_ptr = vec.as_ptr();
let orig_capacity = vec.capacity();
let vec2 = vec.split_off(0);
assert_eq!(vec, []);
assert_eq!(vec2, [1, 2, 3, 4, 5, 6]);
assert_eq!(vec.capacity(), orig_capacity);
assert_eq!(vec2.as_ptr(), orig_ptr);
}

#[test]