small_len 0.1.0

A small library for storing the length in the smallest internal type, with an extra byte signifying that type.
Documentation

small_len

A simple enum and trait to ensure that the value returned by small_len() is always the smallest representation. This is meant to be used by fn_vm to support "infinite" commands, arguments, and registers.

NOTE: This is primarily meant for dynamic sized objects, Vec, HashMap, and IndexMap (with feature indexmap); if you need an optimization for static bounds at compile time check out the smallnum crate.

Usage

use small_len::SmallLen;

fn main() {
    let a = vec![1, 2, 3];
    let c = a.small_len(); // Length::Byte(3)
    let bytes = c.to_be_bytes(); // c.to_bytes() is platform dependent
    let c = SmallLen::from_be_bytes(&bytes); // SmallLen::from_bytes() -> Length::U8(3)
}

Custom Types

If you need to add SmallLen to another type, you can implement the Len trait.

impl <T> Len for Vec<T> {
    #[inline]
    fn length(&self) -> usize {
        self.len()
    }
}

Additional Traits

The Length enum also implements the following traits for easier use:

  • Index for Vec, this will panic if the index is out of bounds
  • Add -> usize
  • Div -> usize
  • Mul -> usize
  • Rem -> usize
  • Sub -> usize