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
use super::Name;
use std::fmt::Display;
use std::ops::Deref;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct Path(Vec<Name>);
impl Deref for Path {
type Target = Vec<Name>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Path {
pub const ROOT: Self = Self(vec![]);
pub fn intersperse(&self, sep: &str) -> String {
let mut it = self.0.iter();
match it.next() {
None => Default::default(),
Some(first) => {
let mut s = String::with_capacity(
self.0.iter().map(|p| p.len()).sum::<usize>() + self.0.len() - 1,
);
s.push_str(first);
for p in it {
s.push_str(sep);
s.push_str(p);
}
s
}
}
}
}
impl From<Name> for Path {
fn from(name: Name) -> Self {
Self(vec![name])
}
}
impl FromIterator<Name> for Path {
fn from_iter<T: IntoIterator<Item = Name>>(iter: T) -> Self {
Self(Vec::<Name>::from_iter(iter))
}
}
impl FromStr for Path {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.trim_start_matches('/')
.split_terminator('/')
.map(FromStr::from_str)
.collect::<Result<Vec<_>, Self::Err>>()
.map(Self)
}
}
impl Display for Path {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.intersperse("/"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_str() {
assert_eq!("/".parse::<Path>().unwrap(), Path::ROOT);
assert_eq!(
"/foo".parse::<Path>().unwrap(),
Path(vec!["foo".parse().unwrap()])
);
assert_eq!(
"/foo/".parse::<Path>().unwrap(),
Path(vec!["foo".parse().unwrap()])
);
assert_eq!(
"/foo/bar".parse::<Path>().unwrap(),
Path(vec!["foo".parse().unwrap(), "bar".parse().unwrap()])
);
}
}