zerocopy

Struct Unalign

Source
#[repr(C, packed(1))]
pub struct Unalign<T>(/* private fields */);
Expand description

A type with no alignment requirement.

An Unalign wraps a T, removing any alignment requirement. Unalign<T> has the same size and bit validity as T, but not necessarily the same alignment or ABI. This is useful if a type with an alignment requirement needs to be read from a chunk of memory which provides no alignment guarantees.

Since Unalign has no alignment requirement, the inner T may not be properly aligned in memory. There are five ways to access the inner T:

§Example

In this example, we need EthernetFrame to have no alignment requirement - and thus implement Unaligned. EtherType is #[repr(u16)] and so cannot implement Unaligned. We use Unalign to relax EtherType’s alignment requirement so that EthernetFrame has no alignment requirement and can implement Unaligned.

use zerocopy::*;

#[derive(TryFromBytes, KnownLayout, Immutable)]
#[repr(u16)]
enum EtherType {
    Ipv4 = 0x0800u16.to_be(),
    Arp = 0x0806u16.to_be(),
    Ipv6 = 0x86DDu16.to_be(),
    ...
}

#[derive(TryFromBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
struct EthernetFrame {
    src: Mac,
    dst: Mac,
    ethertype: Unalign<EtherType>,
    payload: [u8],
}

let bytes = &[
    ...
    0x86, 0xDD,            // EtherType
    0xDE, 0xAD, 0xBE, 0xEF // Payload
][..];

// PANICS: Guaranteed not to panic because `bytes` is of the right
// length, has the right contents, and `EthernetFrame` has no
// alignment requirement.
let packet = EthernetFrame::try_ref_from_bytes(&bytes).unwrap();

assert_eq!(packet.ethertype.get(), EtherType::Ipv6);
assert_eq!(packet.payload, [0xDE, 0xAD, 0xBE, 0xEF]);

§Safety

Unalign<T> is guaranteed to have the same size and bit validity as T, and to have UnsafeCells covering the same byte ranges as T. Unalign<T> is guaranteed to have alignment 1.

Implementations§

Source§

impl<T> Unalign<T>

Source

pub const fn new(val: T) -> Unalign<T>

Constructs a new Unalign.

Source

pub const fn into_inner(self) -> T

Consumes self, returning the inner T.

Source

pub fn try_deref(&self) -> Result<&T, AlignmentError<&Self, T>>

Attempts to return a reference to the wrapped T, failing if self is not properly aligned.

If self does not satisfy align_of::<T>(), then try_deref returns Err.

If T: Unaligned, then Unalign<T> implements Deref, and callers may prefer Deref::deref, which is infallible.

Source

pub fn try_deref_mut(&mut self) -> Result<&mut T, AlignmentError<&mut Self, T>>

Attempts to return a mutable reference to the wrapped T, failing if self is not properly aligned.

If self does not satisfy align_of::<T>(), then try_deref returns Err.

If T: Unaligned, then Unalign<T> implements DerefMut, and callers may prefer DerefMut::deref_mut, which is infallible.

Source

pub const unsafe fn deref_unchecked(&self) -> &T

Returns a reference to the wrapped T without checking alignment.

If T: Unaligned, then Unalign<T> implements Deref, and callers may prefer Deref::deref, which is safe.

§Safety

The caller must guarantee that self satisfies align_of::<T>().

Source

pub unsafe fn deref_mut_unchecked(&mut self) -> &mut T

Returns a mutable reference to the wrapped T without checking alignment.

If T: Unaligned, then Unalign<T> implements DerefMut, and callers may prefer DerefMut::deref_mut, which is safe.

§Safety

The caller must guarantee that self satisfies align_of::<T>().

Source

pub const fn get_ptr(&self) -> *const T

Gets an unaligned raw pointer to the inner T.

§Safety

The returned raw pointer is not necessarily aligned to align_of::<T>(). Most functions which operate on raw pointers require those pointers to be aligned, so calling those functions with the result of get_ptr will result in undefined behavior if alignment is not guaranteed using some out-of-band mechanism. In general, the only functions which are safe to call with this pointer are those which are explicitly documented as being sound to use with an unaligned pointer, such as read_unaligned.

Even if the caller is permitted to mutate self (e.g. they have ownership or a mutable borrow), it is not guaranteed to be sound to write through the returned pointer. If writing is required, prefer get_mut_ptr instead.

Source

