cyfs_lib/router_handler/
action.rs

1use cyfs_base::*;
2
3use serde_json::{Map, Value};
4use std::fmt;
5use std::str::FromStr;
6
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub enum RouterHandlerAction {
9    Default,
10    Response,
11
12    Reject,
13    Drop,
14
15    Pass,
16}
17
18impl RouterHandlerAction {
19    pub fn to_error_code(&self) -> BuckyErrorCode {
20        match *self {
21            RouterHandlerAction::Reject => BuckyErrorCode::Reject,
22            RouterHandlerAction::Drop => BuckyErrorCode::Ignored,
23
24            _ => BuckyErrorCode::Ok,
25        }
26    }
27
28    pub fn is_action_error(e: &BuckyError) -> bool {
29        Self::is_action_error_code(&e.code())
30    }
31
32    pub fn is_action_error_code(code: &BuckyErrorCode) -> bool {
33        match code {
34            BuckyErrorCode::Reject | BuckyErrorCode::Ignored => true,
35            _ => false,
36        }
37    }
38}
39
40impl fmt::Display for RouterHandlerAction {
41    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42        let s = match &*self {
43            Self::Default => "Default",
44            Self::Response => "Response",
45
46            Self::Reject => "Reject",
47            Self::Drop => "Drop",
48
49            Self::Pass => "Pass",
50        };
51
52        fmt::Display::fmt(s, f)
53    }
54}
55
56impl FromStr for RouterHandlerAction {
57    type Err = BuckyError;
58    fn from_str(s: &str) -> BuckyResult<Self> {
59        let ret = match s {
60            "Default" => Self::Default,
61            "Response" => Self::Response,
62
63            "Reject" => Self::Reject,
64            "Drop" => Self::Drop,
65
66            "Pass" => Self::Pass,
67            v @ _ => {
68                let msg = format!("unknown router handler action: {}", v);
69                error!("{}", msg);
70
71                return Err(BuckyError::new(BuckyErrorCode::UnSupport, msg));
72            }
73        };
74
75        Ok(ret)
76    }
77}
78
79impl JsonCodec<RouterHandlerAction> for RouterHandlerAction {
80    fn encode_json(&self) -> Map<String, Value> {
81        let mut obj = Map::new();
82        obj.insert("action".to_owned(), Value::String(self.to_string()));
83
84        obj
85    }
86
87    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<Self> {
88        let action = obj.get("action").ok_or_else(|| {
89            error!("action field missed! {:?}", obj);
90            BuckyError::from(BuckyErrorCode::InvalidFormat)
91        })?;
92
93        let action = action.as_str().unwrap_or("");
94        let ret = Self::from_str(action)?;
95
96        Ok(ret)
97    }
98}