1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use crate::{App, Model, Request, Response};
use std::cell::UnsafeCell;
use std::net::SocketAddr;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;

pub struct Context<M: Model>(Rc<UnsafeCell<Ctx<M>>>);

unsafe impl<M: Model> Send for Context<M> {}
unsafe impl<M: Model> Sync for Context<M> {}

impl<M: Model> Context<M> {
    pub fn new(request: Request, app: App<M>, peer_addr: SocketAddr) -> Self {
        Ctx::new(request, app, peer_addr).into()
    }
}

impl<M: Model> Clone for Context<M> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<M: Model> Deref for Context<M> {
    type Target = Ctx<M>;
    fn deref(&self) -> &Self::Target {
        unsafe { &*self.0.get() }
    }
}

impl<M: Model> DerefMut for Context<M> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { &mut *self.0.get() }
    }
}

impl<M: Model> Deref for Ctx<M> {
    type Target = M::State;
    fn deref(&self) -> &Self::Target {
        &self.state
    }
}

impl<M: Model> DerefMut for Ctx<M> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.state
    }
}

impl<M: Model> From<Ctx<M>> for Context<M> {
    fn from(ctx: Ctx<M>) -> Self {
        Self(Rc::new(UnsafeCell::new(ctx)))
    }
}

pub struct Ctx<M: Model> {
    pub request: Request,
    pub response: Response,
    pub app: App<M>,
    pub state: M::State,
    pub peer_addr: SocketAddr,
}

impl<M: Model> Ctx<M> {
    fn new(request: Request, app: App<M>, peer_addr: SocketAddr) -> Self {
        let state = app.model.new_state();
        Self {
            request,
            response: Response::new(),
            app,
            state,
            peer_addr,
        }
    }
}

impl Ctx<()> {
    // construct fake Context for test.
    pub fn fake(request: Request) -> Self {
        use std::net::{IpAddr, Ipv4Addr};
        let peer_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
        Self {
            request,
            response: Response::new(),
            app: crate::Middleware::new().app(()),
            state: (),
            peer_addr,
        }
    }
}