From b4f07baf81c121093aa8e62b2ac5e2e9b8cbe9fd Mon Sep 17 00:00:00 2001 From: Semih Buyukgungor Date: Mon, 4 Nov 2024 14:01:45 +0300 Subject: [PATCH] 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. https://github.com/google/zerocopy/discussions/1680 > AsBytes -> [IntoBytes](https://docs.rs/zerocopy/0.8.*/zerocopy/trait.IntoBytes.html) --------- Co-authored-by: Martin Geisler --- src/unsafe-rust/unsafe-traits.md | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/unsafe-rust/unsafe-traits.md b/src/unsafe-rust/unsafe-traits.md index f2ccdd2a..ba279b13 100644 --- a/src/unsafe-rust/unsafe-traits.md +++ b/src/unsafe-rust/unsafe-traits.md @@ -8,28 +8,23 @@ Like with functions, you can mark a trait as `unsafe` if the implementation must guarantee particular conditions to avoid undefined behaviour. For example, the `zerocopy` crate has an unsafe trait that looks -[something like this](https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html): +[something like this](https://docs.rs/zerocopy/latest/zerocopy/trait.IntoBytes.html): ```rust,editable -use std::mem::size_of_val; -use std::slice; +use std::{mem, slice}; /// ... /// # Safety /// The type must have a defined representation and no padding. -pub unsafe trait AsBytes { +pub unsafe trait IntoBytes { fn as_bytes(&self) -> &[u8] { - unsafe { - slice::from_raw_parts( - self as *const Self as *const u8, - size_of_val(self), - ) - } + let len = mem::size_of_val(self); + unsafe { slice::from_raw_parts((&raw const self).cast::(), len) } } } // SAFETY: `u32` has a defined representation and no padding. -unsafe impl AsBytes for u32 {} +unsafe impl IntoBytes for u32 {} ```
@@ -37,7 +32,7 @@ unsafe impl AsBytes for u32 {} There should be a `# Safety` section on the Rustdoc for the trait explaining the requirements for the trait to be safely implemented. -The actual safety section for `AsBytes` is rather longer and more complicated. +The actual safety section for `IntoBytes` is rather longer and more complicated. The built-in `Send` and `Sync` traits are unsafe.