Skip to content

Commit

Permalink
Document that writes to padding are not preserved
Browse files Browse the repository at this point in the history
Document that writes to padding bytes are not preserved when an object
is moved or copied.

Makes progress on #1648
  • Loading branch information
joshlf committed Sep 15, 2024
1 parent f998114 commit a0fee44
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1953,6 +1953,15 @@ fn swap<T, U>((t, u): (T, U)) -> (U, T) {
/// overhead. This is useful whenever memory is known to be in a zeroed state,
/// such memory returned from some allocation routines.
///
/// # Warning: Padding bytes
///
/// Note that, when an object is moved or copied, only the non-padding bytes of
/// that object are guaranteed to be preserved. It is unsound to assume that
/// values written to padding bytes are preserved after a move or copy. For more
/// details, see the [`FromBytes` docs][frombytes-warning-padding-bytes].
///
/// [frombytes-warning-padding-bytes]: FromBytes#warning-padding-bytes
///
/// # Implementation
///
/// **Do not implement this trait yourself!** Instead, use
Expand Down Expand Up @@ -2431,6 +2440,27 @@ pub use zerocopy_derive::FromBytes;
/// can be viewed as any `FromBytes` type with no runtime overhead. This is
/// useful for efficiently parsing bytes as structured data.
///
/// # Warning: Padding bytes
///
/// Note that, when an object is moved or copied, only the non-padding bytes of
/// that object are guaranteed to be preserved. It is unsound to assume that
/// values written to padding bytes are preserved after a move or copy. For
/// example, the following is unsound:
///
/// ```rust,no_run
/// # use {zerocopy::FromZeros, zerocopy_derive::FromZeros, core::mem::MaybeUninit};
/// # #[derive(FromZeros)]
/// # struct Foo(MaybeUninit<u8>);
/// # impl Foo { fn new() -> Foo { Foo(MaybeUninit::uninit()) } }
/// // Assume `Foo` is a type with padding bytes.
/// let mut foo: Foo = Foo::new();
/// FromZeros::zero(&mut foo);
/// // UNSOUND: Although `FromZeros::zero` writes zeros to all bytes of `foo`,
/// // those writes are not guaranteed to be preserved in padding bytes when
/// // `foo` is moved, so this may expose padding bytes as `u8`s.
/// let foo_bytes: [u8; size_of::<Foo>()] = unsafe { core::mem::transmute(foo) };
/// ```
///
/// # Implementation
///
/// **Do not implement this trait yourself!** Instead, use
Expand Down

0 comments on commit a0fee44

Please sign in to comment.