Skip to main content

Split

Struct Split 

Source
pub struct Split<T> { /* private fields */ }
Expand description

A T that has been split into two possibly-overlapping parts.

For some dynamically sized types, the padding that appears after the trailing slice field is a dynamic function of the trailing slice length. If T is split at a length that requires trailing padding, the trailing padding of the left part of the split T will overlap the right part. If T is a mutable reference or permits interior mutation, you must ensure that the left and right parts do not overlap. Use Self::via_into_bytes or Self::via_no_dynamic_padding to establish this without a runtime check, or Self::via_runtime_check to check a particular split. Shared references to an Immutable type may overlap; use Self::via_immutable in that case.

Implementations§

Source§

impl<'a, T> Split<&'a T>
where T: SplitAt + ?Sized,

Source

pub fn via_immutable(self) -> (&'a T, &'a [<T as SplitAt>::Elem])
where T: Immutable,

Produces the split parts of self, using Immutable to ensure that it is sound to have concurrent references to both parts.

§Examples
use zerocopy::{SplitAt, FromBytes};

#[derive(SplitAt, FromBytes, KnownLayout, Immutable)]
#[repr(C)]
struct Packet {
    length: u8,
    body: [u8],
}

// These bytes encode a `Packet`.
let bytes = &[4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];

let packet = Packet::ref_from_bytes(bytes).unwrap();

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);

// Attempt to split `packet` at `length`.
let split = packet.split_at(packet.length as usize).unwrap();

// Use the `Immutable` bound on `Packet` to prove that it's okay to
// return concurrent references to `packet` and `rest`.
let (packet, rest) = split.via_immutable();

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4]);
assert_eq!(rest, [5, 6, 7, 8, 9]);
Source

pub fn via_into_bytes(self) -> (&'a T, &'a [<T as SplitAt>::Elem])
where T: IntoBytes,

Produces the split parts of self, using IntoBytes to ensure that it is sound to have concurrent references to both parts.

§Examples
use zerocopy::{SplitAt, FromBytes};

#[derive(SplitAt, FromBytes, KnownLayout, Immutable, IntoBytes)]
#[repr(C)]
struct Packet<B: ?Sized> {
    length: u8,
    body: B,
}

// These bytes encode a `Packet`.
let bytes = &[4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];

let packet = Packet::<[u8]>::ref_from_bytes(bytes).unwrap();

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);

// Attempt to split `packet` at `length`.
let split = packet.split_at(packet.length as usize).unwrap();

// Use the `IntoBytes` bound on `Packet` to prove that it's okay to
// return concurrent references to `packet` and `rest`.
let (packet, rest) = split.via_into_bytes();

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4]);
assert_eq!(rest, [5, 6, 7, 8, 9]);
§ Code Generation

See Split::via_immutable.

Source

pub fn via_no_dynamic_padding(self) -> (&'a T, &'a [<T as SplitAt>::Elem])

Produces the split parts of self using a compile-time assertion to ensure that it is unconditionally sound to have concurrent references to both parts.

When possible, you should prefer using Self::via_into_bytes, which ensures this safety property through regular trait bounds.

§Examples

In the below example, a single byte of padding exists (on most platforms) between Packet<[u16]>’s length and body fields, precluding the use of Self::via_into_bytes.

use zerocopy::SplitAt;

#[derive(SplitAt, KnownLayout)]
#[repr(C)]
struct Packet<B: ?Sized> {
    length: u8,
    body: B,
}

let packet: &Packet<[u16]> = &Packet { length: 4, body: [1u16, 2, 3, 4, 5, 6, 7, 8, 9] };

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);

if let Some(split) = packet.split_at(packet.length as usize) {
    // Every body length requires no trailing padding.
    let (packet, rest) = split.via_no_dynamic_padding();
    assert_eq!(packet.length, 4);
    assert_eq!(packet.body, [1, 2, 3, 4]);
    assert_eq!(rest, [5, 6, 7, 8, 9]);
} else {
    unreachable!("The packet's length field is within its body");
}
§Compile-Time Assertions

This method rejects at compile-time any type that admits dynamic trailing padding. In the below example, some split_at indices would produce left parts whose trailing padding overlaps with the right part:

ⓘ
use zerocopy::SplitAt;

