Skip to content

Commit f4c7cfc

Browse files
authored
Merge pull request #2201 from SuperSamus/patch-1
Listing 19-6: use ptr.add instead of ptr.offset
2 parents 1d0b5e6 + f58d939 commit f4c7cfc

File tree

2 files changed

+4
-4
lines changed

2 files changed

+4
-4
lines changed

listings/ch19-advanced-features/listing-19-06/src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
1010
unsafe {
1111
(
1212
slice::from_raw_parts_mut(ptr, mid),
13-
slice::from_raw_parts_mut(ptr.offset(mid as isize), len - mid),
13+
slice::from_raw_parts_mut(ptr.add(mid), len - mid),
1414
)
1515
}
1616
}

src/ch19-01-unsafe-rust.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -256,16 +256,16 @@ mutable slice to `i32` values, `as_mut_ptr` returns a raw pointer with the type
256256
We keep the assertion that the `mid` index is within the slice. Then we get to
257257
the unsafe code: the `slice::from_raw_parts_mut` function takes a raw pointer
258258
and a length, and it creates a slice. We use this function to create a slice
259-
that starts from `ptr` and is `mid` items long. Then we call the `offset`
259+
that starts from `ptr` and is `mid` items long. Then we call the `add`
260260
method on `ptr` with `mid` as an argument to get a raw pointer that starts at
261261
`mid`, and we create a slice using that pointer and the remaining number of
262262
items after `mid` as the length.
263263

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

0 commit comments

Comments
 (0)