use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt::{self, Formatter};
#[derive(Default)]
pub struct Depot {
map: HashMap<String, Box<dyn Any + Send + Sync>>,
}
#[inline]
fn type_key<T: 'static>() -> String {
format!("{:?}", TypeId::of::<T>())
}
impl Depot {
#[inline]
pub fn new() -> Depot {
Depot { map: HashMap::new() }
}
#[inline]
pub fn inner(&self) -> &HashMap<String, Box<dyn Any + Send + Sync>> {
&self.map
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Depot {
map: HashMap::with_capacity(capacity),
}
}
#[inline]
pub fn capacity(&self) -> usize {
self.map.capacity()
}
#[inline]
pub fn inject<V: Any + Send + Sync>(&mut self, value: V) -> &mut Self {
self.map.insert(type_key::<V>(), Box::new(value));
self
}
#[inline]
pub fn obtain<T: Any + Send + Sync>(&self) -> Result<&T, Option<&Box<dyn Any + Send + Sync>>> {
self.get(&type_key::<T>())
}
#[inline]
pub fn obtain_mut<T: Any + Send + Sync>(&mut self) -> Result<&mut T, Option<&mut Box<dyn Any + Send + Sync>>> {
self.get_mut(&type_key::<T>())
}
#[inline]
pub fn insert<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: Into<String>,
V: Any + Send + Sync,
{
self.map.insert(key.into(), Box::new(value));
self
}
#[inline]
pub fn contains_key(&self, key: &str) -> bool {
self.map.contains_key(key)
}
#[inline]
pub fn contains<T: Any + Send + Sync>(&self) -> bool {
self.map.contains_key(&type_key::<T>())
}
#[inline]
pub fn get<V: Any + Send + Sync>(&self, key: &str) -> Result<&V, Option<&Box<dyn Any + Send + Sync>>> {
if let Some(value) = self.map.get(key) {
value.downcast_ref::<V>().ok_or(Some(value))
} else {
Err(None)
}
}
#[inline]
pub fn get_mut<V: Any + Send + Sync>(
&mut self,
key: &str,
) -> Result<&mut V, Option<&mut Box<dyn Any + Send + Sync>>> {
if let Some(value) = self.map.get_mut(key) {
if value.downcast_mut::<V>().is_some() {
return Ok(value.downcast_mut::<V>().unwrap());
} else {
Err(Some(value))
}
} else {
Err(None)
}
}
#[inline]
pub fn remove<V: Any + Send + Sync>(&mut self, key: &str) -> Result<V, Option<Box<dyn Any + Send + Sync>>> {
if let Some(value) = self.map.remove(key) {
value.downcast::<V>().map(|b| *b).map_err(Some)
} else {
Err(None)
}
}
#[inline]
pub fn delete(&mut self, key: &str) -> bool {
self.map.remove(key).is_some()
}
#[inline]
pub fn scrape<T: Any + Send + Sync>(&mut self) -> Result<T, Option<Box<dyn Any + Send + Sync>>> {
self.remove(&type_key::<T>())
}
}
impl fmt::Debug for Depot {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Depot").field("keys", &self.map.keys()).finish()
}
}
#[cfg(test)]
mod test {
use crate::prelude::*;
use crate::test::{ResponseExt, TestClient};
use super::*;
#[test]
fn test_depot() {
let mut depot = Depot::with_capacity(6);
assert!(depot.capacity() >= 6);
depot.insert("one", "ONE".to_owned());
assert!(depot.contains_key("one"));
assert_eq!(depot.get::<String>("one").unwrap(), &"ONE".to_owned());
assert_eq!(depot.get_mut::<String>("one").unwrap(), &mut "ONE".to_owned());
}
#[tokio::test]
async fn test_middleware_use_depot() {
#[handler]
async fn set_user(req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
depot.insert("user", "client");
ctrl.call_next(req, depot, res).await;
}
#[handler]
async fn hello(depot: &mut Depot) -> String {
format!("Hello {}", depot.get::<&str>("user").copied().unwrap_or_default())
}
let router = Router::new().hoop(set_user).goal(hello);
let service = Service::new(router);
let content = TestClient::get("http://127.0.0.1:5800")
.send(&service)
.await
.take_string()
.await
.unwrap();
assert_eq!(content, "Hello client");
}
}