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
//! Labor traits.

/// A result returned by a "loafer".
#[derive(Debug, Clone, Copy)]
pub enum LoafingResult {
    /// The caller can block on receiving data, since the loafer has done all it needed.
    ImDone,

    /// A hint to call the loafer again.
    TouchMeAgain,
}

/// The one that does the hard job.
pub trait Proletarian<Request, Response> {
    /// Processes a request.
    fn process_request(&mut self, request: Request) -> Response;

    /// Loafs a bit, e.g. when there are no incoming requests.
    fn loaf(&mut self) -> LoafingResult {
        LoafingResult::ImDone
    }
}

/// A `Proletarian` fabric.
pub trait Socium<Request, Response> {
    /// The one that does the hard job.
    type Proletarian: Proletarian<Request, Response>;

    /// Constructs an instance of a `Proletarian`.
    fn construct_proletarian(&self, channel_id: usize) -> Self::Proletarian;
}

impl<F: FnMut(Req) -> Resp, Req, Resp> Proletarian<Req, Resp> for F {
    fn process_request(&mut self, request: Req) -> Resp {
        (self)(request)
    }
}

impl<F, P, Req, Resp> Socium<Req, Resp> for F
where
    F: Fn(usize) -> P,
    P: Proletarian<Req, Resp>,
{
    type Proletarian = P;

    fn construct_proletarian(&self, channel_id: usize) -> Self::Proletarian {
        (self)(channel_id)
    }
}