Trait FromBytes

Source
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§

Source

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.

Source

fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self>
where Self: AsBytes + Sized,

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.

Source

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.

Implementations on Foreign Types§

Source§

impl FromBytes for i8

Source§

impl FromBytes for i16

Source§

impl FromBytes for i32

Source§

impl FromBytes for i64

Source§

impl FromBytes for isize

Source§

impl FromBytes for u8

Source§

impl FromBytes for u16

Source§

impl FromBytes for u32

Source§

impl FromBytes for u64

Source§

impl FromBytes for usize

Source§

impl<T: FromBytes> FromBytes for [T]

Source§

impl<T: FromBytes, const N: usize> FromBytes for [T; N]

Implementors§