2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
|
minutes: 5
|
|
|
|
|
---
|
|
|
|
|
|
2023-01-17 16:41:51 +00:00
|
|
|
# Implementing Unsafe Traits
|
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
Like with functions, you can mark a trait as `unsafe` if the implementation must
|
|
|
|
|
guarantee particular conditions to avoid undefined behaviour.
|
2023-01-17 16:41:51 +00:00
|
|
|
|
|
|
|
|
For example, the `zerocopy` crate has an unsafe trait that looks
|
|
|
|
|
[something like this](https://docs.rs/zerocopy/latest/zerocopy/trait.AsBytes.html):
|
|
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
|
use std::mem::size_of_val;
|
|
|
|
|
use std::slice;
|
|
|
|
|
|
|
|
|
|
/// ...
|
|
|
|
|
/// # Safety
|
|
|
|
|
/// The type must have a defined representation and no padding.
|
|
|
|
|
pub unsafe trait AsBytes {
|
|
|
|
|
fn as_bytes(&self) -> &[u8] {
|
|
|
|
|
unsafe {
|
2023-12-31 00:15:07 +01:00
|
|
|
slice::from_raw_parts(
|
|
|
|
|
self as *const Self as *const u8,
|
|
|
|
|
size_of_val(self),
|
|
|
|
|
)
|
2023-01-17 16:41:51 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Safe because u32 has a defined representation and no padding.
|
|
|
|
|
unsafe impl AsBytes for u32 {}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
<details>
|
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
There should be a `# Safety` section on the Rustdoc for the trait explaining the
|
|
|
|
|
requirements for the trait to be safely implemented.
|
2023-01-17 16:41:51 +00:00
|
|
|
|
|
|
|
|
The actual safety section for `AsBytes` is rather longer and more complicated.
|
|
|
|
|
|
|
|
|
|
The built-in `Send` and `Sync` traits are unsafe.
|
|
|
|
|
|
|
|
|
|
</details>
|