pub const fn is_safe_identifier(s: &str) -> bool {
let bytes = s.as_bytes();
let [first, rest @ ..] = bytes else {
return false;
};
if !first.is_ascii_alphabetic() {
return false;
}
let mut i = 0;
while i < rest.len() {
let b = rest[i];
if !(b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
return false;
}
i += 1;
}
true
}
#[must_use]
#[repr(transparent)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IdentifierStr(str);
impl IdentifierStr {
pub const fn from_constant(val: &'static str) -> &'static IdentifierStr {
assert!(
is_safe_identifier(val),
"IdentifierStr::from_constant requires [A-Za-z][A-Za-z0-9_-]*"
);
unsafe { IdentifierStr::from_str_unchecked(val) }
}
pub fn try_from_str(value: &str) -> Option<&IdentifierStr> {
if is_safe_identifier(value) {
Some(unsafe { IdentifierStr::from_str_unchecked(value) })
} else {
None
}
}
pub const unsafe fn from_str_unchecked(val: &str) -> &IdentifierStr {
unsafe { &*(val as *const str as *const IdentifierStr) }
}
pub const fn as_str(&self) -> &str {
&self.0
}
}
impl core::ops::Deref for IdentifierStr {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl AsRef<str> for IdentifierStr {
fn as_ref(&self) -> &str {
&self.0
}
}
impl core::fmt::Display for IdentifierStr {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.0)
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl core::borrow::Borrow<IdentifierStr> for crate::types::Identifier {
fn borrow(&self) -> &IdentifierStr {
self
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl alloc::borrow::ToOwned for IdentifierStr {
type Owned = crate::types::Identifier;
fn to_owned(&self) -> crate::types::Identifier {
unsafe {
crate::types::Identifier::from_string_unchecked(alloc::string::String::from(&self.0))
}
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl From<&IdentifierStr> for crate::types::Identifier {
fn from(value: &IdentifierStr) -> Self {
alloc::borrow::ToOwned::to_owned(value)
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl PartialEq<IdentifierStr> for crate::types::Identifier {
fn eq(&self, other: &IdentifierStr) -> bool {
self.as_str() == other.as_str()
}
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl PartialEq<crate::types::Identifier> for &IdentifierStr {
fn eq(&self, other: &crate::types::Identifier) -> bool {
self.as_str() == other.as_str()
}
}