anystash 0.1.0

A modern, zero-dependency, zero-unsafe heterogeneous type map. Successor niche of the unmaintained `typemap` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! 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:
//!
//! | 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 you actually need to move the map across threads —
//! it accepts strictly more types, including [`Rc`](std::rc::Rc) and
//! [`RefCell`](std::cell::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`](Any) 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.
//!
//! [`typemap`]: https://crates.io/crates/typemap
//! [`HashMap`]: std::collections::HashMap
//! [`TypeId`]: std::any::TypeId

#![forbid(unsafe_code)]

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;

/// Generates a stash type. `$extra` carries any auto-trait bounds that stored
/// values must satisfy (none for `Stash`, `Send + Sync` for `SyncStash`).
///
/// Public methods are bounded on `Any`, not on the private `AsAny`, so the
/// rendered API refers only to types callers can look up in `std`.
macro_rules! define_stash {
    ($(#[$doc:meta])* $name:ident $(+ $extra:ident)*) => {
        $(#[$doc])*
        #[derive(Default)]
        pub struct $name {
            map: HashMap<TypeId, Box<dyn AsAny $(+ $extra)*>>,
        }

        impl $name {
            /// Creates an empty map.
            ///
            /// This does not allocate until the first value is inserted.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let stash = ", stringify!($name), "::new();\n",
                "assert!(stash.is_empty());\n",
                "```",
            )]
            #[must_use]
            pub fn new() -> Self {
                Self { map: HashMap::new() }
            }

            /// Creates an empty map able to hold at least `capacity` values
            /// without reallocating.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::with_capacity(8);\n",
                "stash.insert(1u32);\n",
                "assert_eq!(stash.len(), 1);\n",
                "```",
            )]
            #[must_use]
            pub fn with_capacity(capacity: usize) -> Self {
                Self { map: HashMap::with_capacity(capacity) }
            }

            /// Inserts a value, returning the previously stored value of the same
            /// type, if any.
            ///
            /// Only one value per type is kept, so inserting a second value of a
            /// type replaces the first and hands it back to you.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "assert_eq!(stash.insert(1u32), None);\n",
                "assert_eq!(stash.insert(2u32), Some(1));\n",
                "assert_eq!(stash.get::<u32>(), Some(&2));\n",
                "```",
            )]
            pub fn insert<T: Any $(+ $extra)*>(&mut self, value: T) -> Option<T> {
                self.map
                    .insert(TypeId::of::<T>(), Box::new(value))
                    .and_then(|b| b.into_any().downcast().ok().map(|b| *b))
            }

            /// Returns a reference to the stored value of type `T`, or `None` if
            /// no value of that type is present.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "stash.insert(String::from(\"hi\"));\n",
                "\n",
                "assert_eq!(stash.get::<String>().map(String::as_str), Some(\"hi\"));\n",
                "assert_eq!(stash.get::<u32>(), None);\n",
                "```",
            )]
            #[must_use]
            pub fn get<T: Any $(+ $extra)*>(&self) -> Option<&T> {
                self.map
                    .get(&TypeId::of::<T>())
                    .and_then(|b| (**b).as_any().downcast_ref())
            }

            /// Returns a mutable reference to the stored value of type `T`, or
            /// `None` if no value of that type is present.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "stash.insert(1u32);\n",
                "\n",
                "*stash.get_mut::<u32>().unwrap() += 41;\n",
                "assert_eq!(stash.get::<u32>(), Some(&42));\n",
                "```",
            )]
            #[must_use]
            pub fn get_mut<T: Any $(+ $extra)*>(&mut self) -> Option<&mut T> {
                self.map
                    .get_mut(&TypeId::of::<T>())
                    .and_then(|b| (**b).as_any_mut().downcast_mut())
            }

            /// Returns a mutable reference to the value of type `T`, inserting
            /// `T::default()` first if it is absent.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "*stash.get_or_default::<u32>() += 1;\n",
                "*stash.get_or_default::<u32>() += 1;\n",
                "assert_eq!(stash.get::<u32>(), Some(&2));\n",
                "```",
            )]
            pub fn get_or_default<T: Any $(+ $extra)* + Default>(&mut self) -> &mut T {
                self.get_or_insert_with(T::default)
            }

            /// Returns a mutable reference to the value of type `T`, inserting the
            /// result of `f` first if it is absent.
            ///
            /// `f` is only called when no value of type `T` is present, which makes
            /// this the right choice when constructing the default is expensive.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "let s = stash.get_or_insert_with(|| String::from(\"seed\"));\n",
                "s.push('!');\n",
                "\n",
                "// The closure is not called again; the stored value is reused.\n",
                "let s = stash.get_or_insert_with(|| String::from(\"ignored\"));\n",
                "assert_eq!(s, \"seed!\");\n",
                "```",
            )]
            pub fn get_or_insert_with<T: Any $(+ $extra)*>(
                &mut self,
                f: impl FnOnce() -> T,
            ) -> &mut T {
                self.map
                    .entry(TypeId::of::<T>())
                    .or_insert_with(|| Box::new(f()));
                // The entry above guarantees presence and correct type.
                self.get_mut::<T>().expect("value just ensured")
            }

            /// Removes the value of type `T` and returns it, or `None` if no value
            /// of that type was present.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "stash.insert(1u32);\n",
                "\n",
                "assert_eq!(stash.remove::<u32>(), Some(1));\n",
                "assert_eq!(stash.remove::<u32>(), None);\n",
                "```",
            )]
            pub fn remove<T: Any $(+ $extra)*>(&mut self) -> Option<T> {
                self.map
                    .remove(&TypeId::of::<T>())
                    .and_then(|b| b.into_any().downcast().ok().map(|b| *b))
            }

            /// Returns `true` if a value of type `T` is present.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "stash.insert(1u32);\n",
                "\n",
                "assert!(stash.contains::<u32>());\n",
                "assert!(!stash.contains::<i64>());\n",
                "```",
            )]
            #[must_use]
            pub fn contains<T: Any $(+ $extra)*>(&self) -> bool {
                self.map.contains_key(&TypeId::of::<T>())
            }

            /// Returns the number of stored values, which is the number of
            /// distinct types present.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "stash.insert(1u32);\n",
                "stash.insert(1u64);\n",
                "stash.insert(2u32); // replaces the first `u32`\n",
                "assert_eq!(stash.len(), 2);\n",
                "```",
            )]
            #[must_use]
            pub fn len(&self) -> usize {
                self.map.len()
            }

            /// Returns `true` if the map holds no values.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "assert!(stash.is_empty());\n",
                "stash.insert(1u32);\n",
                "assert!(!stash.is_empty());\n",
                "```",
            )]
            #[must_use]
            pub fn is_empty(&self) -> bool {
                self.map.is_empty()
            }

            /// Removes all values, keeping the allocated capacity.
            ///
            /// # Examples
            ///
            #[doc = concat!(
                "```\n",
                "use anystash::", stringify!($name), ";\n",
                "\n",
                "let mut stash = ", stringify!($name), "::new();\n",
                "stash.insert(1u32);\n",
                "stash.clear();\n",
                "assert!(stash.is_empty());\n",
                "```",
            )]
            pub fn clear(&mut self) {
                self.map.clear();
            }
        }

        // Stored values are opaque, so only the count is shown.
        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_struct(stringify!($name))
                    .field("len", &self.len())
                    .finish_non_exhaustive()
            }
        }
    };
}

