ic_auth_protocol_types/
role.rs1use std::{error::Error, fmt, str::FromStr};
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
7pub struct RoleError;
8
9impl fmt::Display for RoleError {
10 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11 f.write_str(
12 "role must contain 1..=64 bytes using only a-z, 0-9, underscore, colon or hyphen",
13 )
14 }
15}
16
17impl Error for RoleError {}
18
19#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
24pub struct AuthRole(String);
25
26impl AuthRole {
27 pub fn validate(text: &str) -> Result<(), RoleError> {
29 if !(1..=64).contains(&text.len())
30 || !text
31 .bytes()
32 .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_' | b':' | b'-'))
33 {
34 return Err(RoleError);
35 }
36 Ok(())
37 }
38
39 #[must_use]
41 pub fn as_str(&self) -> &str {
42 &self.0
43 }
44}
45
46impl FromStr for AuthRole {
47 type Err = RoleError;
48 fn from_str(text: &str) -> Result<Self, Self::Err> {
49 Self::validate(text)?;
50 Ok(Self(text.to_owned()))
51 }
52}
53
54impl TryFrom<String> for AuthRole {
55 type Error = RoleError;
56 fn try_from(text: String) -> Result<Self, Self::Error> {
57 Self::validate(&text)?;
58 Ok(Self(text))
59 }
60}