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)]
24#[cfg_attr(
25 feature = "stable-records",
26 derive(serde::Serialize, serde::Deserialize)
27)]
28#[cfg_attr(feature = "stable-records", serde(try_from = "String"))]
29pub struct AuthRole(String);
30
31impl AuthRole {
32 pub fn validate(text: &str) -> Result<(), RoleError> {
34 if !(1..=64).contains(&text.len())
35 || !text
36 .bytes()
37 .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_' | b':' | b'-'))
38 {
39 return Err(RoleError);
40 }
41 Ok(())
42 }
43
44 #[must_use]
46 pub fn as_str(&self) -> &str {
47 &self.0
48 }
49}
50
51impl FromStr for AuthRole {
52 type Err = RoleError;
53 fn from_str(text: &str) -> Result<Self, Self::Err> {
54 Self::validate(text)?;
55 Ok(Self(text.to_owned()))
56 }
57}
58
59impl TryFrom<String> for AuthRole {
60 type Error = RoleError;
61 fn try_from(text: String) -> Result<Self, Self::Error> {
62 Self::validate(&text)?;
63 Ok(Self(text))
64 }
65}