1use std::convert::Infallible;
6use std::rc::Rc;
7
8use crate::{extract::FromContext, hl::context::RequestContext, hl::context::ResponseContext};
9
10#[cfg(feature = "experimental_websocket")]
11use crate::extract::context::{UpgradeDownstreamContext, UpgradeUpstreamContext};
12
13#[derive(Clone)]
14pub struct State<S>(pub Rc<S>);
15
16impl<S> FromContext<RequestContext<S>> for State<S> {
17 type Error = Infallible;
18
19 fn from_context(context: &RequestContext<S>) -> Result<Self, Self::Error> {
20 Ok(Self(Rc::clone(context.state())))
21 }
22}
23
24impl<D, S> FromContext<ResponseContext<D, S>> for State<S> {
25 type Error = Infallible;
26
27 fn from_context(context: &ResponseContext<D, S>) -> Result<Self, Self::Error> {
28 Ok(Self(Rc::clone(context.state())))
29 }
30}
31
32#[cfg(feature = "experimental_websocket")]
33impl<S> FromContext<UpgradeUpstreamContext<S>> for State<S> {
34 type Error = Infallible;
35
36 fn from_context(context: &UpgradeUpstreamContext<S>) -> Result<Self, Self::Error> {
37 Ok(Self(Rc::clone(context.state())))
38 }
39}
40
41#[cfg(feature = "experimental_websocket")]
42impl<S> FromContext<UpgradeDownstreamContext<S>> for State<S> {
43 type Error = Infallible;
44
45 fn from_context(context: &UpgradeDownstreamContext<S>) -> Result<Self, Self::Error> {
46 Ok(Self(Rc::clone(context.state())))
47 }
48}
49
50impl<F, S> CreateHandler for F
51where
52 F: Fn() -> S,
53{
54 type State = S;
55
56 fn create(&self) -> Self::State {
57 self()
58 }
59}
60
61pub trait CreateHandler {
62 type State;
63
64 fn create(&self) -> Self::State;
65}
66
67pub struct EmptyCreateHandler;
68
69impl CreateHandler for EmptyCreateHandler {
70 type State = ();
71
72 fn create(&self) -> Self::State {}
73}
74
75pub trait DoneHandler<S> {
76 fn done(&self, state: S);
77}
78
79impl<S> DoneHandler<S> for () {
80 fn done(&self, _state: S) {}
81}
82
83impl<F, S> DoneHandler<S> for F
84where
85 F: Fn(S),
86{
87 fn done(&self, state: S) {
88 self(state)
89 }
90}