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
use crate::cid::Cid;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Path(Vec<String>);
impl Path {
pub fn iter(&self) -> impl Iterator<Item = &str> {
self.0.iter().map(|s| &**s)
}
pub fn join<T: AsRef<str>>(&mut self, segment: T) {
for seg in segment.as_ref().split('/').filter(|s| !s.is_empty()) {
self.0.push(seg.to_owned())
}
}
}
impl From<Vec<String>> for Path {
fn from(segments: Vec<String>) -> Self {
Path(segments)
}
}
impl From<Vec<&str>> for Path {
fn from(segments: Vec<&str>) -> Self {
Path(segments.into_iter().map(String::from).collect())
}
}
impl From<&str> for Path {
fn from(s: &str) -> Self {
let mut path = Path::default();
path.join(s);
path
}
}
impl From<String> for Path {
fn from(s: String) -> Self {
Path::from(s.as_str())
}
}
impl ToString for Path {
fn to_string(&self) -> String {
let mut path = "".to_string();
for seg in &self.0 {
path.push_str(seg.as_str());
path.push('/');
}
path.pop();
path
}
}
#[derive(Clone, Debug, PartialEq, Hash)]
pub struct DagPath<'a>(&'a Cid, Path);
impl<'a> DagPath<'a> {
pub fn new<T: Into<Path>>(cid: &'a Cid, path: T) -> Self {
Self(cid, path.into())
}
pub fn root(&self) -> &Cid {
self.0
}
pub fn path(&self) -> &Path {
&self.1
}
}
impl<'a> From<&'a Cid> for DagPath<'a> {
fn from(cid: &'a Cid) -> Self {
Self(cid, Default::default())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parsing_one_segment() {
assert_eq!(Path::from("0"), Path::from(vec!["0"]));
}
#[test]
fn test_parsing_three_segments() {
assert_eq!(Path::from("0/foo/2"), Path::from(vec!["0", "foo", "2"]));
}
#[test]
fn test_eliding_empty_segments() {
assert_eq!(Path::from("0//2"), Path::from(vec!["0", "2"]));
}
#[test]
fn test_eliding_leading_slashes() {
assert_eq!(Path::from("/0/2"), Path::from(vec!["0", "2"]));
}
#[test]
fn test_eliding_trailing_slashes() {
assert_eq!(Path::from("0/2/"), Path::from(vec!["0", "2"]));
}
#[test]
fn test_to_string() {
assert_eq!(Path::from(vec!["0", "foo", "2"]).to_string(), "0/foo/2");
}
}