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)]
14pub enum ScopeLabelError {
15 Empty,
17 TooLong {
19 bytes: usize,
21 max: usize,
23 },
24 EmptySegment,
26 InvalidSegmentStart {
28 offset: usize,
30 },
31 InvalidByte {
33 offset: usize,
35 },
36}
37
38impl fmt::Display for ScopeLabelError {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 match self {
41 Self::Empty => f.write_str("scope is empty"),
42 Self::TooLong { bytes, max } => write!(f, "scope has {bytes} bytes; maximum is {max}"),
43 Self::EmptySegment => f.write_str("scope contains an empty segment"),
44 Self::InvalidSegmentStart { offset } => {
45 write!(f, "invalid scope segment start at byte {offset}")
46 }
47 Self::InvalidByte { offset } => write!(f, "invalid scope byte at offset {offset}"),
48 }
49 }
50}
51
52impl Error for ScopeLabelError {}
53
54#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
67#[cfg_attr(
68 feature = "stable-records",
69 derive(serde::Serialize, serde::Deserialize)
70)]
71#[cfg_attr(feature = "stable-records", serde(try_from = "String"))]
72pub struct ScopeLabel(String);
73
74impl ScopeLabel {
75 pub fn validate(text: &str) -> Result<(), ScopeLabelError> {
80 if text.is_empty() {
81 return Err(ScopeLabelError::Empty);
82 }
83 if text.len() > MAX_BYTES {
84 return Err(ScopeLabelError::TooLong {
85 bytes: text.len(),
86 max: MAX_BYTES,
87 });
88 }
89 let mut offset = 0;
90 for segment in text.split(':') {
91 let mut bytes = segment.bytes();
92 let first = bytes.next().ok_or(ScopeLabelError::EmptySegment)?;
93 if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
94 return Err(ScopeLabelError::InvalidSegmentStart { offset });
95 }
96 for (index, byte) in bytes.enumerate() {
97 if !byte.is_ascii_lowercase()
98 && !byte.is_ascii_digit()
99 && !matches!(byte, b'_' | b'-')
100 {
101 return Err(ScopeLabelError::InvalidByte {
102 offset: offset + index + 1,
103 });
104 }
105 }
106 offset += segment.len() + 1;
107 }
108 Ok(())
109 }
110
111 #[must_use]
113 pub fn as_str(&self) -> &str {
114 &self.0
115 }
116
117 #[must_use]
119 pub fn into_string(self) -> String {
120 self.0
121 }
122}
123
124impl TryFrom<String> for ScopeLabel {
125 type Error = ScopeLabelError;
126
127 fn try_from(text: String) -> Result<Self, Self::Error> {
128 Self::validate(&text)?;
129 Ok(Self(text))
130 }
131}
132
133impl FromStr for ScopeLabel {
134 type Err = ScopeLabelError;
135
136 fn from_str(text: &str) -> Result<Self, Self::Err> {
137 Self::validate(text)?;
138 Ok(Self(text.to_owned()))
139 }
140}
141
142impl AsRef<str> for ScopeLabel {
143 fn as_ref(&self) -> &str {
144 self.as_str()
145 }
146}
147
148impl fmt::Display for ScopeLabel {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.write_str(self.as_str())
151 }
152}