This crate provides type-keyed data structures that use Rust types as keys, allowing you to store one value per type.
Data Structures
SingletonSet
A SingletonSet stores at most one value of each type. Think of it as a
HashSet where the type of the value is the key.
use SingletonSet;
let mut set = new;
// Insert values of different types
set.insert;
set.insert;
set.insert;
// Each type has its own slot - inserting again replaces the value
set.insert; // Replaces 42
// Retrieve values by type
assert_eq!;
assert_eq!;
// Check if a type is present
assert!;
assert!;
This is useful for creating locally-scoped singletons without polluting the global scope. It ensures there is only one instance of any type, similar to a traditional Singleton pattern, but with proper scoping.
SingletonMap
A SingletonMap<V> maps types to values of a single value type V. Think of
it as a HashMap<TypeId, V> with a more ergonomic API.
use SingletonMap;
let mut descriptions: = new;
// Map types to descriptions
descriptions.;
descriptions.;
descriptions.;
// Retrieve by type
assert_eq!;
assert_eq!;
// Use the entry API for conditional insertion
descriptions..or_insert;
This is useful when you need to associate metadata, configuration, or handlers with specific types.
Features
- Type Safety: Leverages Rust's type system to ensure compile-time safety when working with type-keyed collections.
- Flexible Initialization: Types implementing
Defaultcan be auto-initialized, or use explicit values and closures for full control. - Scoped Singletons: Unlike global singletons, these collections can be scoped as needed, avoiding global state issues.
- Insertion Order: Both structures preserve insertion order (backed by
IndexMap).
Feature Flags
This crate provides two feature flags, both enabled by default:
set- EnablesSingletonSetmap- EnablesSingletonMap
Installation
Or add the following to your Cargo.toml:
[]
= "0.1"
Contributing
Contributions are welcome! Please open an issue or submit a pull request if you have any suggestions, bug reports, or feature requests.
License
Licensed under either of the Apache License, Version 2.0 or the MIT license 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.