arch_pkg_text/desc/field/
parse.rs1use super::{Field, RawField};
2use derive_more::{Display, Error};
3use pipe_trait::Pipe;
4
5#[derive(Debug, Display, Clone, Copy, Error)]
7pub enum ParseFieldError<ParseNameError> {
8 RawField(ParseRawFieldError),
9 Name(ParseNameError),
10}
11
12impl<Name> Field<Name> {
13 pub fn parse<'a>(value: &'a str) -> Result<Self, <Self as TryFrom<&'a str>>::Error>
21 where
22 &'a str: TryInto<Name>,
23 {
24 Self::try_from(value)
25 }
26}
27
28impl<'a, Name> TryFrom<&'a str> for Field<Name>
30where
31 &'a str: TryInto<Name>,
32{
33 type Error = ParseFieldError<<&'a str as TryInto<Name>>::Error>;
34 fn try_from(value: &'a str) -> Result<Self, Self::Error> {
35 value
36 .pipe(RawField::parse_raw)
37 .map_err(ParseFieldError::RawField)?
38 .into_name()
39 .pipe(TryInto::<Name>::try_into)
40 .map_err(ParseFieldError::Name)
41 .map(Field)
42 }
43}
44
45#[derive(Debug, Display, Clone, Copy, Error)]
47pub enum ParseRawFieldError {
48 #[display("Input doesn't start with '%'")]
49 IncorrectStartingCharacter,
50 #[display("Input doesn't end with '%'")]
51 IncorrectEndingCharacter,
52 #[display("Field name is empty")]
53 Empty,
54 #[display("Field name contains invalid character {_1:?} at index {_0}")]
55 InvalidCharacter(usize, char),
56}
57
58impl<'a> RawField<'a> {
59 pub fn parse_raw(input: &'a str) -> Result<Self, ParseRawFieldError> {
72 let field_name = input
73 .strip_prefix('%')
74 .ok_or(ParseRawFieldError::IncorrectStartingCharacter)?
75 .strip_suffix('%')
76 .ok_or(ParseRawFieldError::IncorrectEndingCharacter)?;
77
78 if field_name.is_empty() {
79 return Err(ParseRawFieldError::Empty);
80 }
81
82 if let Some((index, char)) = field_name
83 .char_indices()
84 .find(|(_, x)| !x.is_ascii_uppercase() && !x.is_ascii_digit())
85 {
86 return Err(ParseRawFieldError::InvalidCharacter(index, char));
87 }
88
89 Ok(Field(field_name))
90 }
91
92 pub fn to_parsed<Name>(&self) -> Result<Field<Name>, <&'a str as TryInto<Name>>::Error>
102 where
103 &'a str: TryInto<Name>,
104 {
105 self.name_str().pipe(TryInto::<Name>::try_into).map(Field)
106 }
107}