use http::Extensions;
pub(crate) trait RequestConfigValue: Clone + 'static {
type Value: Clone + Send + Sync + 'static;
}
#[derive(Clone, Copy)]
pub(crate) struct RequestConfig<T: RequestConfigValue>(Option<T::Value>);
impl<T: RequestConfigValue> Default for RequestConfig<T> {
#[inline]
fn default() -> Self {
RequestConfig(None)
}
}
impl<T> RequestConfig<T>
where
T: RequestConfigValue,
{
#[inline]
pub(crate) const fn new(v: Option<T::Value>) -> Self {
RequestConfig(v)
}
#[inline]
pub(crate) const fn as_ref(&self) -> Option<&T::Value> {
self.0.as_ref()
}
#[inline]
pub(crate) fn fetch<'a>(&'a self, ext: &'a Extensions) -> Option<&'a T::Value> {
ext.get::<RequestConfig<T>>()
.and_then(Self::as_ref)
.or(self.as_ref())
}
#[inline]
pub(crate) fn store<'a>(&'a self, ext: &'a mut Extensions) -> &'a mut Option<T::Value> {
&mut ext.get_or_insert_with(|| self.clone()).0
}
#[inline]
pub(crate) fn load(&mut self, ext: &mut Extensions) -> Option<&T::Value> {
if let Some(value) = RequestConfig::<T>::remove(ext) {
self.0.replace(value);
}
self.as_ref()
}
#[inline]
pub(crate) fn get(ext: &Extensions) -> Option<&T::Value> {
ext.get::<RequestConfig<T>>()?.0.as_ref()
}
#[inline]
pub(crate) fn get_mut(ext: &mut Extensions) -> &mut Option<T::Value> {
&mut ext.get_or_insert_default::<RequestConfig<T>>().0
}
#[inline]
pub(crate) fn remove(ext: &mut Extensions) -> Option<T::Value> {
ext.remove::<RequestConfig<T>>()?.0
}
}
#[allow(unused_macro_rules)]
macro_rules! impl_request_config_value {
($type:ty) => {
impl crate::config::RequestConfigValue for $type {
type Value = Self;
}
};
($type:ty, $value:ty) => {
impl crate::config::RequestConfigValue for $type {
type Value = $value;
}
};
}