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)]
59#[cfg_attr(
60 feature = "stable-records",
61 derive(serde::Serialize, serde::Deserialize)
62)]
63#[cfg_attr(feature = "stable-records", serde(try_from = "String"))]
64pub struct ScopeLabel(String);
65
66impl ScopeLabel {
67 pub fn validate(text: &str) -> Result<(), ScopeLabelError> {
72 if text.is_empty() {
73 return Err(ScopeLabelError::Empty);
74 }
75 if text.len() > MAX_BYTES {
76 return Err(ScopeLabelError::TooLong {
77 bytes: text.len(),
78 max: MAX_BYTES,
79 });
80 }
81 let mut offset = 0;
82 for segment in text.split(':') {
83 let mut bytes = segment.bytes();
84 let first = bytes.next().ok_or(ScopeLabelError::EmptySegment)?;
85 if !first.is_ascii_lowercase() && !first.is_ascii_digit() {
86 return Err(ScopeLabelError::InvalidSegmentStart { offset });
87 }
88 for (index, byte) in bytes.enumerate() {
89 if !byte.is_ascii_lowercase()
90 && !byte.is_ascii_digit()
91 && !matches!(byte, b'_' | b'-')
92 {
93 return Err(ScopeLabelError::InvalidByte {
94 offset: offset + index + 1,
95 });
96 }
97 }
98 offset += segment.len() + 1;
99 }
100 Ok(())
101 }
102
103 #[must_use]
105 pub fn as_str(&self) -> &str {
106 &self.0
107 }
108
109 #[must_use]
111 pub fn into_string(self) -> String {
112 self.0
113 }
114}
115
116impl TryFrom<String> for ScopeLabel {
117 type Error = ScopeLabelError;
118
119 fn try_from(text: String) -> Result<Self, Self::Error> {
120 Self::validate(&text)?;
121 Ok(Self(text))
122 }
123}
124
125impl FromStr for ScopeLabel {
126 type Err = ScopeLabelError;
127
128 fn from_str(text: &str) -> Result<Self, Self::Err> {
129 Self::validate(text)?;
130 Ok(Self(text.to_owned()))
131 }
132}
133
134impl AsRef<str> for ScopeLabel {
135 fn as_ref(&self) -> &str {
136 self.as_str()
137 }
138}
139
140impl fmt::Display for ScopeLabel {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 f.write_str(self.as_str())
143 }
144}