pub fn get_mut_ptr(&mut self) -> *mut T

Gets an unaligned mutable raw pointer to the inner T.

§Safety

The returned raw pointer is not necessarily aligned to align_of::<T>(). Most functions which operate on raw pointers require those pointers to be aligned, so calling those functions with the result of get_ptr will result in undefined behavior if alignment is not guaranteed using some out-of-band mechanism. In general, the only functions which are safe to call with this pointer are those which are explicitly documented as being sound to use with an unaligned pointer, such as read_unaligned.

Source

pub fn set(&mut self, t: T)

Sets the inner T, dropping the previous value.

Source

pub fn update<O, F: FnOnce(&mut T) -> O>(&mut self, f: F) -> O

Updates the inner T by calling a function on it.

If T: Unaligned, then Unalign<T> implements DerefMut, and that impl should be preferred over this method when performing updates, as it will usually be faster and more ergonomic.

For large types, this method may be expensive, as it requires copying 2 * size_of::<T>() bytes. [1]

[1] Since the inner T may not be aligned, it would not be sound to invoke f on it directly. Instead, update moves it into a properly-aligned location in the local stack frame, calls f on it, and then moves it back to its original location in self.

Source§

impl<T: Copy> Unalign<T>

Source

pub fn get(&self) -> T

Gets a copy of the inner T.

Trait Implementations§

Source§

impl<T: Copy> Clone for Unalign<T>

Source§

fn clone(&self) -> Unalign<T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Unaligned + Debug> Debug for Unalign<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default> Default for Unalign<T>

Source§

fn default() -> Unalign<T>

Returns the “default value” for a type. Read more
Source§

impl<T: Unaligned> Deref for Unalign<T>

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &T

Dereferences the value.
Source§

impl<T: Unaligned> DerefMut for Unalign<T>

Source§

fn deref_mut(&mut self) -> &mut T

Mutably dereferences the value.
Source§

impl<T: Unaligned + Display> Display for Unalign<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: FromBytes> FromBytes for Unalign<T>

Source§

fn ref_from_bytes(source: &[u8]) -> Result<&Self, CastError<&[u8], Self>>
where Self: KnownLayout + Immutable,

Interprets the given source as a &Self. Read more
Source§

fn ref_from_prefix( source: &[u8], ) -> Result<(&Self, &[u8]), CastError<&[u8], Self>>
where Self: KnownLayout + Immutable,

Interprets the prefix of the given source as a &Self without copying. Read more
Source§

fn ref_from_suffix( source: &[u8], ) -> Result<(&[u8], &Self), CastError<&[u8], Self>>
where Self: Immutable + KnownLayout,

Interprets the suffix of the given bytes as a &Self. Read more
Source§

fn mut_from_bytes( source: &mut [u8], ) -> Result<&mut Self, CastError<&mut [u8], Self>>
where Self: IntoBytes + KnownLayout,

Interprets the given source as a &mut Self. Read more
Source§

fn mut_from_prefix( source: &mut [u8], ) -> Result<(&mut Self, &mut [u8]), CastError<&mut [u8], Self>>
where Self: IntoBytes + KnownLayout,

Interprets the prefix of the given source as a &mut Self without copying. Read more
Source§

fn mut_from_suffix( source: &mut [u8], ) -> Result<(&mut [u8], &mut Self), CastError<&mut [u8], Self>>
where Self: IntoBytes + KnownLayout,

Interprets the suffix of the given source as a &mut Self without copying. Read more
Source§

fn read_from_bytes(source: &[u8]) -> Result<Self, SizeError<&[u8], Self>>
where Self: Sized,

Reads a copy of Self from the given source. Read more
Source§

fn read_from_prefix( source: &[u8], ) -> Result<(Self, &[u8]), SizeError<&[u8], Self>>
where Self: Sized,

Reads a copy of Self from the prefix of the given source. Read more
Source§

fn read_from_suffix( source: &[u8], ) -> Result<(&[u8], Self), SizeError<&[u8], Self>>
where Self: Sized,

Reads a copy of Self from the suffix of the given source. Read more
Source§

impl<T: FromZeros> FromZeros for Unalign<T>

Source§

fn zero(&mut self)

Overwrites self with zeros. Read more
Source§

fn new_zeroed() -> Self
where Self: Sized,

Creates an instance of Self from zeroed bytes. Read more
Source§

