Skip to content

Commit b4f07ba

Browse files
semihbkgrmgeisler
andauthored
Update unsafe trait example to zerocopy version 0.8 (#2434)
Zerocopy crate version 0.8 introduced changes to its API, which caused the example code to break. google/zerocopy#1680 > AsBytes -> [IntoBytes](https://docs.rs/zerocopy/0.8.*/zerocopy/trait.IntoBytes.html) --------- Co-authored-by: Martin Geisler <[email protected]>
1 parent b6b4381 commit b4f07ba

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

src/unsafe-rust/unsafe-traits.md

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,36 +8,31 @@ Like with functions, you can mark a trait as `unsafe` if the implementation must
88
guarantee particular conditions to avoid undefined behaviour.
99

1010
For example, the `zerocopy` crate has an unsafe trait that looks
11-
[something like this](https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html):
11+
[something like this](https://docs.rs/zerocopy/latest/zerocopy/trait.IntoBytes.html):
1212

1313
```rust,editable
14-
use std::mem::size_of_val;
15-
use std::slice;
14+
use std::{mem, slice};
1615
1716
/// ...
1817
/// # Safety
1918
/// The type must have a defined representation and no padding.
20-
pub unsafe trait AsBytes {
19+
pub unsafe trait IntoBytes {
2120
fn as_bytes(&self) -> &[u8] {
22-
unsafe {
23-
slice::from_raw_parts(
24-
self as *const Self as *const u8,
25-
size_of_val(self),
26-
)
27-
}
21+
let len = mem::size_of_val(self);
22+
unsafe { slice::from_raw_parts((&raw const self).cast::<u8>(), len) }
2823
}
2924
}
3025
3126
// SAFETY: `u32` has a defined representation and no padding.
32-
unsafe impl AsBytes for u32 {}
27+
unsafe impl IntoBytes for u32 {}
3328
```
3429

3530
<details>
3631

3732
There should be a `# Safety` section on the Rustdoc for the trait explaining the
3833
requirements for the trait to be safely implemented.
3934

40-
The actual safety section for `AsBytes` is rather longer and more complicated.
35+
The actual safety section for `IntoBytes` is rather longer and more complicated.
4136

4237
The built-in `Send` and `Sync` traits are unsafe.
4338

0 commit comments

Comments
 (0)