1use std::borrow::Borrow;
2
3use bstr::{BStr, BString, ByteSlice};
4use gix_features::threading::OwnShared;
5
6use crate::{Name, NameRef};
7
8impl NameRef<'_> {
9 pub fn to_owned(self) -> Name {
11 Name(OwnShared::from(self.0))
12 }
13
14 pub fn as_str(&self) -> &str {
16 self.0
17 }
18}
19
20impl AsRef<str> for NameRef<'_> {
21 fn as_ref(&self) -> &str {
22 self.0
23 }
24}
25
26impl<'a> TryFrom<&'a BStr> for NameRef<'a> {
27 type Error = Error;
28
29 fn try_from(attr: &'a BStr) -> Result<Self, Self::Error> {
30 fn attr_valid(attr: &BStr) -> bool {
31 if attr.first() == Some(&b'-') {
32 return false;
33 }
34
35 attr.bytes()
36 .all(|b| matches!(b, b'-' | b'.' | b'_' | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'))
37 }
38
39 attr_valid(attr)
40 .then(|| NameRef(attr.to_str().expect("no illformed utf8")))
41 .ok_or_else(|| Error { attribute: attr.into() })
42 }
43}
44
45impl<'a> Name {
46 pub fn as_ref(&'a self) -> NameRef<'a> {
48 NameRef(self.as_str())
49 }
50
51 pub fn as_str(&self) -> &str {
53 &self.0
54 }
55}
56
57impl AsRef<str> for Name {
58 fn as_ref(&self) -> &str {
59 self.as_str()
60 }
61}
62
63impl Borrow<str> for Name {
64 fn borrow(&self) -> &str {
65 self.as_str()
66 }
67}
68
69#[cfg(feature = "serde")]
70impl serde::Serialize for Name {
71 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
72 where
73 S: serde::Serializer,
74 {
75 serializer.serialize_newtype_struct("Name", self.as_str())
76 }
77}
78
79#[cfg(feature = "serde")]
80impl<'de> serde::Deserialize<'de> for Name {
81 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
82 where
83 D: serde::Deserializer<'de>,
84 {
85 #[derive(serde::Deserialize)]
86 #[serde(rename = "Name")]
87 struct NameDef(String);
88
89 let NameDef(value) = <NameDef as serde::Deserialize>::deserialize(deserializer)?;
90 Ok(Name(OwnShared::from(value)))
91 }
92}
93
94#[derive(Debug, thiserror::Error)]
96#[error("Attribute has non-ascii characters or starts with '-': {attribute}")]
97pub struct Error {
98 pub attribute: BString,
100}