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 std::fmt::{Display, Formatter};
use std::str::FromStr;

use rusqlite::types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef};
use rusqlite::ToSql;

use crate::FirewallError;

/// Direction of a firewall rule.
///
/// Each firewall rule is associated to a given direction.
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum FirewallDirection {
    /// Refers to incoming network traffic.
    IN,
    /// Refers to outgoing network traffic.
    OUT,
}

impl FromStr for FirewallDirection {
    type Err = FirewallError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "IN" => Ok(Self::IN),
            "OUT" => Ok(Self::OUT),
            x => Err(FirewallError::InvalidDirection(x.to_owned())),
        }
    }
}

impl Display for FirewallDirection {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl ToSql for FirewallDirection {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        Ok(self.to_string().into())
    }
}

impl FromSql for FirewallDirection {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        FromSqlResult::Ok(FirewallDirection::from_str(value.as_str().unwrap()).unwrap())
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use rusqlite::types::ToSqlOutput;
    use rusqlite::types::Value::Text;
    use rusqlite::ToSql;

    use crate::{FirewallDirection, FirewallError};

    #[test]
    fn test_firewall_directions_from_str() {
        assert_eq!(FirewallDirection::from_str("IN"), Ok(FirewallDirection::IN));
        assert_eq!(
            FirewallDirection::from_str("OUT"),
            Ok(FirewallDirection::OUT)
        );

        let err = FirewallDirection::from_str("UNDER").unwrap_err();
        assert_eq!(err, FirewallError::InvalidDirection("UNDER".to_owned()));
        assert_eq!(
            err.to_string(),
            "Firewall error - incorrect direction 'UNDER'"
        );
    }

    #[test]
    fn test_firewall_direction_to_sql() {
        assert_eq!(
            FirewallDirection::to_sql(&FirewallDirection::IN),
            Ok(ToSqlOutput::Owned(Text("IN".to_string())))
        );

        assert_eq!(
            FirewallDirection::to_sql(&FirewallDirection::OUT),
            Ok(ToSqlOutput::Owned(Text("OUT".to_string())))
        );
    }
}