anystash
A modern, zero-dependency, zero-unsafe heterogeneous type map for Rust.
Store at most one value of each type; retrieve it by type. This is the building
block behind HTTP request extensions, plugin registries, dependency-injection
containers and per-entity data — a niche long served by the unmaintained
typemap crate, which anystash replaces.
[]
= "0.1"
Example
use Stash;
let mut stash = new;
stash.insert;
stash.insert;
assert_eq!;
assert_eq!;
stash..unwrap.retries = 5;
assert_eq!;
Choosing a map
Both types expose an identical API and differ only in the bound on stored values.
| Type | Value bound | Map is Send + Sync |
Use when |
|---|---|---|---|
Stash |
'static |
no | Single-threaded; values may be !Send |
SyncStash |
'static + Send + Sync |
yes | Shared across threads behind Arc/a lock |
Prefer Stash unless the map must cross a thread boundary — it accepts strictly
more types, including Rc and RefCell.
API
| Method | Description |
|---|---|
new / with_capacity |
Create an empty map |
insert(value) |
Store a value, returning any previous one |
get::<T> / get_mut::<T> |
Borrow the stored value of type T |
get_or_default::<T> |
Borrow, inserting T::default() if absent |
get_or_insert_with(f) |
Borrow, inserting f() if absent |
remove::<T> |
Take the value of type T back out |
contains::<T> |
Test whether a value of type T is present |
len / is_empty / clear |
Inspect or empty the map |
The newtype pattern
Lookup is keyed by type, so two logically distinct values sharing a type collide. Wrap them to keep them apart:
use Stash;
;
;
let mut stash = new;
stash.insert;
stash.insert;
assert_eq!; // two `String`s coexist
Why anystash
- No dependencies. Nothing beyond
std— minimal build time and supply-chain surface. - No
unsafe.#![forbid(unsafe_code)]; downcasting goes throughstd::any. - No trait to implement. Unlike
typemap, values need noKeyimpl — any'statictype works, including types from other crates. - Documented. Every public method carries a compiling example.
Examples
Shows middleware layers attaching typed data to a request without knowing about one another.
Minimum supported Rust version
Rust 1.75. An MSRV bump is treated as a breaking change and will come with a minor version bump before 1.0.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.