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
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;
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 start_with(&self, base: &ObjectPath) -> bool {
if self.0.starts_with(&base.0) {
if let Some(c) = self.0.chars().nth(base.0.len()) {
c == '/'
} else {
false
}
} else {
false
}
}
}