ic_auth_protocol_types/
scope.rs1use std::{error::Error, fmt, str::FromStr};
4
5const MAX_BYTES: usize = 64;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ScopeLabelError {
10 Empty,
12 TooLong {
14 bytes: usize,
16 max: usize,
18 },
19 EmptySegment,
21 InvalidSegmentStart {
23 offset: usize,
25 },
26 InvalidByte {
28 offset: usize,
30 },
31}
32
33impl fmt::Display for ScopeLabelError {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 match self {
36 Self::Empty => f.write_str("scope is empty"),
37 Self::TooLong { bytes, max } => write!(f, "scope has {bytes} bytes; maximum is {max}"),
38 Self::EmptySegment => f.write_str("scope contains an empty segment"),
39 Self::InvalidSegmentStart { offset } => {
40 write!(f, "invalid scope segment start at byte {offset}")
41 }
42 Self::InvalidByte { offset } => write!(f, "invalid scope byte at offset {offset}"),
43 }
44 }
45}
46
47impl Error for ScopeLabelError {}
48
49#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
59pub struct ScopeLabel(String);
60
61impl ScopeLabel {
62 pub fn validate(text: &str) -> Result<(), ScopeLabelError> {
67 if text.is_empty() {
68 return Err(ScopeLabelError::Empty);
69 }
70 if text.len() > MAX_BYTES {
71 return Err(ScopeLabelError::TooLong {
72 bytes: text.len(),
73 max: MAX_BYTES,
74 });
75 }
76 let mut offset = 0;
77 for segment in text.split(':') {
78 let mut bytes = segment.bytes();
79 let first = bytes.next().ok_or(ScopeLabelError::EmptySegment)?;
80 if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
81 return Err(ScopeLabelError::InvalidSegmentStart { offset });
82 }
83 for (index, byte) in bytes.enumerate() {
84 if !byte.is_ascii_lowercase()
85 && !byte.is_ascii_digit()
86 && !matches!(byte, b'_' | b'-')
87 {
88 return Err(ScopeLabelError::InvalidByte {
89 offset: offset + index + 1,
90 });
91 }
92 }
93 offset += segment.len() + 1;
94 }
95 Ok(())
96 }
97
98 #[must_use]
100 pub fn as_str(&self) -> &str {
101 &self.0
102 }
103
104 #[must_use]
106 pub fn into_string(self) -> String {
107 self.0
108 }
109}
110
111impl TryFrom<String> for ScopeLabel {
112 type Error = ScopeLabelError;
113
114 fn try_from(text: String) -> Result<Self, Self::Error> {
115 Self::validate(&text)?;
116 Ok(Self(text))
117 }
118}
119
120impl FromStr for ScopeLabel {
121 type Err = ScopeLabelError;
122
123 fn from_str(text: &str) -> Result<Self, Self::Err> {
124 Self::validate(text)?;
125 Ok(Self(text.to_owned()))
126 }
127}
128
129impl AsRef<str> for ScopeLabel {
130 fn as_ref(&self) -> &str {
131 self.as_str()
132 }
133}
134
135impl fmt::Display for ScopeLabel {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 f.write_str(self.as_str())
138 }
139}