Struct zerocopy::Ref

source ·
pub struct Ref<B, T: ?Sized>(/* private fields */);
Expand description

A typed reference derived from a byte slice.

A Ref<B, T> is a reference to a T which is stored in a byte slice, B. Unlike a native reference (&T or &mut T), Ref<B, T> has the same mutability as the byte slice it was constructed from (B).

§Examples

Ref can be used to treat a sequence of bytes as a structured type, and to read and write the fields of that type as if the byte slice reference were simply a reference to that type.

use zerocopy::{IntoBytes, ByteSliceMut, FromBytes, FromZeros, KnownLayout, Immutable, Ref, SplitByteSlice, Unaligned};

#[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C)]
struct UdpHeader {
    src_port: [u8; 2],
    dst_port: [u8; 2],
    length: [u8; 2],
    checksum: [u8; 2],
}

struct UdpPacket<B> {
    header: Ref<B, UdpHeader>,
    body: B,
}

impl<B: SplitByteSlice> UdpPacket<B> {
    pub fn parse(bytes: B) -> Option<UdpPacket<B>> {
        let (header, body) = Ref::new_unaligned_from_prefix(bytes).ok()?;
        Some(UdpPacket { header, body })
    }

    pub fn get_src_port(&self) -> [u8; 2] {
        self.header.src_port
    }
}

impl<B: ByteSliceMut> UdpPacket<B> {
    pub fn with_src_port(&mut self, src_port: [u8; 2]) {
        self.header.src_port = src_port;
    }
}

Implementations§

source§

impl<B, T> Ref<B, T>

source

pub fn new(bytes: B) -> Result<Ref<B, T>, CastError<B, T>>

Constructs a new Ref.

new verifies that bytes.len() == size_of::<T>() and that bytes is aligned to align_of::<T>(), and constructs a new Ref. If either of these checks fail, it returns None.

§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::*;

#[derive(Immutable, KnownLayout)]
#[repr(C)]
struct ZSTy {
    leading_sized: u16,
    trailing_dst: [()],
}

let _ = Ref::<_, ZSTy>::new(&b"UU"[..]); // ⚠ Compile Error!
source§

impl<B, T> Ref<B, T>

source

pub fn new_from_prefix(bytes: B) -> Result<(Ref<B, T>, B), CastError<B, T>>

Constructs a new Ref from the prefix of a byte slice.

new_from_prefix verifies that bytes.len() >= size_of::<T>() and that bytes is aligned to align_of::<T>(). It consumes the first size_of::<T>() bytes from bytes to construct a Ref, and returns the remaining bytes to the caller. If either the length or alignment checks fail, it returns None.

§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::*;

#[derive(Immutable, KnownLayout)]
#[repr(C)]
struct ZSTy {
    leading_sized: u16,
    trailing_dst: [()],
}

let _ = Ref::<_, ZSTy>::new_from_prefix(&b"UU"[..]); // ⚠ Compile Error!
source

pub fn new_from_suffix(bytes: B) -> Result<(B, Ref<B, T>), CastError<B, T>>

Constructs a new Ref from the suffix of a byte slice.

new_from_suffix verifies that bytes.len() >= size_of::<T>() and that the last size_of::<T>() bytes of bytes are aligned to align_of::<T>(). It consumes the last size_of::<T>() bytes from bytes to construct a Ref, and returns the preceding bytes to the caller. If either the length or alignment checks fail, it returns None.

§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::*;

#[derive(Immutable, KnownLayout)]
#[repr(C)]
struct ZSTy {
    leading_sized: u16,
    trailing_dst: [()],
}

let _ = Ref::<_, ZSTy>::new_from_suffix(&b"UU"[..]); // ⚠ Compile Error!
source§

impl<B, T> Ref<B, T>

source

pub fn new_unaligned(bytes: B) -> Result<Ref<B, T>, SizeError<B, T>>

Constructs a new Ref for a type with no alignment requirement.

new_unaligned verifies that bytes.len() == size_of::<T>() and constructs a new Ref. If the check fails, it returns None.

§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::*;

#[derive(Immutable, KnownLayout, Unaligned)]
#[repr(C, packed)]
struct ZSTy {
    leading_sized: u16,
    trailing_dst: [()],
}

let f = Ref::<&[u8], ZSTy>::new_unaligned(&b"UU"[..]); // ⚠ Compile Error!
source§

impl<B, T> Ref<B, T>

source

pub fn new_unaligned_from_prefix( bytes: B ) -> Result<(Ref<B, T>, B), SizeError<B, T>>

