Skip to content

Commit 51a2efb

Browse files
cuviperMark-Simulacrumtgross35
authored
Apply suggestions from code review
Co-authored-by: Mark Rousskov <[email protected]> Co-authored-by: Trevor Gross <[email protected]>
1 parent 61f2fe2 commit 51a2efb

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

posts/2024-05-02-Rust-1.78.0.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -84,20 +84,21 @@ For more information, see the reference section on [the `diagnostic` tool attrib
8484

8585
### Asserting `unsafe` preconditions
8686

87-
The Rust standard library has a number of assertions for the preconditions of `unsafe` functions, but historically they have only been enabled in `#[cfg(debug_assertions)]` builds to avoid affecting release performance. However, since the standard library is usually compiled and distributed in release mode, most Rust developers weren't ever executing these checks at all.
87+
The Rust standard library has a number of assertions for the preconditions of `unsafe` functions, but historically they have only been enabled in `#[cfg(debug_assertions)]` builds of the standard library to avoid affecting release performance. However, since the standard library is usually compiled and distributed in release mode, most Rust developers weren't ever executing these checks at all.
8888

8989
Now, the condition for these assertions is delayed until code generation, so they will be checked depending on the user's own setting for debug assertions -- enabled by default in debug and test builds. This change helps users catch undefined behavior in their code, though the details of how much is checked are generally not stable.
9090

91-
For example, [`slice::from_raw_parts`](https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html) requires an aligned non-null pointer. The following use of a purposely-misaligned pointer has undefined behavior, _which may or may not cause noticeable ill effect otherwise_, but the debug assertion can now catch it:
91+
For example, [`slice::from_raw_parts`](https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html) requires an aligned non-null pointer. The following use of a purposely-misaligned pointer has undefined behavior, and while that may not have obvious effects, the debug assertion can now catch it:
9292

9393
```rust
9494
fn main() {
9595
let slice: &[u8] = &[1, 2, 3, 4, 5];
96-
let slice16: &[u16] = unsafe {
97-
let ptr = slice.as_ptr();
98-
let i = usize::from(ptr as usize & 1 == 0);
99-
std::slice::from_raw_parts(ptr.add(i) as *const u16, 2)
100-
};
96+
let ptr = slice.as_ptr();
97+
98+
// Create an offset from `ptr` that will always be one off from `u16`'s correct alignment
99+
let i = usize::from(ptr as usize & 1 == 0);
100+
101+
let slice16: &[u16] = unsafe { std::slice::from_raw_parts(ptr.add(i).cast::<u16>(), 2) };
101102
dbg!(slice16);
102103
}
103104
```

0 commit comments

Comments
 (0)