#[derive(SplitAt, KnownLayout)]
#[repr(C, align(2))]
struct Packet<B: ?Sized> {
    length: u16,
    body: B,
}

let packet: &Packet<[u8]> = &Packet { length: 4, body: [1u8, 2, 3, 4, 5, 6, 7, 8, 9] };

if let Some(split) = packet.split_at(packet.length as usize) {
    let _ = split.via_no_dynamic_padding(); // ⚠ Compile Error!
} else {
    unreachable!("The packet's length field is within its body");
}

If you need to split such types, use Self::via_runtime_check.

§ Code Generation

See Split::via_immutable.

Source

pub fn via_runtime_check( self, ) -> Result<(&'a T, &'a [<T as SplitAt>::Elem]), Split<&'a T>>

Produces the split parts of self, using a dynamic check to ensure that it is sound to have concurrent references to both parts. You should prefer using Self::via_immutable, Self::via_into_bytes, or Self::via_no_dynamic_padding, which perform no runtime check.

Note that this check is overly conservative if T is Immutable; for some types, this check will reject some splits which Self::via_immutable will accept.

§Examples
use zerocopy::SplitAt;

#[derive(SplitAt, KnownLayout)]
#[repr(C, align(2))]
struct Packet<B: ?Sized> {
    length: u16,
    body: B,
}

let packet: &Packet<[u8]> = &Packet { length: 4, body: [1u8, 2, 3, 4, 5, 6, 7, 8, 9] };

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);

// The two-byte prefix and four-byte body need no trailing padding.
if let Some(split) = packet.split_at(packet.length as usize) {
    if let Ok((packet, rest)) = split.via_runtime_check() {
        assert_eq!(packet.length, 4);
        assert_eq!(packet.body, [1, 2, 3, 4]);
        assert_eq!(rest, [5, 6, 7, 8, 9]);
    } else {
        unreachable!("A four-byte body requires no trailing padding");
    }
} else {
    unreachable!("The packet's length field is within its body");
}

// A three-byte body needs a padding byte that would overlap `rest`.
if let Some(split) = packet.split_at((packet.length - 1) as usize) {
    assert!(split.via_runtime_check().is_err());
} else {
    unreachable!("One less than the packet's length is within its body");
}
Source

pub unsafe fn via_unchecked(self) -> (&'a T, &'a [<T as SplitAt>::Elem])

Unsafely produces the split parts of self.

§Safety

If T permits interior mutation, the trailing padding bytes of the left portion must not overlap the right portion. For some dynamically sized types, the padding that appears after the trailing slice field is a dynamic function of the trailing slice length. Thus, for some types, this condition is dependent on the length of the left portion.

Source§

impl<'a, T> Split<&'a mut T>
where T: SplitAt + ?Sized,

Source

pub fn via_into_bytes(self) -> (&'a mut T, &'a mut [<T as SplitAt>::Elem])
where T: IntoBytes,

Produces the split parts of self, using IntoBytes to ensure that it is sound to have concurrent references to both parts.

§Examples
use zerocopy::{SplitAt, FromBytes};

#[derive(SplitAt, FromBytes, KnownLayout, IntoBytes)]
#[repr(C)]
struct Packet<B: ?Sized> {
    length: u8,
    body: B,
}

// These bytes encode a `Packet`.
let mut bytes = &mut [4, 1, 2, 3, 4, 5, 6, 7, 8, 9][..];

let packet = Packet::<[u8]>::mut_from_bytes(bytes).unwrap();

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);

{
    // Attempt to split `packet` at `length`.
    let split = packet.split_at_mut(packet.length as usize).unwrap();

    // Use the `IntoBytes` bound on `Packet` to prove that it's okay to
    // return concurrent references to `packet` and `rest`.
    let (packet, rest) = split.via_into_bytes();

    assert_eq!(packet.length, 4);
    assert_eq!(packet.body, [1, 2, 3, 4]);
    assert_eq!(rest, [5, 6, 7, 8, 9]);

    rest.fill(0);
}

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 0, 0, 0, 0, 0]);
§Code Generation

See Split::via_immutable.

Source

pub fn via_no_dynamic_padding( self, ) -> (&'a mut T, &'a mut [<T as SplitAt>::Elem])

