Skip to main content

trino_rust_client/
selected_role.rs

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