#enums #map #key #derive #bool #type

no-std linearize

Types that are enumerable and an array-backed map

2 releases

new 0.1.1 Nov 21, 2024
0.1.0 Nov 21, 2024

#400 in Data structures

MIT/Apache

115KB
2.5K SLoC

linearize

crates.io docs.rs

This crate provides a trait that defines an enumeration of a type and an efficient no_std map that uses such types as keys.

Example

use linearize::{Linearize, static_map};

#[derive(Linearize)]
enum Keys {
    A,
    B(bool),
}

fn main() {
    let map = static_map! {
        Keys::A => "a",
        Keys::B(false) => "b",
        Keys::B(true) => "c",
    };
    assert_eq!(map[Keys::A], "a");
    assert_eq!(map[Keys::B(true)], "c");
}

License

This project is licensed under either of

  • Apache License, Version 2.0
  • MIT License

at your option.


lib.rs:

A crate for enumerable types.

This crate provides the [Linearize] trait which defines a bijection between a type and an interval of the natural numbers.

Given such a bijection, many useful things become possible. For example, this crate defines the types [StaticMap] and [StaticCopyMap] which provide high-performance, non-allocating mappings from linearizable types to arbitrary values.

#
#[derive(Linearize)]
enum ColorFormat {
    R,
    Rgb {
        alpha: bool,
    },
}

let mut channels = StaticMap::default();
channels[ColorFormat::R] = 1;
channels[ColorFormat::Rgb { alpha: false }] = 3;
channels[ColorFormat::Rgb { alpha: true }] = 4;

assert_eq!(channels[ColorFormat::Rgb { alpha: false }], 3);

These maps can be constructed conveniently with the [static_map] macro:

#
#
let channels = static_map! {
    ColorFormat::R => 1,
    ColorFormat::Rgb { alpha } => 3 + alpha as u32,
};

assert_eq!(channels[ColorFormat::Rgb { alpha: false }], 3);

Features

The following features are enabled by default:

  • std

This crate provides the following features:

  • alloc: Adds a dependency on the alloc crate. This implements additional traits for the map types.
  • std: Adds a dependency on the std crate.
  • derive: Provides the Linearize derive macro.
  • serde-1: Implements Serialize and Deserialize from serde 1.x for the map types.
  • arbitrary-1: Implements Arbitrary from arbitrary 1.x for the map types.
  • bytemuck-1: Implements NoUninit, Zeroable, and AnyBitPattern from bytemuck 1.x for the map types.
  • rand-0_8: Implements various distributions from rand 0.8.x for the map types. All iterators exposed by this crate.

This module exists only to keep the top-level namespace clean.

Dependencies

~2–300KB