use core::convert::TryFrom;
use crate::names::chars;
use crate::names::error::{NameError, TargetNameType};
use crate::names::{Ncname, Nmtoken, Qname};
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Name(str);
#[allow(clippy::len_without_is_empty)]
impl Name {
#[allow(clippy::should_implement_trait)]
#[inline]
pub fn from_str(s: &str) -> Result<&Self, NameError> {
<&Self>::try_from(s)
}
#[inline]
#[must_use]
pub unsafe fn new_unchecked(s: &str) -> &Self {
&*(s as *const str as *const Self)
}
fn validate(s: &str) -> Result<(), NameError> {
let mut chars = s.char_indices();
if !chars.next().map_or(false, |(_, c)| chars::is_name_start(c)) {
return Err(NameError::new(TargetNameType::Name, 0));
}
if let Some((i, _)) = chars.find(|(_, c)| !chars::is_name_continue(*c)) {
return Err(NameError::new(TargetNameType::Name, i));
}
Ok(())
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
pub fn parse_next(s: &str) -> Result<(&Self, &str), NameError> {
match Self::from_str(s) {
Ok(v) => Ok((v, &s[s.len()..])),
Err(e) if e.valid_up_to() == 0 => Err(e),
Err(e) => {
let valid_up_to = e.valid_up_to();
let v = unsafe {
let valid = &s[..valid_up_to];
debug_assert!(Self::validate(valid).is_ok());
Self::new_unchecked(valid)
};
Ok((v, &s[valid_up_to..]))
}
}
}
#[cfg(feature = "alloc")]
pub fn into_boxed_str(self: alloc::boxed::Box<Self>) -> Box<str> {
unsafe {
alloc::boxed::Box::<str>::from_raw(alloc::boxed::Box::<Self>::into_raw(self) as *mut str)
}
}
}
impl_traits_for_custom_string_slice!(Name);
impl AsRef<Nmtoken> for Name {
#[inline]
fn as_ref(&self) -> &Nmtoken {
unsafe {
debug_assert!(
Nmtoken::from_str(self.as_str()).is_ok(),
"Name {:?} must be a valid Nmtoken",
self.as_str()
);
Nmtoken::new_unchecked(self.as_str())
}
}
}
impl<'a> From<&'a Ncname> for &'a Name {
#[inline]
fn from(s: &'a Ncname) -> Self {
s.as_ref()
}
}
impl<'a> From<&'a Qname> for &'a Name {
#[inline]
fn from(s: &'a Qname) -> Self {
s.as_ref()
}
}
impl<'a> TryFrom<&'a str> for &'a Name {
type Error = NameError;
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
Name::validate(s)?;
Ok(unsafe {
Name::new_unchecked(s)
})
}
}
impl<'a> TryFrom<&'a Nmtoken> for &'a Name {
type Error = NameError;
fn try_from(s: &'a Nmtoken) -> Result<Self, Self::Error> {
let first = s
.as_str()
.chars()
.next()
.expect("Should never fail: Nmtoken is not empty");
if !chars::is_name_start(first) {
return Err(NameError::new(TargetNameType::Name, 0));
}
Ok(unsafe {
debug_assert!(Name::validate(s.as_str()).is_ok());
Name::new_unchecked(s.as_str())
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ensure_eq(s: &str) {
assert_eq!(
Name::from_str(s).expect("Should not fail"),
s,
"String: {:?}",
s
);
}
fn ensure_error_at(s: &str, valid_up_to: usize) {
let err = Name::from_str(s).expect_err("Should fail");
assert_eq!(err.valid_up_to(), valid_up_to, "String: {:?}", s);
}
#[test]
fn name_str_valid() {
ensure_eq("hello");
ensure_eq("abc123");
ensure_eq("foo:bar");
ensure_eq(":foo");
ensure_eq("foo:");
}
#[test]
fn name_str_invalid() {
ensure_error_at("", 0);
ensure_error_at("-foo", 0);
ensure_error_at("0foo", 0);
ensure_error_at("foo bar", 3);
ensure_error_at("foo/bar", 3);
}
}