-
Notifications
You must be signed in to change notification settings - Fork 124
Description
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 implementKnownLayout
too - Do one of the following:
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>
whereInitialized: IntoBytes
even whenT: !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
- What if we want to copy from a
&T
(which we can't modify) into a buffer while initializing any padding bytes in the destination like musli-zerocopy does? See this discussion.