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§
Required Methods§
Sourcefn to_ordinal(&self) -> u128
fn to_ordinal(&self) -> u128
Convert this value to its ordinal position in [0, RADIX).
The returned value must always be less than RADIX.
Sourcefn from_ordinal(ord: u128) -> Result<Self, DecodeError>
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.