diff options
| author | Steve Klabnik <steve@steveklabnik.com> | 2017-02-07 19:08:12 -0500 |
|---|---|---|
| committer | Steve Klabnik <steve@steveklabnik.com> | 2017-02-13 13:41:10 -0500 |
| commit | 22d4adf14aabfb0ea0cfc8daff203e8d474cbc52 (patch) | |
| tree | 47e38ca93da0581bf477919da94d422e469d55ee /src/doc/nomicon/vec-insert-remove.md | |
| parent | e943e68a47dfbdd73d34f3b40e628f3031f90b6a (diff) | |
| download | rust-22d4adf14aabfb0ea0cfc8daff203e8d474cbc52.tar.gz rust-22d4adf14aabfb0ea0cfc8daff203e8d474cbc52.zip | |
Port Nomicon to mdbook
1. move everything under a src directory 2. add README.md to the SUMMARY.md
Diffstat (limited to 'src/doc/nomicon/vec-insert-remove.md')
| -rw-r--r-- | src/doc/nomicon/vec-insert-remove.md | 51 |
1 files changed, 0 insertions, 51 deletions
diff --git a/src/doc/nomicon/vec-insert-remove.md b/src/doc/nomicon/vec-insert-remove.md deleted file mode 100644 index bcecd78a1b7..00000000000 --- a/src/doc/nomicon/vec-insert-remove.md +++ /dev/null @@ -1,51 +0,0 @@ -% Insert and Remove - -Something *not* provided by slice is `insert` and `remove`, so let's do those -next. - -Insert needs to shift all the elements at the target index to the right by one. -To do this we need to use `ptr::copy`, which is our version of C's `memmove`. -This copies some chunk of memory from one location to another, correctly -handling the case where the source and destination overlap (which will -definitely happen here). - -If we insert at index `i`, we want to shift the `[i .. len]` to `[i+1 .. len+1]` -using the old len. - -```rust,ignore -pub fn insert(&mut self, index: usize, elem: T) { - // Note: `<=` because it's valid to insert after everything - // which would be equivalent to push. - assert!(index <= self.len, "index out of bounds"); - if self.cap == self.len { self.grow(); } - - unsafe { - if index < self.len { - // ptr::copy(src, dest, len): "copy from source to dest len elems" - ptr::copy(self.ptr.offset(index as isize), - self.ptr.offset(index as isize + 1), - self.len - index); - } - ptr::write(self.ptr.offset(index as isize), elem); - self.len += 1; - } -} -``` - -Remove behaves in the opposite manner. We need to shift all the elements from -`[i+1 .. len + 1]` to `[i .. len]` using the *new* len. - -```rust,ignore -pub fn remove(&mut self, index: usize) -> T { - // Note: `<` because it's *not* valid to remove after everything - assert!(index < self.len, "index out of bounds"); - unsafe { - self.len -= 1; - let result = ptr::read(self.ptr.offset(index as isize)); - ptr::copy(self.ptr.offset(index as isize + 1), - self.ptr.offset(index as isize), - self.len - index); - result - } -} -``` |
