Skip to main content

Packable

Trait Packable 

Source
pub trait Packable: Sized {
    const RADIX: u128;

    // Required methods
    fn to_ordinal(&self) -> u128;
    fn from_ordinal(ord: u128) -> Result<Self, DecodeError>;
}
Expand description

A type that can be packed into a mixed-radix representation.

Each implementor declares how many distinct values it can take (RADIX) and provides bidirectional mapping between values and ordinals in [0, RADIX).

Planck uses these ordinals to encode structs as mixed-radix numbers: each field becomes a digit with its own base. The total number of bits needed is ⌈log₂(r₁ × r₂ × ... × rₙ)⌉, which is always ≤ the sum of individual field bit widths.

§Derive

The easiest way to implement this trait is via #[derive(Planck)] from the planck crate.

§Manual Implementation

use planck_pack_core::{Packable, DecodeError};

struct DieRoll(u8); // 1-6

impl Packable for DieRoll {
    const RADIX: u128 = 6;

    fn to_ordinal(&self) -> u128 {
        (self.0 - 1) as u128
    }

    fn from_ordinal(ord: u128) -> Result<Self, DecodeError> {
        if ord < 6 {
            Ok(DieRoll(ord as u8 + 1))
        } else {
            Err(DecodeError::OrdinalOutOfRange { ordinal: ord, radix: 6 })
        }
    }
}

assert_eq!(DieRoll(3).to_ordinal(), 2);
assert_eq!(DieRoll::RADIX, 6);

Required Associated Constants§

Source

const RADIX: u128

The number of distinct values this type can take.

For a bool this is 2, for an enum with 3 variants this is 3, for a u8 constrained to 0..=10 this is 11.

For structs, RADIX is the product of all field radixes. For enums, RADIX is the sum of all variant radixes.

Required Methods§

Source

fn to_ordinal(&self) -> u128

Convert this value to its ordinal position in [0, RADIX).

The returned value must always be less than RADIX.

Source

fn from_ordinal(ord: u128) -> Result<Self, DecodeError>

Reconstruct from an ordinal. Returns Err if ord >= RADIX.

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.

Implementations on Foreign Types§

Source§

impl Packable for bool

Source§

impl Packable for i8

Source§

impl Packable for i16

Source§

impl Packable for i32

Source§

impl Packable for i64

Source§

impl Packable for u8

Source§

impl Packable for u16

Source§

impl Packable for u32

Source§

impl Packable for u64

Source§

impl Packable for ()

Source§

impl<T: Packable> Packable for Option<T>

Implementors§