#len #size #length #index-map #dynamic #optimization #size-optimization

small_len

A small library for storing the length in the smallest internal type

24 releases (6 stable)

1.1.2 Jul 17, 2024
0.7.0 Jul 14, 2024

#384 in Algorithms

Download history 528/week @ 2024-06-27 150/week @ 2024-07-04 1282/week @ 2024-07-11 189/week @ 2024-07-18 152/week @ 2024-07-25 23/week @ 2024-08-01

51 downloads per month
Used in 2 crates

MIT license

22KB
615 lines

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, String, [T], &[T], Vec, HashMap, and IndexMap (with feature indexmap); if you need an optimization for static bounds at compile time check out the smallnum crate.

For a generic number crate check out varnum.

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();
    let c = SmallLen::from_be_bytes(&bytes); // SmallLen::from_bytes() -> Length::Byte(3)
}

Features

  • default: No extra features, includes Vec and HashMap<K, V> implementations.
  • bumpalo: Adds Len implementation for bumpalo::Bump.
  • bytes: Adds Len implementation for bytes::Bytes and bytes::BytesMut.
  • indexmap: Adds Len implementation for indexmap::IndexMap.

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) -> Length {
        self.len().into() // Length::new(self.len())
    }
}

Additional Traits

The Length enum also implements the following traits for easier use (Length | SmallLength | usize):

  • Index for Vec, this will panic if the index is out of bounds
  • Add
  • Div
  • Mul
  • Rem
  • Sub
  • Not
  • BitAnd
  • BitOr
  • BitXor

Dependencies

~0–590KB