use std::convert::Infallible;
use std::rc::Rc;
use crate::{extract::FromContext, hl::context::RequestContext, hl::context::ResponseContext};
#[derive(Clone)]
pub struct State<S>(pub Rc<S>);
impl<S> FromContext<RequestContext<S>> for State<S> {
type Error = Infallible;
fn from_context(context: &RequestContext<S>) -> Result<Self, Self::Error> {
Ok(Self(Rc::clone(context.state())))
}
}
impl<D, S> FromContext<ResponseContext<D, S>> for State<S> {
type Error = Infallible;
fn from_context(context: &ResponseContext<D, S>) -> Result<Self, Self::Error> {
Ok(Self(Rc::clone(context.state())))
}
}
impl<F, S> CreateHandler for F
where
F: Fn() -> S,
{
type State = S;
fn create(&self) -> Self::State {
self()
}
}
pub trait CreateHandler {
type State;
fn create(&self) -> Self::State;
}
pub struct EmptyCreateHandler;
impl CreateHandler for EmptyCreateHandler {
type State = ();
fn create(&self) -> Self::State {}
}
pub trait DoneHandler<S> {
fn done(&self, state: S);
}
impl<S> DoneHandler<S> for () {
fn done(&self, _state: S) {
}
}
impl<F, S> DoneHandler<S> for F
where
F: Fn(S),
{
fn done(&self, state: S) {
self(state)
}
}