impl<T: Unaligned + Hash> Hash for Unalign<T>

Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T: IntoBytes> IntoBytes for Unalign<T>

Source§

fn as_bytes(&self) -> &[u8]
where Self: Immutable,

Gets the bytes of this value. Read more
Source§

fn as_mut_bytes(&mut self) -> &mut [u8]
where Self: FromBytes,

Gets the bytes of this value mutably. Read more
Source§

fn write_to(&self, dst: &mut [u8]) -> Result<(), SizeError<&Self, &mut [u8]>>
where Self: Immutable,

Writes a copy of self to dst. Read more
Source§

fn write_to_prefix( &self, dst: &mut [u8], ) -> Result<(), SizeError<&Self, &mut [u8]>>
where Self: Immutable,

Writes a copy of self to the prefix of dst. Read more
Source§

fn write_to_suffix( &self, dst: &mut [u8], ) -> Result<(), SizeError<&Self, &mut [u8]>>
where Self: Immutable,

Writes a copy of self to the suffix of dst. Read more
Source§

impl<T> KnownLayout for Unalign<T>

Source§

type PointerMetadata = ()

The type of metadata stored in a pointer to Self. Read more
Source§

impl<T: Unaligned + Ord> Ord for Unalign<T>

Source§

fn cmp(&self, other: &Unalign<T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T: Unaligned + PartialEq> PartialEq for Unalign<T>

Source§

fn eq(&self, other: &Unalign<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: Unaligned + PartialOrd> PartialOrd for Unalign<T>

Source§

fn partial_cmp(&self, other: &Unalign<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: TryFromBytes> TryFromBytes for Unalign<T>

Source§

fn try_ref_from_bytes(source: &[u8]) -> Result<&Self, TryCastError<&[u8], Self>>
where Self: KnownLayout + Immutable,

Attempts to interpret the given source as a &Self. Read more
Source§

fn try_ref_from_prefix( source: &[u8], ) -> Result<(&Self, &[u8]), TryCastError<&[u8], Self>>
where Self: KnownLayout + Immutable,

Attempts to interpret the prefix of the given source as a &Self. Read more
Source§

fn try_ref_from_suffix( source: &[u8], ) -> Result<(&[u8], &Self), TryCastError<&[u8], Self>>
where Self: KnownLayout + Immutable,

Attempts to interpret the suffix of the given source as a &Self. Read more
Source§

fn try_mut_from_bytes( bytes: &mut [u8], ) -> Result<&mut Self, TryCastError<&mut [u8], Self>>
where Self: KnownLayout,

Attempts to interpret the given source as a &mut Self without copying. Read more
Source§

fn try_mut_from_prefix( source: &mut [u8], ) -> Result<(&mut Self, &mut [u8]), TryCastError<&mut [u8], Self>>
where Self: KnownLayout,

Attempts to interpret the prefix of the given source as a &mut Self. Read more
Source§

fn try_mut_from_suffix( source: &mut [u8], ) -> Result<(&mut [u8], &mut Self), TryCastError<&mut [u8], Self>>
where Self: KnownLayout,

Attempts to interpret the suffix of the given source as a &mut Self. Read more
Source§

fn try_read_from_bytes(source: &[u8]) -> Result<Self, TryReadError<&[u8], Self>>
where Self: Sized,

Attempts to read the given source as a Self. Read more
Source§

fn try_read_from_prefix( source: &[u8], ) -> Result<(Self, &[u8]), TryReadError<&[u8], Self>>
where Self: Sized,

Attempts to read a Self from the prefix of the given source. Read more
Source§

fn try_read_from_suffix( source: &[u8], ) -> Result<(&[u8], Self), TryReadError<&[u8], Self>>
where Self: Sized,

Attempts to read a Self from the suffix of the given source. Read more
Source§

impl<T: Copy> Copy for Unalign<T>

Source§

impl<T: Unaligned + Eq> Eq for Unalign<T>

Source§

impl<T: Immutable> Immutable for Unalign<T>

Source§

impl<T> Unaligned for Unalign<T>

Auto Trait Implementations§

§

impl<T> Freeze for Unalign<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Unalign<T>
where T: RefUnwindSafe,

§

impl<T> Send for Unalign<T>
where T: Send,

§

impl<T> Sync for Unalign<T>
where T: Sync,

§

impl<T> Unpin for Unalign<T>
where T: Unpin,

§

impl<T> UnwindSafe for Unalign<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.