]> git.proxmox.com Git - rustc.git/blame - vendor/gix-attributes/src/name.rs
New upstream version 1.74.1+dfsg1
[rustc.git] / vendor / gix-attributes / src / name.rs
CommitLineData
49aad941 1use bstr::{BStr, BString, ByteSlice};
781aab86 2use byteyarn::YarnRef;
0a29b90c
FG
3
4use crate::{Name, NameRef};
5
6impl<'a> NameRef<'a> {
7 /// Turn this ref into its owned counterpart.
8 pub fn to_owned(self) -> Name {
781aab86
FG
9 Name(
10 self.0
11 .immortalize()
12 .map_or_else(|| self.0.to_boxed_str().into(), YarnRef::to_box),
13 )
0a29b90c
FG
14 }
15
16 /// Return the inner `str`.
17 pub fn as_str(&self) -> &str {
49aad941 18 self.0.as_str()
0a29b90c
FG
19 }
20}
21
22impl AsRef<str> for NameRef<'_> {
23 fn as_ref(&self) -> &str {
49aad941
FG
24 self.0.as_ref()
25 }
26}
27
28impl<'a> TryFrom<&'a BStr> for NameRef<'a> {
29 type Error = Error;
30
31 fn try_from(attr: &'a BStr) -> Result<Self, Self::Error> {
32 fn attr_valid(attr: &BStr) -> bool {
33 if attr.first() == Some(&b'-') {
34 return false;
35 }
36
37 attr.bytes()
38 .all(|b| matches!(b, b'-' | b'.' | b'_' | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'))
39 }
40
41 attr_valid(attr)
781aab86 42 .then(|| NameRef(YarnRef::from(attr.to_str().expect("no illformed utf8"))))
49aad941 43 .ok_or_else(|| Error { attribute: attr.into() })
0a29b90c
FG
44 }
45}
46
47impl<'a> Name {
48 /// Provide our ref-type.
49 pub fn as_ref(&'a self) -> NameRef<'a> {
50 NameRef(self.0.as_ref())
51 }
52
53 /// Return the inner `str`.
54 pub fn as_str(&self) -> &str {
55 self.0.as_str()
56 }
57}
58
59impl AsRef<str> for Name {
60 fn as_ref(&self) -> &str {
61 self.0.as_str()
62 }
63}
64
65/// The error returned by [`parse::Iter`][crate::parse::Iter].
66#[derive(Debug, thiserror::Error)]
67#[error("Attribute has non-ascii characters or starts with '-': {attribute}")]
68pub struct Error {
69 /// The attribute that failed to parse.
70 pub attribute: BString,
71}