On Thu, Apr 18, 2024 at 9:03 AM Benno Lossin <benno.lossin@xxxxxxxxx> wrote: > > On 18.04.24 10:59, Alice Ryhl wrote: > > diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs > > index 8fad61268465..9c57c6c75553 100644 > > --- a/rust/kernel/types.rs > > +++ b/rust/kernel/types.rs > > @@ -409,3 +409,67 @@ pub enum Either<L, R> { > > /// Constructs an instance of [`Either`] containing a value of type `R`. > > Right(R), > > } > > + > > +/// Types for which any bit pattern is valid. > > +/// > > +/// Not all types are valid for all values. For example, a `bool` must be either zero or one, so > > +/// reading arbitrary bytes into something that contains a `bool` is not okay. > > +/// > > +/// It's okay for the type to have padding, as initializing those bytes has no effect. > > +/// > > +/// # Safety > > +/// > > +/// All bit-patterns must be valid for this type. This type must not have interior mutability. > > What is the reason for disallowing interior mutability here? I agree > that it is necessary for `AsBytes`, but I don't think we need it here. > For example it is fine to convert `u8` to `UnsafeCell<u8>`. Niches also > should not be a problem, since eg `Option<UnsafeCell<NonNull<u8>>>` > already fails the "All bit-patterns must be valid for this type". > > -- > Cheers, > Benno > > > +pub unsafe trait FromBytes {} See also the reasoning in zerocopy [1] and bytemuck [2] [1]: https://docs.rs/zerocopy/latest/zerocopy/derive.FromBytes.html#analysis [2]: https://docs.rs/bytemuck/latest/bytemuck/trait.AnyBitPattern.html#safety