Produces the split parts of self using a compile-time assertion to ensure that it is unconditionally sound to have concurrent references to both parts.

When possible, you should prefer using Self::via_into_bytes, which ensures this safety property through regular trait bounds.

§Examples

In the below example, a single byte of padding exists (on most platforms) between Packet<[u16]>’s length and body fields, precluding the use of Self::via_into_bytes.

use zerocopy::SplitAt;

#[derive(SplitAt, KnownLayout)]
#[repr(C)]
struct Packet<B: ?Sized> {
    length: u8,
    body: B,
}

let packet: &mut Packet<[u16]> = &mut Packet { length: 4, body: [1u16, 2, 3, 4, 5, 6, 7, 8, 9] };

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);

// Every body length requires no trailing padding.
if let Some(split) = packet.split_at_mut(packet.length as usize) {
    let (packet, rest) = split.via_no_dynamic_padding();
    assert_eq!(packet.length, 4);
    assert_eq!(packet.body, [1, 2, 3, 4]);
    assert_eq!(rest, [5, 6, 7, 8, 9]);
    rest.fill(0);
} else {
    unreachable!("The packet's length field is within its body");
}

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 0, 0, 0, 0, 0]);
§Compile-Time Assertions

This method rejects at compile-time any type that admits dynamic trailing padding. In the below example, some split_at indices would produce left parts whose trailing padding overlaps with the right part:

ⓘ
use zerocopy::SplitAt;

#[derive(SplitAt, KnownLayout)]
#[repr(C, align(2))]
struct Packet<B: ?Sized> {
    length: u16,
    body: B,
}

let packet: &mut Packet<[u8]> = &mut Packet { length: 4, body: [1u8, 2, 3, 4, 5, 6, 7, 8, 9] };

if let Some(split) = packet.split_at_mut(packet.length as usize) {
    let _ = split.via_no_dynamic_padding(); // ⚠ Compile Error!
} else {
    unreachable!("The packet's length field is within its body");
}

If you need to split such types, use Self::via_runtime_check.

§Code Generation

See Split::via_immutable.

Source

pub fn via_runtime_check( self, ) -> Result<(&'a mut T, &'a mut [<T as SplitAt>::Elem]), Split<&'a mut T>>

Produces the split parts of self, using a dynamic check to ensure that it is sound to have concurrent references to both parts. You should prefer using Self::via_into_bytes or Self::via_no_dynamic_padding, which perform no runtime check.

§Examples
use zerocopy::SplitAt;

#[derive(SplitAt, KnownLayout)]
#[repr(C, align(2))]
struct Packet<B: ?Sized> {
    length: u16,
    body: B,
}

let packet: &mut Packet<[u8]> = &mut Packet { length: 4, body: [1u8, 2, 3, 4, 5, 6, 7, 8, 9] };

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 5, 6, 7, 8, 9]);

// The two-byte prefix and four-byte body need no trailing padding.
if let Some(split) = packet.split_at_mut(packet.length as usize) {
    if let Ok((packet, rest)) = split.via_runtime_check() {
        assert_eq!(packet.length, 4);
        assert_eq!(packet.body, [1, 2, 3, 4]);
        assert_eq!(rest, [5, 6, 7, 8, 9]);
        rest.fill(0);
    } else {
        unreachable!("A four-byte body requires no trailing padding");
    }
} else {
    unreachable!("The packet's length field is within its body");
}

assert_eq!(packet.length, 4);
assert_eq!(packet.body, [1, 2, 3, 4, 0, 0, 0, 0, 0]);
§Code Generation

See Split::via_runtime_check.

Source

pub unsafe fn via_unchecked(self) -> (&'a mut T, &'a mut [<T as SplitAt>::Elem])

Unsafely produces the split parts of self.

§Safety

The trailing padding bytes of the left portion must not overlap the right portion. For some dynamically sized types, the padding that appears after the trailing slice field is a dynamic function of the trailing slice length. Thus, for some types, this condition is dependent on the length of the left portion.

§Code Generation

See Split::via_unchecked.

Trait Implementations§

Source§

impl<T> Debug for Split<T>
where T: Debug,

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

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

§

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

§

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

§

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

§

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

§

impl<T> UnsafeUnpin for Split<T>
where T: UnsafeUnpin,

§

impl<T> UnwindSafe for Split<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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.