Constructs a new Ref from the prefix of a byte slice for a type with no alignment requirement.

new_unaligned_from_prefix verifies that bytes.len() >= size_of::<T>(). It consumes the first size_of::<T>() bytes from bytes to construct a Ref, and returns the remaining bytes to the caller. If the length check fails, it returns None.

§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::*;

#[derive(Immutable, KnownLayout, Unaligned)]
#[repr(C, packed)]
struct ZSTy {
    leading_sized: u16,
    trailing_dst: [()],
}

let _ = Ref::<_, ZSTy>::new_unaligned_from_prefix(&b"UU"[..]); // ⚠ Compile Error!
source

pub fn new_unaligned_from_suffix( bytes: B ) -> Result<(B, Ref<B, T>), SizeError<B, T>>

Constructs a new Ref from the suffix of a byte slice for a type with no alignment requirement.

new_unaligned_from_suffix verifies that bytes.len() >= size_of::<T>(). It consumes the last size_of::<T>() bytes from bytes to construct a Ref, and returns the preceding bytes to the caller. If the length check fails, it returns None.

§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::*;

#[derive(Immutable, KnownLayout, Unaligned)]
#[repr(C, packed)]
struct ZSTy {
    leading_sized: u16,
    trailing_dst: [()],
}

let _ = Ref::<_, ZSTy>::new_unaligned_from_suffix(&b"UU"[..]); // ⚠ Compile Error!
source§

impl<'a, B, T> Ref<B, T>
where B: 'a + IntoByteSlice<'a>, T: FromBytes + KnownLayout + Immutable + ?Sized,

source

pub fn into_ref(self) -> &'a T

Converts this Ref into a reference.

into_ref consumes the Ref, and returns a reference to T.

source§

impl<'a, B, T> Ref<B, T>
where B: 'a + IntoByteSliceMut<'a>, T: FromBytes + IntoBytes + KnownLayout + ?Sized,

source

pub fn into_mut(self) -> &'a mut T

Converts this Ref into a mutable reference.

into_mut consumes the Ref, and returns a mutable reference to T.

source§

impl<B, T> Ref<B, T>
where B: ByteSlice, T: ?Sized,

source

pub fn bytes(&self) -> &[u8]

Gets the underlying bytes.

source§

impl<B, T> Ref<B, T>
where B: ByteSliceMut, T: ?Sized,

source

pub fn bytes_mut(&mut self) -> &mut [u8]

Gets the underlying bytes mutably.

source§

impl<B, T> Ref<B, T>
where B: ByteSlice, T: FromBytes,

source

pub fn read(&self) -> T

Reads a copy of T.

source§

impl<B, T> Ref<B, T>
where B: ByteSliceMut, T: IntoBytes,

source

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

Writes the bytes of t and then forgets t.

Trait Implementations§

source§

impl<B: CloneableByteSlice + Clone, T: ?Sized> Clone for Ref<B, T>

source§

fn clone(&self) -> Ref<B, 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, B> Debug for Ref<B, T>

source§

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

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

impl<B, T> Deref for Ref<B, T>

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &T

Dereferences the value.
source§

impl<B, T> DerefMut for Ref<B, T>

source§

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

Mutably dereferences the value.
source§

impl<T, B> Display for Ref<B, T>

source§

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

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

impl<T, B> Ord for Ref<B, T>

source§

fn cmp(&self, other: &Self) -> 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 + PartialOrd,

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

impl<T, B> PartialEq for Ref<B, T>

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T, B> PartialOrd for Ref<B, T>

source§

fn partial_cmp(&self, other: &Self) -> 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

This method 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

This method 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

This method 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

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<B: CopyableByteSlice + Copy, T: ?Sized> Copy for Ref<B, T>

source§

impl<T, B> Eq for Ref<B, T>

Auto Trait Implementations§

§

impl<B, T> Freeze for Ref<B, T>
where B: Freeze, T: ?Sized,

§

impl<B, T> RefUnwindSafe for Ref<B, T>

§

impl<B, T> Send for Ref<B, T>
where B: Send, T: Send + ?Sized,

§

impl<B, T> Sync for Ref<B, T>
where B: Sync, T: Sync + ?Sized,

§

impl<B, T> Unpin for Ref<B, T>
where B: Unpin, T: Unpin + ?Sized,

§

impl<B, T> UnwindSafe for Ref<B, T>
where B: UnwindSafe, T: UnwindSafe + ?Sized,

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> 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<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for T
where T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

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

§

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>,

§

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.