pub unsafe trait FromBytes {
// Provided methods
fn from_bytes(bytes: &[u8]) -> Option<&Self>
where Self: Sized { ... }
fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self>
where Self: AsBytes + Sized { ... }
fn from_bytes_copy(bytes: &[u8]) -> Option<Self>
where Self: Sized { ... }
}
Expand description
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.
§Examples
use kernel::transmute::FromBytes;
let raw = [1, 2, 3, 4];
let result = u32::from_bytes(&raw)?;
#[cfg(target_endian = "little")]
assert_eq!(*result, 0x4030201);
#[cfg(target_endian = "big")]
assert_eq!(*result, 0x1020304);
§Safety
All bit-patterns must be valid for this type. This type must not have interior mutability.
Provided Methods§
Sourcefn from_bytes(bytes: &[u8]) -> Option<&Self>where
Self: Sized,
fn from_bytes(bytes: &[u8]) -> Option<&Self>where
Self: Sized,
Converts a slice of bytes to a reference to Self
.
Succeeds if the reference is properly aligned, and the size of bytes
is equal to that of
T
and different from zero.
Otherwise, returns None
.
Sourcefn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self>
fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self>
Converts a mutable slice of bytes to a reference to Self
.
Succeeds if the reference is properly aligned, and the size of bytes
is equal to that of
T
and different from zero.
Otherwise, returns None
.
Sourcefn from_bytes_copy(bytes: &[u8]) -> Option<Self>where
Self: Sized,
fn from_bytes_copy(bytes: &[u8]) -> Option<Self>where
Self: Sized,
Creates an owned instance of Self
by copying bytes
.
Unlike FromBytes::from_bytes
, which requires aligned input, this method can be used on
non-aligned data at the cost of a copy.