Skip to content

Commit

Permalink
Merge pull request rust-lang#2201 from SuperSamus/patch-1
Browse files Browse the repository at this point in the history
Listing 19-6: use ptr.add instead of ptr.offset
  • Loading branch information
steveklabnik authored Jan 30, 2020
2 parents 1d0b5e6 + f58d939 commit f4c7cfc
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion listings/ch19-advanced-features/listing-19-06/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
unsafe {
(
slice::from_raw_parts_mut(ptr, mid),
slice::from_raw_parts_mut(ptr.offset(mid as isize), len - mid),
slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/ch19-01-unsafe-rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,16 +256,16 @@ mutable slice to `i32` values, `as_mut_ptr` returns a raw pointer with the type
We keep the assertion that the `mid` index is within the slice. Then we get to
the unsafe code: the `slice::from_raw_parts_mut` function takes a raw pointer
and a length, and it creates a slice. We use this function to create a slice
that starts from `ptr` and is `mid` items long. Then we call the `offset`
that starts from `ptr` and is `mid` items long. Then we call the `add`
method on `ptr` with `mid` as an argument to get a raw pointer that starts at
`mid`, and we create a slice using that pointer and the remaining number of
items after `mid` as the length.

The function `slice::from_raw_parts_mut` is unsafe because it takes a raw
pointer and must trust that this pointer is valid. The `offset` method on raw
pointer and must trust that this pointer is valid. The `add` method on raw
pointers is also unsafe, because it must trust that the offset location is also
a valid pointer. Therefore, we had to put an `unsafe` block around our calls to
`slice::from_raw_parts_mut` and `offset` so we could call them. By looking at
`slice::from_raw_parts_mut` and `add` so we could call them. By looking at
the code and by adding the assertion that `mid` must be less than or equal to
`len`, we can tell that all the raw pointers used within the `unsafe` block
will be valid pointers to data within the slice. This is an acceptable and
Expand Down

0 comments on commit f4c7cfc

Please sign in to comment.