Skip to main content

Module enc_into_array

Module enc_into_array 

Source
Expand description

EncodeIntoArray trait for stack-based encoding Stack-based encoding trait for no-allocation varint encoding.

This module provides the EncodeIntoArray trait, which allows encoding values into a stack-allocated array without any heap allocation. This is essential for no_std environments and embedded systems.

§Performance Benefits

Using EncodeIntoArray provides:

  • Zero heap allocations: All data on stack
  • Deterministic performance: No GC or allocator overhead
  • Embedded-friendly: Works in no_std contexts
  • Predictable memory: Compile-time known sizes

§Use Cases

  • Embedded systems without allocator
  • Real-time systems requiring deterministic performance
  • no_std environments
  • Memory-constrained devices
  • Safety-critical systems

§Examples

§Basic stack encoding

use multi_trait::EncodeIntoArray;

let (array, len) = 42u8.encode_into_array();
assert_eq!(&array[..len], &[42]);

§Working with larger values

use multi_trait::EncodeIntoArray;

let (array, len) = 1000u16.encode_into_array();
// Varint encoding of 1000 takes 2 bytes
assert_eq!(len, 2);
assert_eq!(&array[..len], &[0xE8, 0x07]);

§Maximum encoded sizes

Each type has a compile-time known maximum encoded size:

use multi_trait::EncodeIntoArray;

// u8 values fit in 2 bytes max
assert_eq!(<u8 as EncodeIntoArray>::MAX_ENCODED_SIZE, 2);

// u16 values fit in 3 bytes max
assert_eq!(<u16 as EncodeIntoArray>::MAX_ENCODED_SIZE, 3);

// u32 values fit in 5 bytes max
assert_eq!(<u32 as EncodeIntoArray>::MAX_ENCODED_SIZE, 5);

Constants§

MAX_VARINT_SIZE
Maximum size needed for any varint encoding (u128 max = 19 bytes)

Traits§

EncodeIntoArray
Trait for encoding values into a stack-allocated array.