use std::{fmt, str::FromStr}; use thiserror::Error; const MAX_ID_LENGTH: usize = 64; /// Why a stable user-defined identifier was rejected. #[derive(Clone, Debug, Error, Eq, PartialEq)] pub enum IdError { /// The identifier was empty. #[error("identifier must not be empty")] Empty, /// The identifier exceeded the stable storage limit. #[error("identifier length {actual} exceeds the maximum {maximum}")] TooLong { /// Actual byte length. actual: usize, /// Maximum allowed byte length. maximum: usize, }, /// The first character was not ASCII alphanumeric. #[error("identifier must start with an ASCII letter or digit, found {found:?}")] InvalidStart { /// Invalid first character. found: char, }, /// A later character was outside the durable identifier alphabet. #[error("identifier contains invalid character {found:?} at position {position}")] InvalidCharacter { /// Zero-based character position. position: usize, /// Invalid character. found: char, }, } fn validate(value: &str) -> Result<(), IdError> { if value.is_empty() { return Err(IdError::Empty); } if value.len() > MAX_ID_LENGTH { return Err(IdError::TooLong { actual: value.len(), maximum: MAX_ID_LENGTH, }); } let mut characters = value.chars(); let Some(first) = characters.next() else { return Err(IdError::Empty); }; if !first.is_ascii_alphanumeric() { return Err(IdError::InvalidStart { found: first }); } for (offset, character) in characters.enumerate() { if !(character.is_ascii_alphanumeric() || matches!(character, '-' | '_')) { return Err(IdError::InvalidCharacter { position: offset + 1, found: character, }); } } Ok(()) } macro_rules! stable_id { ($name:ident, $description:literal) => { #[doc = $description] #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct $name(String); impl $name { /// Validates and constructs an identifier. /// /// # Errors /// /// Returns [`IdError`] when `value` is empty, too long, or outside /// the portable `[A-Za-z0-9_-]` identifier alphabet. pub fn new(value: impl Into) -> Result { let value = value.into(); validate(&value)?; Ok(Self(value)) } /// Returns the persisted string representation. #[must_use] pub fn as_str(&self) -> &str { &self.0 } } impl fmt::Display for $name { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(&self.0) } } impl FromStr for $name { type Err = IdError; fn from_str(value: &str) -> Result { Self::new(value) } } }; } stable_id!( ApplicationId, "Stable identifier for a virtual application." ); stable_id!(FaderId, "Stable identifier for a logical fader."); stable_id!(GroupId, "Stable identifier for an application group."); stable_id!(ProfileId, "Stable identifier for a configuration profile."); stable_id!(SurfaceId, "Stable identifier for a physical MIDI surface."); #[cfg(test)] mod tests { use std::any::TypeId; use super::*; #[test] fn accepts_portable_stable_ids() { let id = ApplicationId::new("music-player_2").expect("valid application ID"); assert_eq!(id.as_str(), "music-player_2"); assert_eq!(id.to_string(), "music-player_2"); } #[test] fn rejects_invalid_ids_with_a_precise_reason() { assert_eq!(GroupId::new(""), Err(IdError::Empty)); assert_eq!( GroupId::new("-group"), Err(IdError::InvalidStart { found: '-' }) ); assert_eq!( GroupId::new("group/name"), Err(IdError::InvalidCharacter { position: 5, found: '/', }) ); assert!(matches!( GroupId::new("a".repeat(MAX_ID_LENGTH + 1)), Err(IdError::TooLong { .. }) )); } #[test] fn stable_id_types_cannot_be_interchanged() { assert_ne!(TypeId::of::(), TypeId::of::()); assert_ne!(TypeId::of::(), TypeId::of::()); assert_ne!(TypeId::of::(), TypeId::of::()); } }