#typemap #map #no-std #static #traits #tyght

nightly no-std tyght-map

A static type map implementation

8 releases

0.2.0 Mar 9, 2024
0.1.1 May 24, 2023
0.1.0 Mar 23, 2023

#2387 in Data structures

MIT license

17KB
335 lines

tyght-map

CI Crates.io Documentation License: MIT

A static type map implementation.


lib.rs:

The tyght-map crate provides a static type map implementation.

A type map is a map where the values are indexed by their types.

The map, TyghtMap, enjoys the following properties:

  • The size of the map will match the size of its items.
  • No heap allocations, this crate is !#[no_std].
  • Provides both infallible and fallible methods.
  • No unsafe.

Example

#![feature(generic_const_exprs)]

// Insert some different types into the map and check the size
let map = TyghtMap::new().insert(3u32).insert(4i32).insert(3f32);
assert_eq!(std::mem::size_of_val(&map), 12);

// Retrieve the `u32` from the map
let item: &u32 = map.get();
assert_eq!(*item, 3);

// Insert a `String` into the map, then mutate it
let mut map = map.insert("Hey".to_string());
*map.get_mut::<String>() += ", world!";

// Try to get a `u8` from the map
let item = map.try_get::<u8>();
assert_eq!(item, None);

// Remove the `String` from the map
let (item, _map) = map.remove::<String>();
println!("{item}");

Traits

Placing constraints on the S of TyghtMap<S> acts as a constraint on the values it contains.

There are three important marker traits:

The following function cannot be called using a map which does not contain a String and a u32.

fn print_string<S>(map: &TyghtMap<S>)
where
    S: Contains<String>,
    S: Contains<u32>,
{
    let string: &String = map.get();
    let int: &u32 = map.get();
    println!("{string} {int}");
}

Nightly

In contrast to other attempts, this implementation does not rely on specialization. It does however rely on a variety of nightly features:

These can be expected to be stabilized, in some form, before specialization.

No runtime deps