#![forbid(unsafe_code)]
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
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 {
#[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() }
}
#[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) }
}
#[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))
}
#[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())
}
#[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())
}
#[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)
}
#[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()));
self.get_mut::<T>().expect("value just ensured")
}
#[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))
}
#[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>())
}
#[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()
}
#[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()
}
#[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();
}
}
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()
}
}
};
}
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!(
Stash
);
define_stash!(
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());
}
}