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 at_segment_start = true;
90 for (offset, byte) in text.bytes().enumerate() {
91 match byte {
92 b'a'..=b'z' | b'0'..=b'9' => at_segment_start = false,
93 b':' if at_segment_start => return Err(ScopeLabelError::EmptySegment),
94 b':' => at_segment_start = true,
95 _ if at_segment_start => {
96 return Err(ScopeLabelError::InvalidSegmentStart { offset });
97 }
98 b'_' | b'-' => {}
99 _ => return Err(ScopeLabelError::InvalidByte { offset }),
100 }
101 }
102 if at_segment_start {
103 return Err(ScopeLabelError::EmptySegment);
104 }
105 Ok(())
106 }
107
108 #[must_use]
110 pub fn as_str(&self) -> &str {
111 &self.0
112 }
113
114 #[must_use]
116 pub fn into_string(self) -> String {
117 self.0
118 }
119}
120
121impl TryFrom<String> for ScopeLabel {
122 type Error = ScopeLabelError;
123
124 fn try_from(text: String) -> Result<Self, Self::Error> {
125 Self::validate(&text)?;
126 Ok(Self(text))
127 }
128}
129
130impl FromStr for ScopeLabel {
131 type Err = ScopeLabelError;
132
133 fn from_str(text: &str) -> Result<Self, Self::Err> {
134 Self::validate(text)?;
135 Ok(Self(text.to_owned()))
136 }
137}
138
139impl AsRef<str> for ScopeLabel {
140 fn as_ref(&self) -> &str {
141 self.as_str()
142 }
143}
144
145impl fmt::Display for ScopeLabel {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.write_str(self.as_str())
148 }
149}