use std::borrow::Cow;
use std::fmt;
use std::ops::Deref;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum IdError {
Empty,
NoPrefix,
EmptySegment {
at: usize,
},
BadChar {
at: usize,
},
}
impl fmt::Display for IdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
IdError::Empty => f.write_str("the id is empty"),
IdError::NoPrefix => {
f.write_str("the id has no `<crate>.` prefix (`<crate>.<subject>.<moment>`)")
}
IdError::EmptySegment { at } => write!(f, "the id has an empty segment at byte {at}"),
IdError::BadChar { at } => write!(
f,
"the id has a character not allowed at byte {at}: the prefix is `[a-z][a-z0-9_-]*`, the other segments `[A-Za-z0-9_-]+`"
),
}
}
}
impl std::error::Error for IdError {}
pub const fn check_id(id: &str) -> Result<(), IdError> {
let b = id.as_bytes();
if b.is_empty() {
return Err(IdError::Empty);
}
let mut i = 0;
let mut start = 0;
let mut segments = 1;
while i < b.len() {
let c = b[i];
if c == b'.' {
if i == start {
return Err(IdError::EmptySegment { at: i });
}
segments += 1;
start = i + 1;
} else if segments == 1 {
let ok =
c.is_ascii_lowercase() || (i > 0 && (c.is_ascii_digit() || c == b'_' || c == b'-'));
if !ok {
return Err(IdError::BadChar { at: i });
}
} else if !(c.is_ascii_alphanumeric() || c == b'_' || c == b'-') {
return Err(IdError::BadChar { at: i });
}
i += 1;
}
if segments < 2 {
return Err(IdError::NoPrefix);
}
if start == b.len() {
return Err(IdError::EmptySegment { at: b.len() });
}
Ok(())
}
const fn refuse(error: IdError) -> ! {
match error {
IdError::Empty => panic!("invalid bus id: the id is empty"),
IdError::NoPrefix => {
panic!("invalid bus id: no `<crate>.` prefix (`<crate>.<subject>.<moment>`)")
}
IdError::EmptySegment { .. } => panic!("invalid bus id: an empty segment"),
IdError::BadChar { .. } => panic!(
"invalid bus id: a character not allowed (prefix `[a-z][a-z0-9_-]*`, then `[A-Za-z0-9_-]+`)"
),
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PointId(&'static str);
impl PointId {
pub const fn new(id: &'static str) -> PointId {
match check_id(id) {
Ok(()) => PointId(id),
Err(e) => refuse(e),
}
}
pub const fn try_new(id: &'static str) -> Result<PointId, IdError> {
match check_id(id) {
Ok(()) => Ok(PointId(id)),
Err(e) => Err(e),
}
}
pub const fn as_str(&self) -> &'static str {
self.0
}
}
impl Deref for PointId {
type Target = str;
fn deref(&self) -> &str {
self.0
}
}
impl AsRef<str> for PointId {
fn as_ref(&self) -> &str {
self.0
}
}
impl fmt::Display for PointId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.0)
}
}
impl fmt::Debug for PointId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.0, f)
}
}
impl TryFrom<&'static str> for PointId {
type Error = IdError;
fn try_from(id: &'static str) -> Result<PointId, IdError> {
PointId::try_new(id)
}
}
impl From<PointId> for &'static str {
fn from(id: PointId) -> &'static str {
id.0
}
}
impl From<PointId> for String {
fn from(id: PointId) -> String {
id.0.to_owned()
}
}
impl PartialEq<str> for PointId {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for PointId {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
impl PartialEq<PointId> for str {
fn eq(&self, other: &PointId) -> bool {
self == other.0
}
}
impl PartialEq<PointId> for &str {
fn eq(&self, other: &PointId) -> bool {
*self == other.0
}
}
impl PartialEq<PointId> for String {
fn eq(&self, other: &PointId) -> bool {
self == other.0
}
}
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ListenerId(Cow<'static, str>);
impl ListenerId {
pub const fn new(id: &'static str) -> ListenerId {
match check_id(id) {
Ok(()) => ListenerId(Cow::Borrowed(id)),
Err(e) => refuse(e),
}
}
pub fn try_new(id: impl Into<String>) -> Result<ListenerId, IdError> {
let id = id.into();
check_id(&id)?;
Ok(ListenerId(Cow::Owned(id)))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Deref for ListenerId {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl AsRef<str> for ListenerId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for ListenerId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl fmt::Debug for ListenerId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&*self.0, f)
}
}
impl TryFrom<&str> for ListenerId {
type Error = IdError;
fn try_from(id: &str) -> Result<ListenerId, IdError> {
ListenerId::try_new(id)
}
}
impl TryFrom<String> for ListenerId {
type Error = IdError;
fn try_from(id: String) -> Result<ListenerId, IdError> {
ListenerId::try_new(id)
}
}
impl From<ListenerId> for String {
fn from(id: ListenerId) -> String {
id.0.into_owned()
}
}
impl From<&ListenerId> for String {
fn from(id: &ListenerId) -> String {
id.0.clone().into_owned()
}
}
impl PartialEq<str> for ListenerId {
fn eq(&self, other: &str) -> bool {
*self.0 == *other
}
}
impl PartialEq<&str> for ListenerId {
fn eq(&self, other: &&str) -> bool {
*self.0 == **other
}
}
impl PartialEq<ListenerId> for str {
fn eq(&self, other: &ListenerId) -> bool {
*self == *other.0
}
}
impl PartialEq<ListenerId> for String {
fn eq(&self, other: &ListenerId) -> bool {
**self == *other.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_naming_rule() {
for ok in [
"doc.close",
"stack.layout.changed",
"bus.overBudget",
"egui_pop.a-b.c_d9",
"a1.x",
] {
assert_eq!(check_id(ok), Ok(()), "{ok}");
}
assert_eq!(check_id(""), Err(IdError::Empty));
assert_eq!(check_id("close"), Err(IdError::NoPrefix));
assert_eq!(check_id("a..b"), Err(IdError::EmptySegment { at: 2 }));
assert_eq!(check_id(".a"), Err(IdError::EmptySegment { at: 0 }));
assert_eq!(check_id("a."), Err(IdError::EmptySegment { at: 2 }));
assert_eq!(check_id("Doc.close"), Err(IdError::BadChar { at: 0 }));
assert_eq!(check_id("1doc.close"), Err(IdError::BadChar { at: 0 }));
assert_eq!(check_id("doc.cl ose"), Err(IdError::BadChar { at: 6 }));
assert_eq!(check_id("doc.*"), Err(IdError::BadChar { at: 4 }));
assert_eq!(check_id("doc.é"), Err(IdError::BadChar { at: 4 }));
}
#[test]
fn newtypes_read_as_str() {
const P: PointId = PointId::new("doc.close");
assert_eq!(P, "doc.close");
assert_eq!(&*P, "doc.close");
assert_eq!(P.to_string(), "doc.close");
assert!(PointId::try_new("close").is_err());
let l = ListenerId::try_new("doc.save").unwrap();
assert_eq!(String::from(l.clone()), "doc.save");
assert_eq!(l, "doc.save");
}
#[test]
#[should_panic(expected = "invalid bus id")]
fn new_panics_at_run_time() {
let id = String::from("x");
let _ = ListenerId::new(Box::leak(id.into_boxed_str()));
}
}