/// Object-safe helper trait: upcast to `dyn Any`.
///
/// Blanket-implemented for every `'static` type, so users never implement it.
trait AsAny: Any {
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
    fn into_any(self: Box<Self>) -> Box<dyn Any>;
}

impl<T: Any> AsAny for T {
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }
}

define_stash!(
    /// A single-threaded heterogeneous type map.
    ///
    /// Values need only be `'static`, so `!Send` types such as
    /// [`Rc`](std::rc::Rc) and [`RefCell`](std::cell::RefCell) are accepted. The
    /// map itself is therefore neither `Send` nor `Sync`; use [`SyncStash`] when
    /// it must cross a thread boundary.
    ///
    /// # Examples
    ///
    /// ```
    /// use anystash::Stash;
    /// use std::rc::Rc;
    ///
    /// let mut stash = Stash::new();
    /// stash.insert(Rc::new(5u32)); // `!Send`, allowed here
    /// assert_eq!(**stash.get::<Rc<u32>>().unwrap(), 5);
    /// ```
    Stash
);

define_stash!(
    /// A thread-safe heterogeneous type map.
    ///
    /// Values must be `Send + Sync`, which makes the map itself `Send + Sync` and
    /// safe to share behind an [`Arc`](std::sync::Arc) and a lock. Use [`Stash`]
    /// if you need to store `!Send` values.
    ///
    /// # Examples
    ///
    /// ```
    /// use anystash::SyncStash;
    ///
    /// fn assert_send_sync<T: Send + Sync>() {}
    /// assert_send_sync::<SyncStash>();
    ///
    /// let mut stash = SyncStash::new();
    /// stash.insert(5u32);
    /// assert_eq!(stash.get::<u32>(), Some(&5));
    /// ```
    SyncStash + Send + Sync
);

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug, PartialEq, Default, Clone)]
    struct Counter(u64);

    #[test]
    fn insert_get_remove_roundtrip() {
        let mut s = Stash::new();
        assert!(s.is_empty());
        assert_eq!(s.insert(Counter(1)), None);
        assert_eq!(s.insert(Counter(2)), Some(Counter(1)));
        assert_eq!(s.get::<Counter>(), Some(&Counter(2)));
        assert!(s.contains::<Counter>());
        assert_eq!(s.remove::<Counter>(), Some(Counter(2)));
        assert!(!s.contains::<Counter>());
    }

    #[test]
    fn distinct_types_coexist() {
        let mut s = Stash::new();
        s.insert(1u8);
        s.insert(1u16);
        s.insert(String::from("x"));
        assert_eq!(s.len(), 3);
        assert_eq!(s.get::<u8>(), Some(&1));
        assert_eq!(s.get::<u16>(), Some(&1));
        assert_eq!(s.get::<String>().map(String::as_str), Some("x"));
    }

    #[test]
    fn get_or_default_and_with() {
        let mut s = Stash::new();
        s.get_or_default::<Counter>().0 += 10;
        assert_eq!(s.get::<Counter>(), Some(&Counter(10)));
        let v = s.get_or_insert_with(|| String::from("seed"));
        v.push('!');
        assert_eq!(s.get::<String>().map(String::as_str), Some("seed!"));
    }

    #[test]
    fn non_send_values_allowed_in_stash() {
        use std::rc::Rc;
        let mut s = Stash::new();
        s.insert(Rc::new(5u32));
        assert_eq!(**s.get::<Rc<u32>>().unwrap(), 5);
    }

    #[test]
    fn sync_stash_is_send_sync_and_shareable() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<SyncStash>();

        let mut s = SyncStash::new();
        s.insert(Counter(7));
        let s = std::sync::Arc::new(std::sync::Mutex::new(s));
        let s2 = s.clone();
        std::thread::spawn(move || {
            assert_eq!(s2.lock().unwrap().get::<Counter>(), Some(&Counter(7)));
        })
        .join()
        .unwrap();
    }

    #[test]
    fn clear_empties_map() {
        let mut s = Stash::new();
        s.insert(1u8);
        s.insert("a");
        s.clear();
        assert!(s.is_empty());
    }
}