std_ext/
path2.rs

1use std::ops::{Deref, Div, RangeFull};
2use std::path::{Path, PathBuf as StdPathBuf};
3
4pub struct PathBuf(StdPathBuf);
5
6impl From<StdPathBuf> for PathBuf {
7    fn from(value: StdPathBuf) -> Self {
8        Self(value)
9    }
10}
11
12impl From<&Path> for PathBuf {
13    fn from(value: &Path) -> Self {
14        Self(value.to_path_buf())
15    }
16}
17
18impl From<&str> for PathBuf {
19    fn from(value: &str) -> Self {
20        Self(value.into())
21    }
22}
23
24impl std::fmt::Debug for PathBuf {
25    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
26        self.0.fmt(f)
27    }
28}
29
30impl Deref for PathBuf {
31    type Target = StdPathBuf;
32
33    fn deref(&self) -> &Self::Target {
34        &self.0
35    }
36}
37
38impl AsRef<Path> for PathBuf {
39    fn as_ref(&self) -> &Path {
40        &self.0
41    }
42}
43
44impl PathBuf {
45    pub fn new() -> Self {
46        Self(StdPathBuf::new())
47    }
48}
49
50impl PartialEq<StdPathBuf> for PathBuf {
51    fn eq(&self, other: &StdPathBuf) -> bool {
52        self.0 == *other
53    }
54}
55
56impl PartialEq<Path> for PathBuf {
57    fn eq(&self, other: &Path) -> bool {
58        self.0 == *other
59    }
60}
61
62impl Div<&str> for PathBuf {
63    type Output = PathBuf;
64
65    fn div(mut self, rhs: &str) -> Self::Output {
66        self.0.push(rhs);
67        self
68    }
69}
70
71impl Div<&Path> for PathBuf {
72    type Output = PathBuf;
73
74    fn div(mut self, rhs: &Path) -> Self::Output {
75        self.0.push(rhs);
76        self
77    }
78}
79
80impl Div<PathBuf> for PathBuf {
81    type Output = PathBuf;
82
83    fn div(mut self, rhs: PathBuf) -> Self::Output {
84        self.0.push(rhs.0);
85        self
86    }
87}
88
89impl Div<RangeFull> for PathBuf {
90    type Output = PathBuf;
91
92    fn div(mut self, _: RangeFull) -> Self::Output {
93        self.0.pop();
94        self
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    #[test]
102    fn test_path() {
103        let p = PathBuf::new() / "foo" / "bar" / ..;
104        assert_eq!(p, StdPathBuf::from("foo"));
105    }
106}