Module zerocopy::byteorder

source ·
Expand description

Byte order-aware numeric primitives.

This module contains equivalents of the native multi-byte integer types with no alignment requirement and supporting byte order conversions.

For each native multi-byte integer type - u16, i16, u32, etc - and floating point type - f32 and f64 - an equivalent type is defined by this module - U16, I16, U32, F64, etc. Unlike their native counterparts, these types have alignment 1, and take a type parameter specifying the byte order in which the bytes are stored in memory. Each type implements the FromBytes, AsBytes, and Unaligned traits.

These two properties, taken together, make these types useful for defining data structures whose memory layout matches a wire format such as that of a network protocol or a file format. Such formats often have multi-byte values at offsets that do not respect the alignment requirements of the equivalent native types, and stored in a byte order not necessarily the same as that of the target platform.

Type aliases are provided for common byte orders in the big_endian, little_endian, network_endian, and native_endian submodules.

§Example

One use of these types is for representing network packet formats, such as UDP:

use zerocopy::{AsBytes, ByteSlice, FromBytes, FromZeroes, Ref, Unaligned};
use zerocopy::byteorder::network_endian::U16;

#[derive(FromZeroes, FromBytes, AsBytes, Unaligned)]
#[repr(C)]
struct UdpHeader {
    src_port: U16,
    dst_port: U16,
    length: U16,
    checksum: U16,
}

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

impl<B: ByteSlice> UdpPacket<B> {
    fn parse(bytes: B) -> Option<UdpPacket<B>> {
        let (header, body) = Ref::new_from_prefix(bytes)?;
        Some(UdpPacket { header, body })
    }

    fn src_port(&self) -> u16 {
        self.header.src_port.get()
    }

    // more getters...
}

Modules§

  • Numeric primitives stored in big-endian byte order.
  • Numeric primitives stored in little-endian byte order.
  • Numeric primitives stored in native-endian byte order.
  • Numeric primitives stored in network-endian byte order.

Structs§

  • A 32-bit floating point number stored in a given byte order.
  • A 64-bit floating point number stored in a given byte order.
  • A 16-bit signed integer stored in a given byte order.
  • A 32-bit signed integer stored in a given byte order.
  • A 64-bit signed integer stored in a given byte order.
  • A 128-bit signed integer stored in a given byte order.
  • A 16-bit unsigned integer stored in a given byte order.
  • A 32-bit unsigned integer stored in a given byte order.
  • A 64-bit unsigned integer stored in a given byte order.
  • A 128-bit unsigned integer stored in a given byte order.

Enums§

Traits§

  • ByteOrder describes types that can serialize integers as bytes.

Type Aliases§