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
use crate::net::ResKey;
use regex::Regex;
use std::convert::TryFrom;
use std::fmt;
use zenoh_util::core::{ZError, ZErrorKind, ZResult};
use zenoh_util::zerror;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Path {
pub(crate) p: String,
}
impl Path {
fn is_valid(path: &str) -> bool {
!path.is_empty()
&& !path.contains(|c| c == '?' || c == '#' || c == '[' || c == ']' || c == '*')
}
pub(crate) fn remove_useless_slashes(path: &str) -> String {
lazy_static! {
static ref RE: Regex = Regex::new("/+").unwrap();
}
let p = RE.replace_all(path, "/");
p.strip_suffix("/").unwrap_or(&p).to_string()
}
pub fn new(p: String) -> ZResult<Path> {
if !Self::is_valid(&p) {
zerror!(ZErrorKind::InvalidPath { path: p })
} else {
Ok(Path {
p: Self::remove_useless_slashes(&p),
})
}
}
pub fn as_str(&self) -> &str {
self.p.as_str()
}
pub fn is_relative(&self) -> bool {
!self.p.starts_with('/')
}
pub fn with_prefix(&self, prefix: &Path) -> Self {
if self.is_relative() {
Self {
p: format!("{}/{}", prefix.p, self.p),
}
} else {
Self {
p: format!("{}{}", prefix.p, self.p),
}
}
}
pub fn strip_prefix(&self, prefix: &Path) -> Option<Self> {
self.p
.strip_prefix(&prefix.p)
.map(|p| Path { p: p.to_string() })
}
}
impl fmt::Display for Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.p)
}
}
impl TryFrom<String> for Path {
type Error = ZError;
fn try_from(p: String) -> Result<Self, Self::Error> {
Path::new(p)
}
}
impl TryFrom<&str> for Path {
type Error = ZError;
fn try_from(p: &str) -> ZResult<Path> {
Self::try_from(p.to_string())
}
}
impl From<Path> for ResKey {
fn from(path: Path) -> Self {
ResKey::from(path.p.as_str())
}
}
impl From<&Path> for ResKey {
fn from(path: &Path) -> Self {
ResKey::from(path.p.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::convert::TryInto;
#[test]
fn test_path() {
assert_eq!(Path::try_from("a/b").unwrap(), Path { p: "a/b".into() });
assert_eq!(Path::try_from("/a/b").unwrap(), Path { p: "/a/b".into() });
assert_eq!(
Path::try_from("////a///b///").unwrap(),
Path { p: "/a/b".into() }
);
assert!(Path::try_from("a/b").unwrap().is_relative());
assert!(!Path::try_from("/a/b").unwrap().is_relative());
assert_eq!(
Path::try_from("c/d")
.unwrap()
.with_prefix(&"/a/b".try_into().unwrap()),
Path {
p: "/a/b/c/d".into()
}
);
assert_eq!(
Path::try_from("/c/d")
.unwrap()
.with_prefix(&"/a/b".try_into().unwrap()),
Path {
p: "/a/b/c/d".into()
}
);
}
}