Skip to main content

Pack

Trait Pack 

Source
pub trait Pack: Packable {
    // Provided methods
    fn bit_size() -> u32 { ... }
    fn byte_size() -> usize { ... }
    fn encode(&self) -> Vec<u8>  { ... }
    fn encode_to_buf(&self, buf: &mut [u8]) -> usize { ... }
    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> { ... }
}
Expand description

High-level encode/decode that handles byte-level packing.

This trait is automatically implemented for all Packable types via a blanket impl. It converts ordinals to and from little-endian byte representations using the minimum number of bytes needed for the type’s RADIX.

§Example

use planck_pack_core::{Packable, Pack};

// bool has RADIX = 2, so it encodes to 1 byte
assert_eq!(bool::byte_size(), 1);
assert_eq!(bool::bit_size(), 1);

let bytes = true.encode();
assert_eq!(bool::decode(&bytes).unwrap(), true);

Provided Methods§

Source

fn bit_size() -> u32

Number of bits needed to represent this type’s full radix.

Computed as ⌈log₂(RADIX)⌉. Returns 0 for types with RADIX ≤ 1.

Source

fn byte_size() -> usize

Number of bytes needed (byte-aligned).

This is ⌈bit_size() / 8⌉. Every value of this type encodes to exactly this many bytes.

Source

fn encode(&self) -> Vec<u8>

Encode this value to bytes (little-endian).

The returned Vec has exactly byte_size() bytes.

Source

fn encode_to_buf(&self, buf: &mut [u8]) -> usize

Encode this value into a fixed-size buffer. Returns number of bytes written.

The buffer must be at least byte_size() bytes long. Useful in no_std environments where allocation is unavailable.

Source

fn decode(bytes: &[u8]) -> Result<Self, DecodeError>

Decode from bytes (little-endian).

Reads exactly byte_size() bytes from the front of the slice. Returns DecodeError::InsufficientData if the slice is too short.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: Packable> Pack for T