Module byteorder

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, F32, 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 this crate's relevant conversion and marker 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. Note that network-endian is a synonym for big-endian.

Example

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

use zerocopy::{*, byteorder::network_endian::U16};
# use zerocopy_derive::*;

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

#[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned)]
#[repr(C, packed)]
struct UdpPacket {
    header: UdpHeader,
    body: [u8],
}

impl UdpPacket {
    fn parse(bytes: &[u8]) -> Option<&UdpPacket> {
        UdpPacket::ref_from_bytes(bytes).ok()
    }
}

Modules

Structs

Enums

Traits

Type Aliases