Module zerocopy::byteorder[][src]

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

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

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

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

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

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

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

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

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

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

Enums

Defines big-endian serialization.

Defines little-endian serialization.

Traits

ByteOrder describes types that can serialize integers as bytes.

Type Definitions

A type alias for BigEndian.

A type alias for LittleEndian.

Defines system native-endian serialization.

Defines network byte order serialization.