]> git.lizzy.rs Git - rust.git/blob - crates/paths/src/lib.rs
tree-wide: make rustdoc links spiky so they are clickable
[rust.git] / crates / paths / src / lib.rs
1 //! Thin wrappers around `std::path`, distinguishing between absolute and
2 //! relative paths.
3 use std::{
4     borrow::Borrow,
5     convert::{TryFrom, TryInto},
6     ops,
7     path::{Component, Path, PathBuf},
8 };
9
10 /// Wrapper around an absolute [`PathBuf`].
11 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
12 pub struct AbsPathBuf(PathBuf);
13
14 impl From<AbsPathBuf> for PathBuf {
15     fn from(AbsPathBuf(path_buf): AbsPathBuf) -> PathBuf {
16         path_buf
17     }
18 }
19
20 impl ops::Deref for AbsPathBuf {
21     type Target = AbsPath;
22     fn deref(&self) -> &AbsPath {
23         self.as_path()
24     }
25 }
26
27 impl AsRef<Path> for AbsPathBuf {
28     fn as_ref(&self) -> &Path {
29         self.0.as_path()
30     }
31 }
32
33 impl AsRef<AbsPath> for AbsPathBuf {
34     fn as_ref(&self) -> &AbsPath {
35         self.as_path()
36     }
37 }
38
39 impl Borrow<AbsPath> for AbsPathBuf {
40     fn borrow(&self) -> &AbsPath {
41         self.as_path()
42     }
43 }
44
45 impl TryFrom<PathBuf> for AbsPathBuf {
46     type Error = PathBuf;
47     fn try_from(path_buf: PathBuf) -> Result<AbsPathBuf, PathBuf> {
48         if !path_buf.is_absolute() {
49             return Err(path_buf);
50         }
51         Ok(AbsPathBuf(path_buf))
52     }
53 }
54
55 impl TryFrom<&str> for AbsPathBuf {
56     type Error = PathBuf;
57     fn try_from(path: &str) -> Result<AbsPathBuf, PathBuf> {
58         AbsPathBuf::try_from(PathBuf::from(path))
59     }
60 }
61
62 impl PartialEq<AbsPath> for AbsPathBuf {
63     fn eq(&self, other: &AbsPath) -> bool {
64         self.as_path() == other
65     }
66 }
67
68 impl AbsPathBuf {
69     /// Wrap the given absolute path in `AbsPathBuf`
70     ///
71     /// # Panics
72     ///
73     /// Panics if `path` is not absolute.
74     pub fn assert(path: PathBuf) -> AbsPathBuf {
75         AbsPathBuf::try_from(path)
76             .unwrap_or_else(|path| panic!("expected absolute path, got {}", path.display()))
77     }
78
79     /// Coerces to a `AbsPath` slice.
80     ///
81     /// Equivalent of [`PathBuf::as_path`] for `AbsPathBuf`.
82     pub fn as_path(&self) -> &AbsPath {
83         AbsPath::assert(self.0.as_path())
84     }
85
86     /// Equivalent of [`PathBuf::pop`] for `AbsPathBuf`.
87     ///
88     /// Note that this won't remove the root component, so `self` will still be
89     /// absolute.
90     pub fn pop(&mut self) -> bool {
91         self.0.pop()
92     }
93 }
94
95 /// Wrapper around an absolute [`Path`].
96 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
97 #[repr(transparent)]
98 pub struct AbsPath(Path);
99
100 impl ops::Deref for AbsPath {
101     type Target = Path;
102     fn deref(&self) -> &Path {
103         &self.0
104     }
105 }
106
107 impl AsRef<Path> for AbsPath {
108     fn as_ref(&self) -> &Path {
109         &self.0
110     }
111 }
112
113 impl<'a> TryFrom<&'a Path> for &'a AbsPath {
114     type Error = &'a Path;
115     fn try_from(path: &'a Path) -> Result<&'a AbsPath, &'a Path> {
116         if !path.is_absolute() {
117             return Err(path);
118         }
119         Ok(AbsPath::assert(path))
120     }
121 }
122
123 impl AbsPath {
124     /// Wrap the given absolute path in `AbsPath`
125     ///
126     /// # Panics
127     ///
128     /// Panics if `path` is not absolute.
129     pub fn assert(path: &Path) -> &AbsPath {
130         assert!(path.is_absolute());
131         unsafe { &*(path as *const Path as *const AbsPath) }
132     }
133
134     /// Equivalent of [`Path::parent`] for `AbsPath`.
135     pub fn parent(&self) -> Option<&AbsPath> {
136         self.0.parent().map(AbsPath::assert)
137     }
138
139     /// Equivalent of [`Path::join`] for `AbsPath`.
140     pub fn join(&self, path: impl AsRef<Path>) -> AbsPathBuf {
141         self.as_ref().join(path).try_into().unwrap()
142     }
143
144     /// Normalize the given path:
145     /// - Removes repeated separators: `/a//b` becomes `/a/b`
146     /// - Removes occurrences of `.` and resolves `..`.
147     /// - Removes trailing slashes: `/a/b/` becomes `/a/b`.
148     ///
149     /// # Example
150     /// ```
151     /// # use paths::AbsPathBuf;
152     /// let abs_path_buf = AbsPathBuf::assert("/a/../../b/.//c//".into());
153     /// let normalized = abs_path_buf.normalize();
154     /// assert_eq!(normalized, AbsPathBuf::assert("/b/c".into()));
155     /// ```
156     pub fn normalize(&self) -> AbsPathBuf {
157         AbsPathBuf(normalize_path(&self.0))
158     }
159
160     /// Equivalent of [`Path::to_path_buf`] for `AbsPath`.
161     pub fn to_path_buf(&self) -> AbsPathBuf {
162         AbsPathBuf::try_from(self.0.to_path_buf()).unwrap()
163     }
164
165     /// Equivalent of [`Path::strip_prefix`] for `AbsPath`.
166     ///
167     /// Returns a relative path.
168     pub fn strip_prefix(&self, base: &AbsPath) -> Option<&RelPath> {
169         self.0.strip_prefix(base).ok().map(RelPath::new_unchecked)
170     }
171 }
172
173 /// Wrapper around a relative [`PathBuf`].
174 #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
175 pub struct RelPathBuf(PathBuf);
176
177 impl From<RelPathBuf> for PathBuf {
178     fn from(RelPathBuf(path_buf): RelPathBuf) -> PathBuf {
179         path_buf
180     }
181 }
182
183 impl ops::Deref for RelPathBuf {
184     type Target = RelPath;
185     fn deref(&self) -> &RelPath {
186         self.as_path()
187     }
188 }
189
190 impl AsRef<Path> for RelPathBuf {
191     fn as_ref(&self) -> &Path {
192         self.0.as_path()
193     }
194 }
195
196 impl TryFrom<PathBuf> for RelPathBuf {
197     type Error = PathBuf;
198     fn try_from(path_buf: PathBuf) -> Result<RelPathBuf, PathBuf> {
199         if !path_buf.is_relative() {
200             return Err(path_buf);
201         }
202         Ok(RelPathBuf(path_buf))
203     }
204 }
205
206 impl TryFrom<&str> for RelPathBuf {
207     type Error = PathBuf;
208     fn try_from(path: &str) -> Result<RelPathBuf, PathBuf> {
209         RelPathBuf::try_from(PathBuf::from(path))
210     }
211 }
212
213 impl RelPathBuf {
214     /// Coerces to a `RelPath` slice.
215     ///
216     /// Equivalent of [`PathBuf::as_path`] for `RelPathBuf`.
217     pub fn as_path(&self) -> &RelPath {
218         RelPath::new_unchecked(self.0.as_path())
219     }
220 }
221
222 /// Wrapper around a relative [`Path`].
223 #[derive(Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
224 #[repr(transparent)]
225 pub struct RelPath(Path);
226
227 impl ops::Deref for RelPath {
228     type Target = Path;
229     fn deref(&self) -> &Path {
230         &self.0
231     }
232 }
233
234 impl AsRef<Path> for RelPath {
235     fn as_ref(&self) -> &Path {
236         &self.0
237     }
238 }
239
240 impl RelPath {
241     /// Creates a new `RelPath` from `path`, without checking if it is relative.
242     pub fn new_unchecked(path: &Path) -> &RelPath {
243         unsafe { &*(path as *const Path as *const RelPath) }
244     }
245 }
246
247 /// Taken from <https://github.com/rust-lang/cargo/blob/79c769c3d7b4c2cf6a93781575b7f592ef974255/src/cargo/util/paths.rs#L60-L85>
248 fn normalize_path(path: &Path) -> PathBuf {
249     let mut components = path.components().peekable();
250     let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
251         components.next();
252         PathBuf::from(c.as_os_str())
253     } else {
254         PathBuf::new()
255     };
256
257     for component in components {
258         match component {
259             Component::Prefix(..) => unreachable!(),
260             Component::RootDir => {
261                 ret.push(component.as_os_str());
262             }
263             Component::CurDir => {}
264             Component::ParentDir => {
265                 ret.pop();
266             }
267             Component::Normal(c) => {
268                 ret.push(c);
269             }
270         }
271     }
272     ret
273 }