Skip to main content

FixedOrderableBytes

Trait FixedOrderableBytes 

Source
pub trait FixedOrderableBytes: OrderableBytes {
    type Array: AsRef<[u8]> + Copy;

    const ENCODED_LEN: usize;

    // Required method
    fn to_fixed_orderable_bytes(&self) -> Self::Array;
}
Expand description

An OrderableBytes encoding whose length is the same for every value of the type.

to_fixed_orderable_bytes returns the same bytes as to_orderable_bytes, as an owned Array of exactly ENCODED_LEN bytes that doesn’t borrow from the value. Generic code can store or return it:

use orderable_bytes::FixedOrderableBytes;

fn term<T: FixedOrderableBytes>(value: T) -> T::Array {
    value.to_fixed_orderable_bytes()
}

assert_eq!(term(7u32), [0, 0, 0, 7]);

Fixed-length encodings may be zero-extended to a larger block, since every value is extended the same way. Bounding on this trait is what keeps variable-length types out of such code:

use orderable_bytes::FixedOrderableBytes;

fn pad_to_16<T: FixedOrderableBytes>(value: &T) -> [u8; 16] {
    let mut block = [0u8; 16];
    block[..T::ENCODED_LEN].copy_from_slice(value.to_fixed_orderable_bytes().as_ref());
    block
}

assert!(pad_to_16(&1u32) < pad_to_16(&2u32));
ⓘ
// Strings are variable-length, so padding them is rejected.
pad_to_16(&String::from("a"));

Required Associated Constants§

Source

const ENCODED_LEN: usize

Length, in bytes, of the canonical encoding.

Required Associated Types§

Source

type Array: AsRef<[u8]> + Copy

The owned encoding: always [u8; ENCODED_LEN].

Required Methods§

Source

fn to_fixed_orderable_bytes(&self) -> Self::Array

Build the canonical, order-preserving byte encoding of self as an owned array. The bytes are the same as to_orderable_bytes returns.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl FixedOrderableBytes for bool

Source§

impl FixedOrderableBytes for char

Source§

impl FixedOrderableBytes for f32

Source§

impl FixedOrderableBytes for f64

Source§

impl FixedOrderableBytes for i8

Source§

impl FixedOrderableBytes for i16

Source§

impl FixedOrderableBytes for i32

Source§

impl FixedOrderableBytes for i64

Source§

impl FixedOrderableBytes for i128

Source§

impl FixedOrderableBytes for u8

Source§

impl FixedOrderableBytes for u16

Source§

impl FixedOrderableBytes for u32

Source§

impl FixedOrderableBytes for u64

Source§

impl FixedOrderableBytes for u128

Source§

impl<T: FixedOrderableBytes + ?Sized> FixedOrderableBytes for &T

Source§

impl<const N: usize> FixedOrderableBytes for [u8; N]

Implementors§