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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use regex::Regex;
use std::cmp::{Eq, PartialEq};
use std::convert::{From, TryFrom};
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::ops::Deref;
use std::str::Split;

lazy_static! {
    /// The regular expression for a valid [object path].
    ///
    /// [object path]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling-object-path
    pub static ref OBJECT_PATH_REGEX: Regex = Regex::new(r"^/([A-Za-z0-9_]+(/[A-Za-z0-9_]+)*)?$").unwrap();

    /// The regular expression for a element of an [object path].
    ///
    /// [object path]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling-object-path
    pub static ref OBJECT_PATH_ELEMENT_REGEX: Regex = Regex::new(r"^[A-Za-z0-9_]+$").unwrap();
}

/// This represents a [object path].
///
/// [object path]: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling-object-path
#[derive(Debug, Clone, PartialOrd, PartialEq, Ord, Eq, Hash)]
pub struct ObjectPath(String);

/// An enum representing all errors, which can occur during the handling of a [`ObjectPath`].
#[derive(Debug, PartialEq, Eq)]
pub enum ObjectPathError {
    /// This error occurs, when the given string was not a valid object path.
    TryFromError(String),
}

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

impl TryFrom<String> for ObjectPath {
    type Error = ObjectPathError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if OBJECT_PATH_REGEX.is_match(&value) {
            Ok(ObjectPath(value))
        } else {
            Err(ObjectPathError::TryFromError(value))
        }
    }
}

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

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let value = value.to_string();
        ObjectPath::try_from(value)
    }
}

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

impl Deref for ObjectPath {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Default for ObjectPath {
    fn default() -> Self {
        ObjectPath("/".to_string())
    }
}

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

impl ObjectPath {
    /// Append an element to the object path.
    ///
    /// Returns `true` if the new element could be appended, otherwise `false`.
    /// An element cannot be appended if the element contain a character, which is not allowed.
    ///
    /// # Example
    /// ```
    /// # use std::convert::TryFrom;
    /// # use dbus_message_parser::ObjectPath;
    /// #
    /// let mut object_path = ObjectPath::try_from("/object").unwrap();
    ///
    /// assert!(object_path.append("path"));
    /// assert!(!object_path.append("/path"));
    ///
    /// assert_eq!(&object_path, "/object/path");
    /// ```
    pub fn append(&mut self, element: &str) -> bool {
        if OBJECT_PATH_ELEMENT_REGEX.is_match(element) {
            if self.0 != "/" {
                self.0 += "/";
            }
            self.0 += element;
            true
        } else {
            false
        }
    }

    /// Determines whether `base` is a prefix of `self`.
    ///
    /// # Example
    /// ```
    /// # use std::convert::TryFrom;
    /// # use dbus_message_parser::ObjectPath;
    /// #
    /// let base = ObjectPath::try_from("/object").unwrap();
    ///
    /// let path_1 = ObjectPath::try_from("/object/path").unwrap();
    /// let path_2 = ObjectPath::try_from("/object_/path").unwrap();
    ///
    /// assert!(path_1.starts_with(&base));
    /// assert!(!path_2.starts_with(&base));
    /// assert!(!base.starts_with(&base));
    /// ```
    pub fn starts_with(&self, base: &ObjectPath) -> bool {
        if let Some(mut iter) = self.strip_prefix_elements(base) {
            iter.next().is_some()
        } else {
            false
        }
    }

    /// Returns a [`Split`] object with the prefix removed.
    ///
    /// [`Split`]: std::str::Split
    ///
    /// # Example
    /// ```
    /// # use std::convert::TryFrom;
    /// # use dbus_message_parser::ObjectPath;
    /// #
    /// let base = ObjectPath::try_from("/object").unwrap();
    ///
    /// let path_1 = ObjectPath::try_from("/object/path").unwrap();
    /// let path_2 = ObjectPath::try_from("/object_/path").unwrap();
    /// let path_3 = ObjectPath::try_from("/object/path/element").unwrap();
    ///
    /// let path_1_base_vec: Vec<&str> = path_1.strip_prefix_elements(&base).unwrap().collect();
    /// let path_3_base_vec: Vec<&str> = path_3.strip_prefix_elements(&base).unwrap().collect();
    ///
    /// assert_eq!(path_1_base_vec, vec!["path"]);
    /// assert!(path_2.strip_prefix_elements(&base).is_none());
    /// assert_eq!(path_3_base_vec, vec!["path", "element"]);
    /// assert!(base.strip_prefix_elements(&base).is_none());
    /// ```
    pub fn strip_prefix_elements<'a, 'b>(
        &'a self,
        base: &'b ObjectPath,
    ) -> Option<Split<'a, char>> {
        let mut self_iter = self.0.split('/');
        if self != "/" && base == "/" {
            self_iter.next()?;
            return Some(self_iter);
        }
        let mut base_iter = base.0.split('/');
        loop {
            let self_iter_prev = self_iter.clone();
            match (self_iter.next(), base_iter.next()) {
                (Some(ref x), Some(ref y)) => {
                    if x != y {
                        return None;
                    }
                }
                (Some(_), None) => return Some(self_iter_prev),
                (None, None) => return None,
                (None, Some(_)) => return None,
            }
        }
    }
}