Skip to content

Provide the ability to zero padding bytes and return &Initialized<T> #494

@joshlf

Description

@joshlf

Note: We likely won't do this. See the conversation below for the full context, but TL;DR: We'd need for any KnownLayout type to require that all of its fields also implement KnownLayout, which we don't currently require. We expect that the freeze language feature will land soon enough that it's not worth worsening KnownLayout's UX to support this use case.

Progress

  • Update this issue description per this comment
  • Update KnownLayout to require that fields implement KnownLayout too
  • Do one of the following:
    • Decide that the freeze intrinsic (RFC 3605) will land and stabilize soon enough that we can rely on it instead; relax KnownLayout to not be recursive (and watch out for #1162)
    • Use the recursive KnownLayout requirement to implement this design

Details

Issues like this one demonstrate that it is sometimes useful to access the bytes of a type which cannot implement AsBytes. In these cases, it should be sound to:

  • Recursively zero any inter-field padding bytes
  • Provide access to the bytes of the object as an &Initialized<T> where Initialized: IntoBytes even when T: !IntoBytes

We would need to teach KnownLayout to be able to zero padding, e.g.:

pub unsafe trait KnownLayout {
    fn zero_padding(&mut self) -> &mut Initialized<Self>;
}

#[repr(transparent)]
pub struct Initialized<T> {
    // INVARIANT: Every byte in `inner` is initialized. Note that this implies
    // that an `Initialized` cannot be moved by value unless `T: IntoBytes`
    // since typed copies de-initialize padding bytes.
    inner: T,
}

unsafe impl<T> IntoBytes for Initialized<T> {}

impl<T> Deref for Initialized<T> { ... }

// INVARIANT: Since `T: IntoBytes`, any value that is written via this impl
// has no padding bytes, and so will not invalidate the invariant that all of
// `inner`'s bytes are initialized.
impl<T: IntoBytes> DerefMut for Initialized<T> { ... }

// TODO: Provide field projection

The only requirement for a type supporting this operation is that we know where its padding bytes are. The public API for this type could be in KnownLayout.

As of this writing, KnownLayout does not require that a type's fields also be KnownLayout. We are planning to add that requirement in order to support this design.

Open questions

Related & prior art

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions