drawbridge_type/tree/
path.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use super::Name;
4
5use std::fmt::Display;
6use std::ops::Deref;
7use std::path::PathBuf;
8use std::str::FromStr;
9
10use serde::{Deserialize, Serialize};
11
12#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
13#[repr(transparent)]
14#[serde(transparent)]
15pub struct Path(Vec<Name>);
16
17impl Path {
18    pub const ROOT: Self = Self(vec![]);
19
20    pub fn intersperse(&self, sep: &str) -> String {
21        let mut it = self.0.iter();
22        match it.next() {
23            None => Default::default(),
24            Some(first) => {
25                let mut s = String::with_capacity(
26                    self.0.iter().map(|p| p.len()).sum::<usize>() + self.0.len() - 1,
27                );
28                s.push_str(first);
29                for p in it {
30                    s.push_str(sep);
31                    s.push_str(p);
32                }
33                s
34            }
35        }
36    }
37}
38
39impl AsRef<Vec<Name>> for Path {
40    fn as_ref(&self) -> &Vec<Name> {
41        &self.0
42    }
43}
44
45impl AsRef<[Name]> for Path {
46    fn as_ref(&self) -> &[Name] {
47        &self.0
48    }
49}
50
51impl Deref for Path {
52    type Target = Vec<Name>;
53
54    fn deref(&self) -> &Self::Target {
55        &self.0
56    }
57}
58
59impl Display for Path {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        write!(f, "{}", self.intersperse("/"))
62    }
63}
64
65impl From<Name> for Path {
66    fn from(name: Name) -> Self {
67        Self(vec![name])
68    }
69}
70
71impl From<Path> for PathBuf {
72    fn from(path: Path) -> Self {
73        path.into_iter().map(PathBuf::from).collect()
74    }
75}
76
77impl FromIterator<Name> for Path {
78    fn from_iter<T: IntoIterator<Item = Name>>(iter: T) -> Self {
79        Self(Vec::<Name>::from_iter(iter))
80    }
81}
82
83impl FromStr for Path {
84    type Err = anyhow::Error;
85
86    fn from_str(s: &str) -> Result<Self, Self::Err> {
87        s.trim_start_matches('/')
88            .split_terminator('/')
89            .map(FromStr::from_str)
90            .collect::<Result<Vec<_>, Self::Err>>()
91            .map(Self)
92    }
93}
94
95impl IntoIterator for Path {
96    type Item = Name;
97    type IntoIter = std::vec::IntoIter<Self::Item>;
98
99    fn into_iter(self) -> Self::IntoIter {
100        self.0.into_iter()
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn from_str() {
110        assert_eq!("/".parse::<Path>().unwrap(), Path::ROOT);
111        assert_eq!(
112            "/foo".parse::<Path>().unwrap(),
113            Path(vec!["foo".parse().unwrap()])
114        );
115        assert_eq!(
116            "/foo/".parse::<Path>().unwrap(),
117            Path(vec!["foo".parse().unwrap()])
118        );
119        assert_eq!(
120            "/foo/bar".parse::<Path>().unwrap(),
121            Path(vec!["foo".parse().unwrap(), "bar".parse().unwrap()])
122        );
123    }
124}