1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use crate::value::MAXIMUM_NAME_LENGTH;
use std::cmp::{Eq, PartialEq};
use std::convert::{From, TryFrom};
use std::fmt::{Display, Formatter, Result as FmtResult};
use thiserror::Error as ThisError;

enum Input {
    /// [A-Z][a-z]_
    AlphabeticAndUnderscore,
    /// [0-9]
    Digit,
    /// .
    Dot,
}

impl TryFrom<u8> for Input {
    type Error = ErrorError;

    fn try_from(c: u8) -> Result<Self, Self::Error> {
        if c.is_ascii_alphabetic() || c == b'_' {
            Ok(Input::AlphabeticAndUnderscore)
        } else if c.is_ascii_digit() {
            Ok(Input::Digit)
        } else if c == b'.' {
            Ok(Input::Dot)
        } else {
            Err(ErrorError::InvalidChar(c))
        }
    }
}

enum State {
    /// The first character of the first element.
    FirstElementBegin,
    /// The second or subsequent character of the first element.
    FirstElement,
    /// The first character of the second or subsequent element.
    ElementBegin,
    /// The second or subsequent character of the second or subsequent element.
    Element,
}

impl State {
    #[inline]
    fn consume(self, i: Input) -> Result<State, ErrorError> {
        match self {
            State::FirstElementBegin => match i {
                Input::AlphabeticAndUnderscore => Ok(State::FirstElement),
                Input::Digit => Err(ErrorError::ElementBeginDigit),
                Input::Dot => Err(ErrorError::ElementBeginDot),
            },
            State::FirstElement => match i {
                Input::AlphabeticAndUnderscore => Ok(State::FirstElement),
                Input::Digit => Ok(State::FirstElement),
                Input::Dot => Ok(State::ElementBegin),
            },
            State::ElementBegin => match i {
                Input::AlphabeticAndUnderscore => Ok(State::Element),
                Input::Digit => Err(ErrorError::ElementBeginDigit),
                Input::Dot => Err(ErrorError::ElementBeginDot),
            },
            State::Element => match i {
                Input::AlphabeticAndUnderscore => Ok(State::Element),
                Input::Digit => Ok(State::Element),
                Input::Dot => Ok(State::ElementBegin),
            },
        }
    }
}

/// Check if the given bytes is a valid [error name].
///
/// [error name]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-error
fn check(error: &[u8]) -> Result<(), ErrorError> {
    let error_len = error.len();
    if MAXIMUM_NAME_LENGTH < error_len {
        return Err(ErrorError::ExceedMaximum(error_len));
    }

    let mut state = State::FirstElementBegin;
    for c in error {
        let i = Input::try_from(*c)?;
        state = state.consume(i)?;
    }

    match state {
        State::FirstElementBegin => Err(ErrorError::Empty),
        State::FirstElement => Err(ErrorError::Elements),
        State::ElementBegin => Err(ErrorError::EndDot),
        State::Element => Ok(()),
    }
}

/// This represents an [error name].
///
/// [error name]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-error
#[derive(Debug, Clone, PartialOrd, PartialEq, Ord, Eq, Hash)]
pub struct Error(String);

/// An enum representing all errors, which can occur during the handling of a [`Error`].
#[derive(Debug, PartialEq, Eq, ThisError)]
pub enum ErrorError {
    #[error("Error element must not begin with a digit")]
    ElementBeginDigit,
    #[error("Error element must not beign with a '.'")]
    ElementBeginDot,
    #[error("Error must not end with '.'")]
    EndDot,
    #[error("Error most not be empty")]
    Empty,
    #[error("Error have to be composed of 2 or more elements")]
    Elements,
    #[error("Error must not exceed the maximum length: {MAXIMUM_NAME_LENGTH} < {0}")]
    ExceedMaximum(usize),
    #[error("Error must only contain '[A-Z][a-z][0-9]_.': {0}")]
    InvalidChar(u8),
}

impl From<Error> for String {
    fn from(error: Error) -> Self {
        error.0
    }
}

impl TryFrom<String> for Error {
    type Error = ErrorError;

    fn try_from(error: String) -> Result<Self, Self::Error> {
        check(error.as_bytes())?;
        Ok(Error(error))
    }
}

impl TryFrom<&str> for Error {
    type Error = ErrorError;

    fn try_from(error: &str) -> Result<Self, Self::Error> {
        check(error.as_bytes())?;
        Ok(Error(error.to_owned()))
    }
}

impl TryFrom<&[u8]> for Error {
    type Error = ErrorError;

    fn try_from(error: &[u8]) -> Result<Self, Self::Error> {
        check(error)?;
        let error = error.to_vec();
        //  The vector only contains valid UTF-8 (ASCII) characters because it was already
        //  checked by the `check` function above
        unsafe { Ok(Error(String::from_utf8_unchecked(error))) }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "{}", self.0)
    }
}

impl AsRef<str> for Error {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for Error {
    fn eq(&self, other: &str) -> bool {
        self.as_ref() == other
    }
}