ic_auth_protocol_types/
role.rs1use std::{error::Error, fmt, str::FromStr};
4
5#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub struct RoleError;
13
14impl fmt::Display for RoleError {
15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16 f.write_str(
17 "role must contain 1..=64 bytes using only a-z, 0-9, underscore, colon or hyphen",
18 )
19 }
20}
21
22impl Error for RoleError {}
23
24#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
33#[cfg_attr(
34 feature = "stable-records",
35 derive(serde::Serialize, serde::Deserialize)
36)]
37#[cfg_attr(feature = "stable-records", serde(try_from = "String"))]
38pub struct AuthRole(String);
39
40impl AuthRole {
41 pub fn validate(text: &str) -> Result<(), RoleError> {
43 if !(1..=64).contains(&text.len())
44 || !text
45 .bytes()
46 .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_' | b':' | b'-'))
47 {
48 return Err(RoleError);
49 }
50 Ok(())
51 }
52
53 #[must_use]
55 pub fn as_str(&self) -> &str {
56 &self.0
57 }
58}
59
60impl FromStr for AuthRole {
61 type Err = RoleError;
62 fn from_str(text: &str) -> Result<Self, Self::Err> {
63 Self::validate(text)?;
64 Ok(Self(text.to_owned()))
65 }
66}
67
68impl TryFrom<String> for AuthRole {
69 type Error = RoleError;
70 fn try_from(text: String) -> Result<Self, Self::Error> {
71 Self::validate(&text)?;
72 Ok(Self(text))
73 }
74}