use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Default, Clone)]
pub struct TypeMap {
map: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}
pub type StateMap = TypeMap;
impl TypeMap {
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
pub fn insert<T>(&mut self, value: T)
where
T: Send + Sync + 'static,
{
self.map.insert(TypeId::of::<T>(), Arc::new(value));
}
pub fn get<T>(&self) -> Option<Arc<T>>
where
T: Send + Sync + 'static,
{
self.map
.get(&TypeId::of::<T>())
.and_then(|v| v.clone().downcast::<T>().ok())
}
pub fn extend(&mut self, other: TypeMap) {
self.map.extend(other.map);
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub(crate) fn clone_map(&self) -> TypeMap {
self.clone()
}
}
#[derive(Default)]
pub struct Extensions {
map: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}
impl Extensions {
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
self.map.insert(TypeId::of::<T>(), Box::new(value));
}
pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
self.map
.get(&TypeId::of::<T>())
.and_then(|v| v.downcast_ref::<T>())
}
pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
self.map
.get_mut(&TypeId::of::<T>())
.and_then(|v| v.downcast_mut::<T>())
}
pub fn remove<T: Send + Sync + 'static>(&mut self) -> Option<T> {
self.map
.remove(&TypeId::of::<T>())
.and_then(|v| v.downcast::<T>().ok().map(|b| *b))
}
}
#[derive(Clone)]
pub struct MatchedMeta(pub crate::route_value::MetaMap);
#[derive(Clone, Default)]
pub struct MatchedMetaCapture {
inner: std::sync::Arc<std::sync::Mutex<Option<crate::route_value::MetaMap>>>,
}
impl MatchedMetaCapture {
pub fn new() -> Self {
Self::default()
}
pub fn set(&self, meta: crate::route_value::MetaMap) {
*self.inner.lock().unwrap() = Some(meta);
}
pub fn get(&self) -> Option<crate::route_value::MetaMap> {
self.inner.lock().unwrap().clone()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MatchedRoute(pub String);
#[derive(Clone, Default)]
pub struct MatchedRouteCapture {
inner: std::sync::Arc<std::sync::Mutex<Option<String>>>,
}
impl MatchedRouteCapture {
pub fn new() -> Self {
Self::default()
}
pub fn set(&self, route: impl Into<String>) {
*self.inner.lock().unwrap() = Some(route.into());
}
pub fn get(&self) -> Option<String> {
self.inner.lock().unwrap().clone()
}
}