1use bstr::{BStr, BString, ByteSlice};
2use kstring::KStringRef;
3
4use crate::{Name, NameRef};
5
6impl NameRef<'_> {
7 pub fn to_owned(self) -> Name {
9 Name(self.0.into())
10 }
11
12 pub fn as_str(&self) -> &str {
14 self.0.as_str()
15 }
16}
17
18impl AsRef<str> for NameRef<'_> {
19 fn as_ref(&self) -> &str {
20 self.0.as_ref()
21 }
22}
23
24impl<'a> TryFrom<&'a BStr> for NameRef<'a> {
25 type Error = Error;
26
27 fn try_from(attr: &'a BStr) -> Result<Self, Self::Error> {
28 fn attr_valid(attr: &BStr) -> bool {
29 if attr.first() == Some(&b'-') {
30 return false;
31 }
32
33 attr.bytes()
34 .all(|b| matches!(b, b'-' | b'.' | b'_' | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'))
35 }
36
37 attr_valid(attr)
38 .then(|| NameRef(KStringRef::from_ref(attr.to_str().expect("no illformed utf8"))))
39 .ok_or_else(|| Error { attribute: attr.into() })
40 }
41}
42
43impl<'a> Name {
44 pub fn as_ref(&'a self) -> NameRef<'a> {
46 NameRef(self.0.as_ref())
47 }
48
49 pub fn as_str(&self) -> &str {
51 self.0.as_str()
52 }
53}
54
55impl AsRef<str> for Name {
56 fn as_ref(&self) -> &str {
57 self.0.as_str()
58 }
59}
60
61#[derive(Debug, thiserror::Error)]
63#[error("Attribute has non-ascii characters or starts with '-': {attribute}")]
64pub struct Error {
65 pub attribute: BString,
67}