]> git.lizzy.rs Git - rust.git/commit - src/tools/miri
Auto merge of #79015 - WaffleLapkin:vec_append_from_within, r=KodrAus
authorbors <bors@rust-lang.org>
Tue, 2 Feb 2021 09:12:53 +0000 (09:12 +0000)
committerbors <bors@rust-lang.org>
Tue, 2 Feb 2021 09:12:53 +0000 (09:12 +0000)
commitf6cb45ad01a4518f615926f39801996622f46179
tree8db918c838e9374f90bc236feee71305e5d01fb6
parentd60b29d1ae8147538b8d542f7ffcc03b48e2cbda
parent125ec782bd1f5929a72ff4a520daf316db4c1e7c
Auto merge of #79015 - WaffleLapkin:vec_append_from_within, r=KodrAus

add `Vec::extend_from_within` method under `vec_extend_from_within` feature gate

Implement <https://github.com/rust-lang/rfcs/pull/2714>

### tl;dr

This PR adds a `extend_from_within` method to `Vec` which allows copying elements from a range to the end:

```rust
#![feature(vec_extend_from_within)]

let mut vec = vec![0, 1, 2, 3, 4];

vec.extend_from_within(2..);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);

vec.extend_from_within(..2);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);

vec.extend_from_within(4..8);
assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
```

### Implementation notes

Originally I've copied `@Shnatsel's` [implementation](https://github.com/WanzenBug/rle-decode-helper/blob/690742a0de158d391b7bde1a0c71cccfdad33ab3/src/lib.rs#L74) with some minor changes to support other ranges:
```rust
pub fn append_from_within<R>(&mut self, src: R)
where
    T: Copy,
    R: RangeBounds<usize>,
{
    let len = self.len();
    let Range { start, end } = src.assert_len(len);;

    let count = end - start;
    self.reserve(count);
    unsafe {
        // This is safe because `reserve()` above succeeded,
        // so `self.len() + count` did not overflow usize
        ptr::copy_nonoverlapping(
            self.get_unchecked(src.start),
            self.as_mut_ptr().add(len),
            count,
        );
        self.set_len(len + count);
    }
}
```

But then I've realized that this duplicates most of the code from (private) `Vec::append_elements`, so I've used it instead.

Then I've applied `@KodrAus` suggestions from https://github.com/rust-lang/rust/pull/79015#issuecomment-727200852.
library/alloc/src/lib.rs
library/alloc/src/vec/mod.rs
library/alloc/tests/lib.rs