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! {
pub static ref OBJECT_PATH_REGEX: Regex = Regex::new(r"^/([A-Za-z0-9_]+(/[A-Za-z0-9_]+)*)?$").unwrap();
pub static ref OBJECT_PATH_ELEMENT_REGEX: Regex = Regex::new(r"^[A-Za-z0-9_]+$").unwrap();
}
#[derive(Debug, Clone, PartialOrd, PartialEq, Ord, Eq, Hash)]
pub struct ObjectPath(String);
#[derive(Debug, PartialEq, Eq)]
pub enum ObjectPathError {
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 {
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
}
}
pub fn starts_with(&self, base: &ObjectPath) -> bool {
if let Some(mut iter) = self.strip_prefix_elements(base) {
iter.next().is_some()
} else {
false
}
}
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,
}
}
}
}