Trait FromBytes
unsafe trait FromBytes: FromZeros
Types for which any bit pattern is valid.
Any memory region of the appropriate length which contains initialized bytes
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 a value is moved or copied, only the non-padding bytes of that value 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:
use ;
use FromZeros;
# use *;
// Assume `Foo` is a type with padding bytes.
let mut foo: Foo = default;
zero;
// 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: = unsafe ;
Implementation
Do not implement this trait yourself! Instead, use
#[derive(FromBytes)]; e.g.:
# use ;
union MyUnion
This derive performs a sophisticated, compile-time safety analysis to
determine whether a type is FromBytes.
Safety
This section describes what is required in order for T: FromBytes, and
what unsafe code may assume of such types. If you don't plan on implementing
FromBytes manually, and you don't plan on writing unsafe code that
operates on FromBytes types, then you don't need to read this section.
If T: FromBytes, then unsafe code may assume that it is sound to produce a
T whose bytes are initialized to any sequence of valid u8s (in other
words, any byte value which is not uninitialized). If a type is marked as
FromBytes which violates this contract, it may cause undefined behavior.
#[derive(FromBytes)] only permits types which satisfy these
requirements.
Provided Methods
fn ref_from_bytes(source: &[u8]) -> Result<&Self, CastError<&[u8], Self>> where Self: KnownLayout + ImmutableInterprets the given
sourceas a&Self.This method attempts to return a reference to
sourceinterpreted as aSelf. If the length ofsourceis not a valid size ofSelf, or ifsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Selfmay be a sized type, a slice, or a slice DST.Compile-Time Assertions
This method cannot yet be used on unsized types whose dynamically-sized component is zero-sized. Attempting to use this method on such types results in a compile-time assertion error; e.g.:
use zerocopy::*; # use zerocopy_derive::*; #[derive(FromBytes, Immutable, KnownLayout)] #[repr(C)] struct ZSTy { leading_sized: u16, trailing_dst: [()], } let _ = ZSTy::ref_from_bytes(0u16.as_bytes()); // ⚠ Compile Error!Examples
use FromBytes; # use *; // These bytes encode a `Packet`. let bytes = &; let packet = ref_from_bytes.unwrap; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn ref_from_prefix(source: &[u8]) -> Result<(&Self, &[u8]), CastError<&[u8], Self>> where Self: KnownLayout + ImmutableInterprets the prefix of the given
sourceas a&Selfwithout copying.This method computes the largest possible size of
Selfthat can fit in the leading bytes ofsource, then attempts to return both a reference to those bytes interpreted as aSelf, and a reference to the remaining bytes. If there are insufficient bytes, or ifsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Selfmay be a sized type, a slice, or a slice DST.Compile-Time Assertions
This method cannot yet be used on unsized types whose dynamically-sized component is zero-sized. See
ref_from_prefix_with_elems, which does support such types. Attempting to use this method on such types results in a compile-time assertion error; e.g.:use zerocopy::*; # use zerocopy_derive::*; #[derive(FromBytes, Immutable, KnownLayout)] #[repr(C)] struct ZSTy { leading_sized: u16, trailing_dst: [()], } let _ = ZSTy::ref_from_prefix(0u16.as_bytes()); // ⚠ Compile Error!Examples
use FromBytes; # use *; // These are more bytes than are needed to encode a `Packet`. let bytes = &; let = ref_from_prefix.unwrap; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn ref_from_suffix(source: &[u8]) -> Result<(&[u8], &Self), CastError<&[u8], Self>> where Self: Immutable + KnownLayoutInterprets the suffix of the given bytes as a
&Self.This method computes the largest possible size of
Selfthat can fit in the trailing bytes ofsource, then attempts to return both a reference to those bytes interpreted as aSelf, and a reference to the preceding bytes. If there are insufficient bytes, or if that suffix ofsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Selfmay be a sized type, a slice, or a slice DST.Compile-Time Assertions
This method cannot yet be used on unsized types whose dynamically-sized component is zero-sized. See
ref_from_suffix_with_elems, which does support such types. Attempting to use this method on such types results in a compile-time assertion error; e.g.:use zerocopy::*; # use zerocopy_derive::*; #[derive(FromBytes, Immutable, KnownLayout)] #[repr(C)] struct ZSTy { leading_sized: u16, trailing_dst: [()], } let _ = ZSTy::ref_from_suffix(0u16.as_bytes()); // ⚠ Compile Error!Examples
use FromBytes; # use *; // These are more bytes than are needed to encode a `PacketTrailer`. let bytes = &; let = ref_from_suffix.unwrap; assert_eq!; assert_eq!;fn mut_from_bytes(source: &mut [u8]) -> Result<&mut Self, CastError<&mut [u8], Self>> where Self: IntoBytes + KnownLayoutInterprets the given
sourceas a&mut Self.This method attempts to return a reference to
sourceinterpreted as aSelf. If the length ofsourceis not a valid size ofSelf, or ifsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Selfmay be a sized type, a slice, or a slice DST.Compile-Time Assertions
This method cannot yet be used on unsized types whose dynamically-sized component is zero-sized. See
mut_from_prefix_with_elems, which does support such types. Attempting to use this method on such types results in a compile-time assertion error; e.g.:use zerocopy::*; # use zerocopy_derive::*; #[derive(FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] struct ZSTy { leading_sized: [u8; 2], trailing_dst: [()], } let mut source = [85, 85]; let _ = ZSTy::mut_from_bytes(&mut source[..]); // ⚠ Compile Error!Examples
use FromBytes; # use *; // These bytes encode a `PacketHeader`. let bytes = &mut ; let header = mut_from_bytes.unwrap; assert_eq!; assert_eq!; assert_eq!; assert_eq!; header.checksum = ; assert_eq!;fn mut_from_prefix(source: &mut [u8]) -> Result<(&mut Self, &mut [u8]), CastError<&mut [u8], Self>> where Self: IntoBytes + KnownLayoutInterprets the prefix of the given
sourceas a&mut Selfwithout copying.This method computes the largest possible size of
Selfthat can fit in the leading bytes ofsource, then attempts to return both a reference to those bytes interpreted as aSelf, and a reference to the remaining bytes. If there are insufficient bytes, or ifsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Selfmay be a sized type, a slice, or a slice DST.Compile-Time Assertions
This method cannot yet be used on unsized types whose dynamically-sized component is zero-sized. See
mut_from_suffix_with_elems, which does support such types. Attempting to use this method on such types results in a compile-time assertion error; e.g.:use zerocopy::*; # use zerocopy_derive::*; #[derive(FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] struct ZSTy { leading_sized: [u8; 2], trailing_dst: [()], } let mut source = [85, 85]; let _ = ZSTy::mut_from_prefix(&mut source[..]); // ⚠ Compile Error!Examples
use FromBytes; # use *; // These are more bytes than are needed to encode a `PacketHeader`. let bytes = &mut ; let = mut_from_prefix.unwrap; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!; header.checksum = ; body.fill; assert_eq!;fn mut_from_suffix(source: &mut [u8]) -> Result<(&mut [u8], &mut Self), CastError<&mut [u8], Self>> where Self: IntoBytes + KnownLayoutInterprets the suffix of the given
sourceas a&mut Selfwithout copying.This method computes the largest possible size of
Selfthat can fit in the trailing bytes ofsource, then attempts to return both a reference to those bytes interpreted as aSelf, and a reference to the preceding bytes. If there are insufficient bytes, or if that suffix ofsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Selfmay be a sized type, a slice, or a slice DST.Compile-Time Assertions
This method cannot yet be used on unsized types whose dynamically-sized component is zero-sized. Attempting to use this method on such types results in a compile-time assertion error; e.g.:
use zerocopy::*; # use zerocopy_derive::*; #[derive(FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] struct ZSTy { leading_sized: [u8; 2], trailing_dst: [()], } let mut source = [85, 85]; let _ = ZSTy::mut_from_suffix(&mut source[..]); // ⚠ Compile Error!Examples
use FromBytes; # use *; // These are more bytes than are needed to encode a `PacketTrailer`. let bytes = &mut ; let = mut_from_suffix.unwrap; assert_eq!; assert_eq!; prefix.fill; trailer.frame_check_sequence.fill; assert_eq!;fn ref_from_bytes_with_elems(source: &[u8], count: usize) -> Result<&Self, CastError<&[u8], Self>> where Self: KnownLayout<PointerMetadata = usize> + ImmutableInterprets the given
sourceas a&Selfwith a DST length equal tocount.This method attempts to return a reference to
sourceinterpreted as aSelfwithcounttrailing elements. If the length ofsourceis not equal to the size ofSelfwithcountelements, or ifsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Examples
use FromBytes; # use *; # let bytes = &; let pixels = ref_from_bytes_with_elems.unwrap; assert_eq!;Since an explicit
countis provided, this method supports types with zero-sized trailing slice elements. Methods such asref_from_byteswhich do not take an explicit count do not support such types.use *; # use *; let src = &; let zsty = ref_from_bytes_with_elems.unwrap; assert_eq!;fn ref_from_prefix_with_elems(source: &[u8], count: usize) -> Result<(&Self, &[u8]), CastError<&[u8], Self>> where Self: KnownLayout<PointerMetadata = usize> + ImmutableInterprets the prefix of the given
sourceas a DST&Selfwith length equal tocount.This method attempts to return a reference to the prefix of
sourceinterpreted as aSelfwithcounttrailing elements, and a reference to the remaining bytes. If there are insufficient bytes, or ifsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Examples
use FromBytes; # use *; # // These are more bytes than are needed to encode two `Pixel`s. let bytes = &; let = ref_from_prefix_with_elems.unwrap; assert_eq!; assert_eq!;Since an explicit
countis provided, this method supports types with zero-sized trailing slice elements. Methods such asref_from_prefixwhich do not take an explicit count do not support such types.use *; # use *; let src = &; let = ref_from_prefix_with_elems.unwrap; assert_eq!;fn ref_from_suffix_with_elems(source: &[u8], count: usize) -> Result<(&[u8], &Self), CastError<&[u8], Self>> where Self: KnownLayout<PointerMetadata = usize> + ImmutableInterprets the suffix of the given
sourceas a DST&Selfwith length equal tocount.This method attempts to return a reference to the suffix of
sourceinterpreted as aSelfwithcounttrailing elements, and a reference to the preceding bytes. If there are insufficient bytes, or if that suffix ofsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Examples
use FromBytes; # use *; # // These are more bytes than are needed to encode two `Pixel`s. let bytes = &; let = ref_from_suffix_with_elems.unwrap; assert_eq!; assert_eq!;Since an explicit
countis provided, this method supports types with zero-sized trailing slice elements. Methods such asref_from_suffixwhich do not take an explicit count do not support such types.use *; # use *; let src = &; let = ref_from_suffix_with_elems.unwrap; assert_eq!;fn mut_from_bytes_with_elems(source: &mut [u8], count: usize) -> Result<&mut Self, CastError<&mut [u8], Self>> where Self: IntoBytes + KnownLayout<PointerMetadata = usize> + ImmutableInterprets the given
sourceas a&mut Selfwith a DST length equal tocount.This method attempts to return a reference to
sourceinterpreted as aSelfwithcounttrailing elements. If the length ofsourceis not equal to the size ofSelfwithcountelements, or ifsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Examples
use FromBytes; # use *; # let bytes = &mut ; let pixels = mut_from_bytes_with_elems.unwrap; assert_eq!; pixels = Pixel ; assert_eq!;Since an explicit
countis provided, this method supports types with zero-sized trailing slice elements. Methods such asmut_fromwhich do not take an explicit count do not support such types.use *; # use *; let src = &mut ; let zsty = mut_from_bytes_with_elems.unwrap; assert_eq!;fn mut_from_prefix_with_elems(source: &mut [u8], count: usize) -> Result<(&mut Self, &mut [u8]), CastError<&mut [u8], Self>> where Self: IntoBytes + KnownLayout<PointerMetadata = usize>Interprets the prefix of the given
sourceas a&mut Selfwith DST length equal tocount.This method attempts to return a reference to the prefix of
sourceinterpreted as aSelfwithcounttrailing elements, and a reference to the preceding bytes. If there are insufficient bytes, or ifsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Examples
use FromBytes; # use *; # // These are more bytes than are needed to encode two `Pixel`s. let bytes = &mut ; let = mut_from_prefix_with_elems.unwrap; assert_eq!; assert_eq!; pixels = Pixel ; suffix.fill; assert_eq!;Since an explicit
countis provided, this method supports types with zero-sized trailing slice elements. Methods such asmut_from_prefixwhich do not take an explicit count do not support such types.use *; # use *; let src = &mut ; let = mut_from_prefix_with_elems.unwrap; assert_eq!;fn mut_from_suffix_with_elems(source: &mut [u8], count: usize) -> Result<(&mut [u8], &mut Self), CastError<&mut [u8], Self>> where Self: IntoBytes + KnownLayout<PointerMetadata = usize>Interprets the suffix of the given
sourceas a&mut Selfwith DST length equal tocount.This method attempts to return a reference to the suffix of
sourceinterpreted as aSelfwithcounttrailing elements, and a reference to the remaining bytes. If there are insufficient bytes, or if that suffix ofsourceis not appropriately aligned, this returnsErr. IfSelf: Unaligned, you can infallibly discard the alignment error.Examples
use FromBytes; # use *; # // These are more bytes than are needed to encode two `Pixel`s. let bytes = &mut ; let = mut_from_suffix_with_elems.unwrap; assert_eq!; assert_eq!; prefix.fill; pixels = Pixel ; assert_eq!;Since an explicit
countis provided, this method supports types with zero-sized trailing slice elements. Methods such asmut_from_suffixwhich do not take an explicit count do not support such types.use *; # use *; let src = &mut ; let = mut_from_suffix_with_elems.unwrap; assert_eq!;fn read_from_bytes(source: &[u8]) -> Result<Self, SizeError<&[u8], Self>> where Self: SizedReads a copy of
Selffrom the givensource.If
source.len() != size_of::<Self>(),read_from_bytesreturnsErr.Examples
use FromBytes; # use *; // These bytes encode a `PacketHeader`. let bytes = &; let header = read_from_bytes.unwrap; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn read_from_prefix(source: &[u8]) -> Result<(Self, &[u8]), SizeError<&[u8], Self>> where Self: SizedReads a copy of
Selffrom the prefix of the givensource.This attempts to read a
Selffrom the firstsize_of::<Self>()bytes ofsource, returning thatSelfand any remaining bytes. Ifsource.len() < size_of::<Self>(), it returnsErr.Examples
use FromBytes; # use *; // These are more bytes than are needed to encode a `PacketHeader`. let bytes = &; let = read_from_prefix.unwrap; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn read_from_suffix(source: &[u8]) -> Result<(&[u8], Self), SizeError<&[u8], Self>> where Self: SizedReads a copy of
Selffrom the suffix of the givensource.This attempts to read a
Selffrom the lastsize_of::<Self>()bytes ofsource, returning thatSelfand any preceding bytes. Ifsource.len() < size_of::<Self>(), it returnsErr.Examples
use FromBytes; # use *; // These are more bytes than are needed to encode a `PacketTrailer`. let bytes = &; let = read_from_suffix.unwrap; assert_eq!; assert_eq!;
Implementors
impl FromBytes for Option<NonZeroU16>impl FromBytes for Option<NonZeroI64>impl FromBytes for AtomicU8impl FromBytes for AtomicI32impl<T: ?Sized> FromBytes for PhantomData<T>impl<O> FromBytes for F64<O>impl<T: ?Sized + FromBytes> FromBytes for UnsafeCell<T>impl<O> FromBytes for I128<O>impl FromBytes for __m128iimpl FromBytes for i16impl FromBytes for __m512impl FromBytes for u128impl FromBytes for f64impl FromBytes for Option<NonZeroU32>impl FromBytes for Option<NonZeroI128>impl FromBytes for AtomicU16impl FromBytes for AtomicI64impl<T> FromBytes for CoreMaybeUninit<T>impl<T: FromBytes> FromBytes for [T]impl FromBytes for u8impl FromBytes for __m256dimpl FromBytes for i32impl<O> FromBytes for U32<O>impl FromBytes for __m512iimpl<O> FromBytes for U128<O>impl FromBytes for usizeimpl FromBytes for Option<NonZeroI8>impl FromBytes for Option<NonZeroU64>impl<O> FromBytes for F32<O>impl<O> FromBytes for I64<O>impl FromBytes for Option<NonZeroIsize>impl FromBytes for AtomicU32impl FromBytes for AtomicIsizeimpl<T: ?Sized + FromBytes> FromBytes for Cell<T>impl FromBytes for __m128dimpl FromBytes for u16impl FromBytes for __m512bhimpl FromBytes for i64impl FromBytes for f32impl<O> FromBytes for U16<O>impl FromBytes for Option<NonZeroI16>impl FromBytes for Option<NonZeroU128>impl FromBytes for AtomicI8impl<O> FromBytes for I16<O>impl FromBytes for AtomicU64impl<T> FromBytes for Unalign<T>impl<O> FromBytes for I32<O>impl<T: FromBytes> FromBytes for Wrapping<T>impl<T: FromBytes, N: usize> FromBytes for [T; N]impl FromBytes for ()impl FromBytes for __m256impl FromBytes for u32impl FromBytes for __m512dimpl FromBytes for i128impl<O> FromBytes for Isize<O>impl FromBytes for Option<NonZeroU8>impl FromBytes for Option<NonZeroI32>impl<O> FromBytes for Usize<O>impl FromBytes for Option<NonZeroUsize>impl FromBytes for AtomicI16impl FromBytes for AtomicUsizeimpl<O> FromBytes for U64<O>impl<T: ?Sized + FromBytes> FromBytes for ManuallyDrop<T>impl FromBytes for __m128impl FromBytes for i8impl FromBytes for __m256iimpl FromBytes for u64impl FromBytes for isize