[][src]Module zerocopy::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 - an equivalent type is defined by this module - U16, I16, U32, 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 very 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.

Example

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

This code runs with edition 2018
use ::byteorder::NetworkEndian;

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

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

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

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

    // more getters...
}

Structs

I16

A 16-bit signed integer stored in O byte order.

I32

A 32-bit signed integer stored in O byte order.

I64

A 64-bit signed integer stored in O byte order.

I128

A 128-bit signed integer stored in O byte order.

U16

A 16-bit unsigned integer stored in O byte order.

U32

A 32-bit unsigned integer stored in O byte order.

U64

A 64-bit unsigned integer stored in O byte order.

U128

A 128-bit unsigned integer stored in O byte order.