Skip to content

Commit

Permalink
Traits other than NoCell permit UnsafeCells (#682)
Browse files Browse the repository at this point in the history
Previously, `FromZeros`, `FromBytes`, and `AsBytes` could not be
implemented for types containing `UnsafeCell`s. This is a soundness
precondition for some types of reference transmutations (notably
transmuting either direction between `&[u8]` and `&T`). However, some of
our machinery operates only on values (e.g. `transmute!`), and that
machinery should in principle be able to support types which contain
`UnsafeCell`s.

In this commit, we remove the "no `UnsafeCell`" restriction from
`FromZeros`, `FromBytes`, and `AsBytes`. We use the recently-added
`NoCell` trait as a bound on individual functions and methods where
`UnsafeCell`s would be unsound. This permits some APIs to support
`UnsafeCell`s which could not previously support them.

Closes #251
  • Loading branch information
joshlf committed Dec 8, 2023
1 parent 5e77f3c commit a8572da
Show file tree
Hide file tree
Showing 85 changed files with 1,175 additions and 694 deletions.
8 changes: 4 additions & 4 deletions src/byteorder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@
//!
//! ```rust,edition2021
//! # #[cfg(feature = "derive")] { // This example uses derives, and won't compile without them
//! use zerocopy::{AsBytes, ByteSlice, FromBytes, FromZeros, Ref, Unaligned};
//! use zerocopy::{AsBytes, ByteSlice, FromBytes, FromZeros, NoCell, Ref, Unaligned};
//! use zerocopy::byteorder::network_endian::U16;
//!
//! #[derive(FromZeros, FromBytes, AsBytes, Unaligned)]
//! #[derive(FromZeros, FromBytes, AsBytes, NoCell, Unaligned)]
//! #[repr(C)]
//! struct UdpHeader {
//! src_port: U16,
Expand Down Expand Up @@ -655,7 +655,7 @@ mod tests {
use compatibility::*;

// A native integer type (u16, i32, etc).
trait Native: Arbitrary + FromBytes + AsBytes + Copy + PartialEq + Debug {
trait Native: Arbitrary + FromBytes + AsBytes + NoCell + Copy + PartialEq + Debug {
const ZERO: Self;
const MAX_VALUE: Self;

Expand Down Expand Up @@ -692,7 +692,7 @@ mod tests {
}

trait ByteArray:
FromBytes + AsBytes + Copy + AsRef<[u8]> + AsMut<[u8]> + Debug + Default + Eq
FromBytes + AsBytes + NoCell + Copy + AsRef<[u8]> + AsMut<[u8]> + Debug + Default + Eq
{
/// Invert the order of the bytes in the array.
fn invert(self) -> Self;
Expand Down

0 comments on commit a8572da

Please sign in to comment.