use std::{error::Error, fmt, str::FromStr};
const MAX_BYTES: usize = 64;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScopeLabelError {
Empty,
TooLong {
bytes: usize,
max: usize,
},
EmptySegment,
InvalidSegmentStart {
offset: usize,
},
InvalidByte {
offset: usize,
},
}
impl fmt::Display for ScopeLabelError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => f.write_str("scope is empty"),
Self::TooLong { bytes, max } => write!(f, "scope has {bytes} bytes; maximum is {max}"),
Self::EmptySegment => f.write_str("scope contains an empty segment"),
Self::InvalidSegmentStart { offset } => {
write!(f, "invalid scope segment start at byte {offset}")
}
Self::InvalidByte { offset } => write!(f, "invalid scope byte at offset {offset}"),
}
}
}
impl Error for ScopeLabelError {}
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(
feature = "stable-records",
derive(serde::Serialize, serde::Deserialize)
)]
#[cfg_attr(feature = "stable-records", serde(try_from = "String"))]
pub struct ScopeLabel(String);
impl ScopeLabel {
pub fn validate(text: &str) -> Result<(), ScopeLabelError> {
if text.is_empty() {
return Err(ScopeLabelError::Empty);
}
if text.len() > MAX_BYTES {
return Err(ScopeLabelError::TooLong {
bytes: text.len(),
max: MAX_BYTES,
});
}
let mut at_segment_start = true;
for (offset, byte) in text.bytes().enumerate() {
match byte {
b'a'..=b'z' | b'0'..=b'9' => at_segment_start = false,
b':' if at_segment_start => return Err(ScopeLabelError::EmptySegment),
b':' => at_segment_start = true,
_ if at_segment_start => {
return Err(ScopeLabelError::InvalidSegmentStart { offset });
}
b'_' | b'-' => {}
_ => return Err(ScopeLabelError::InvalidByte { offset }),
}
}
if at_segment_start {
return Err(ScopeLabelError::EmptySegment);
}
Ok(())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl TryFrom<String> for ScopeLabel {
type Error = ScopeLabelError;
fn try_from(text: String) -> Result<Self, Self::Error> {
Self::validate(&text)?;
Ok(Self(text))
}
}
impl FromStr for ScopeLabel {
type Err = ScopeLabelError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::validate(text)?;
Ok(Self(text.to_owned()))
}
}
impl AsRef<str> for ScopeLabel {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for ScopeLabel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}