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
use ::job::Job;
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::marker::Sync;


#[derive(Debug)]
pub struct JobHandlerError(pub Box<Error + Send>);

impl Error for JobHandlerError {
    fn description(&self) -> &str {
        &self.0.description()
    }
}

impl Display for JobHandlerError {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        write!(fmt, "{:?}", self)
    }
}



pub trait JobHandlerFactory {
    fn produce(&mut self) -> Box<JobHandler>;
}

pub trait JobHandler: Send {
    fn handle(&mut self, job: &Job) -> Result<(), JobHandlerError>;
}


pub struct PrinterHandlerFactory;

impl JobHandlerFactory for PrinterHandlerFactory {
    fn produce(&mut self) -> Box<JobHandler> {
        Box::new(PrinterHandler)
    }
}

pub struct PrinterHandler;

unsafe impl Sync for PrinterHandler {}

impl JobHandler for PrinterHandler {
    fn handle(&mut self, job: &Job) -> Result<(), JobHandlerError> {
        info!("handling {:?}", job);
        Ok(())
    }
}


pub struct ErrorHandlerFactory;

impl JobHandlerFactory for ErrorHandlerFactory {
    fn produce(&mut self) -> Box<JobHandler> {
        Box::new(ErrorHandler)
    }
}

pub struct ErrorHandler;

unsafe impl Sync for ErrorHandler {}

impl JobHandler for ErrorHandler {
    fn handle(&mut self, _: &Job) -> Result<(), JobHandlerError> {
        Err(JobHandlerError(Box::new("a".parse::<i8>().unwrap_err())))
    }
}


pub struct PanicHandlerFactory;

impl JobHandlerFactory for PanicHandlerFactory {
    fn produce(&mut self) -> Box<JobHandler> {
        Box::new(PanicHandler)
    }
}

pub struct PanicHandler;

unsafe impl Sync for PanicHandler {}

impl JobHandler for PanicHandler {
    fn handle(&mut self, _: &Job) -> Result<(), JobHandlerError> {
        panic!("yeah, I do it deliberately")
    }
}