prusto_rs/
selected_role.rs

1use lazy_static::lazy_static;
2use regex::Regex;
3
4#[derive(Debug, PartialEq)]
5pub enum RoleType {
6    Role,
7    All,
8    None,
9}
10
11#[derive(Debug, PartialEq)]
12pub struct SelectedRole {
13    pub ty: RoleType,
14    pub role: Option<String>,
15}
16
17lazy_static! {
18    static ref PATTERN: Regex = Regex::new(r"^(ROLE|ALL|NONE)(\{(.*)\})?$").unwrap();
19}
20
21impl SelectedRole {
22    pub fn new(ty: RoleType, role: Option<String>) -> Self {
23        SelectedRole { ty, role }
24    }
25
26    pub fn from_str(s: &str) -> Option<Self> {
27        let cap = PATTERN.captures(s)?;
28        let ty = match cap.get(1).unwrap().as_str() {
29            "ROLE" => RoleType::Role,
30            "ALL" => RoleType::All,
31            "NONE" => RoleType::None,
32            _ => unreachable!(),
33        };
34        let role = cap.get(3).map(|m| m.as_str().to_string());
35        Some(Self::new(ty, role))
36    }
37}
38
39impl ToString for RoleType {
40    fn to_string(&self) -> String {
41        use RoleType::*;
42        match self {
43            Role => "ROLE".to_string(),
44            All => "ALL".to_string(),
45            None => "NONE".to_string(),
46        }
47    }
48}
49
50impl ToString for SelectedRole {
51    fn to_string(&self) -> String {
52        let ty = self.ty.to_string();
53        if let Some(role) = &self.role {
54            format!("{}{{{}}}", ty, role)
55        } else {
56            ty
57        }
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_to_string() {
67        let a = SelectedRole::new(RoleType::All, None);
68        let res = a.to_string();
69        assert_eq!(res, "ALL");
70
71        let a = SelectedRole::new(RoleType::Role, Some("admin".to_string()));
72        let res = a.to_string();
73        assert_eq!(res, "ROLE{admin}");
74    }
75
76    #[test]
77    fn test_from_str() {
78        let a = "ALL";
79        let res = SelectedRole::from_str(a).unwrap();
80        assert_eq!(res.ty, RoleType::All);
81        assert_eq!(res.role, None);
82
83        let a = "ROLE{admin}";
84        let res = SelectedRole::from_str(a).unwrap();
85        assert_eq!(res.ty, RoleType::Role);
86        assert_eq!(res.role, Some("admin".to_string()));
87    }
88}