Skip to main content

Crate anystash

Crate anystash 

Source
Expand description

A modern, zero-dependency, zero-unsafe heterogeneous type map.

A type map stores at most one value of each Rust type and retrieves it by type rather than by key. It is the classic building block behind HTTP request extensions, plugin registries, dependency-injection containers, ECS-style per-entity data and “context” objects that middleware layers extend as a request travels through them.

This niche was long served by the typemap crate, which has been unmaintained for years. anystash fills it with a small, dependency-free, #![forbid(unsafe_code)] implementation.

§Quick start

use anystash::Stash;

#[derive(Debug, PartialEq)]
struct Config { retries: u32 }

let mut stash = Stash::new();
stash.insert(Config { retries: 3 });
stash.insert("hello");

assert_eq!(stash.get::<Config>(), Some(&Config { retries: 3 }));
assert_eq!(stash.get::<&str>(), Some(&"hello"));
assert_eq!(stash.len(), 2);

stash.get_mut::<Config>().unwrap().retries = 5;
assert_eq!(stash.remove::<Config>(), Some(Config { retries: 5 }));
assert!(stash.get::<Config>().is_none());

§Choosing a map

Two flavors are provided. They have identical APIs and differ only in the bound placed on stored values:

TypeValue boundMap is Send + SyncUse when
Stash'staticnoSingle-threaded; values may be !Send
SyncStash'static + Send + SyncyesShared across threads behind Arc/a lock

Prefer Stash unless you actually need to move the map across threads — it accepts strictly more types, including Rc and RefCell.

use anystash::SyncStash;
use std::sync::{Arc, Mutex};

let mut stash = SyncStash::new();
stash.insert(42u32);

let shared = Arc::new(Mutex::new(stash));
let handle = {
    let shared = Arc::clone(&shared);
    std::thread::spawn(move || {
        *shared.lock().unwrap().get_or_default::<u32>() += 1;
    })
};
handle.join().unwrap();

assert_eq!(shared.lock().unwrap().get::<u32>(), Some(&43));

§The newtype pattern

Because lookup is keyed by type, storing two logically different values that share a type collides. Wrap them in distinct newtypes to keep them apart:

use anystash::Stash;

struct RequestId(String);
struct TraceId(String);

let mut stash = Stash::new();
stash.insert(RequestId("req-1".into()));
stash.insert(TraceId("trace-9".into()));

// Two `String`s coexist because their wrapper types differ.
assert_eq!(stash.len(), 2);
assert_eq!(stash.get::<RequestId>().unwrap().0, "req-1");

§Performance

Values are boxed and stored in a HashMap keyed by TypeId. Lookups are a hash of a 128-bit id plus a pointer dereference; there is no per-lookup type comparison beyond that. Insert and remove move the value into and out of a Box, so prefer storing small handles over large structs when a value is inserted on a hot path.

§Design notes

  • No unsafe. The crate is #![forbid(unsafe_code)]. Downcasting goes through Any::downcast_ref and friends, so the compiler and standard library enforce type safety rather than hand-written pointer casts.
  • No dependencies. Nothing outside std, which keeps build times and supply-chain surface minimal.
  • No trait to implement. Unlike typemap, values do not need to implement a Key trait; any 'static type works as-is, including types from other crates.

§Minimum supported Rust version

Rust 1.75. Raising the MSRV is treated as a breaking change and will come with a minor version bump before 1.0.

Structs§

Stash
A single-threaded heterogeneous type map.
SyncStash
A thread-safe heterogeneous type map.