-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathabsolute.rs
More file actions
312 lines (265 loc) · 9.44 KB
/
absolute.rs
File metadata and controls
312 lines (265 loc) · 9.44 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use std::{
ffi::OsStr,
fmt::Display,
ops::Deref,
path::{Path, PathBuf},
sync::Arc,
};
use ref_cast::{RefCastCustom, ref_cast_custom};
use crate::relative::{FromPathError, InvalidPathDataError, RelativePathBuf};
/// A path that is guaranteed to be absolute
#[derive(RefCastCustom, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct AbsolutePath(Path);
impl AsRef<Self> for AbsolutePath {
fn as_ref(&self) -> &Self {
self
}
}
impl PartialEq<AbsolutePathBuf> for AbsolutePath {
fn eq(&self, other: &AbsolutePathBuf) -> bool {
self.0 == other.0
}
}
impl PartialEq<AbsolutePathBuf> for &AbsolutePath {
fn eq(&self, other: &AbsolutePathBuf) -> bool {
self.0 == other.0
}
}
impl AbsolutePath {
/// Creates a [`AbsolutePath`] if the give path is absolute.
pub fn new<P: AsRef<Path> + ?Sized>(path: &P) -> Option<&Self> {
let path = path.as_ref();
if path.is_absolute() { Some(unsafe { Self::assume_absolute(path) }) } else { None }
}
#[ref_cast_custom]
pub(crate) unsafe fn assume_absolute(abs_path: &Path) -> &Self;
/// Gets the underlying [`Path`]
#[must_use]
pub const fn as_path(&self) -> &Path {
&self.0
}
/// Converts `self` to an owned [`AbsolutePathBuf`].
#[must_use]
pub fn to_absolute_path_buf(&self) -> AbsolutePathBuf {
unsafe { AbsolutePathBuf::assume_absolute(self.0.to_path_buf()) }
}
/// Returns a path that, when joined onto base, yields self.
///
/// If `base` is not a prefix of `self`, returns [`None`].
///
/// If the stripped path is not a valid `RelativePath`. Returns an error with the reason and the stripped path.
pub fn strip_prefix<P: AsRef<Self>>(
&self,
base: P,
) -> Result<Option<RelativePathBuf>, StripPrefixError<'_>> {
let base = base.as_ref();
let Ok(stripped_path) = self.0.strip_prefix(&base.0) else {
return Ok(None);
};
match RelativePathBuf::new(stripped_path) {
Ok(relative_path) => Ok(Some(relative_path)),
Err(FromPathError::NonRelative) => {
unreachable!("stripped path should always be relative")
}
Err(FromPathError::InvalidPathData(invalid_path_data_error)) => {
Err(StripPrefixError { stripped_path, invalid_path_data_error })
}
}
}
/// Creates an owned [`AbsolutePathBuf`] with `path` adjoined to `self`.
pub fn join<P: AsRef<Path>>(&self, path: P) -> AbsolutePathBuf {
let mut absolute_path_buf = self.to_absolute_path_buf();
absolute_path_buf.push(path);
absolute_path_buf
}
/// Returns the parent directory of `self`, or `None` if `self` is the root.
#[must_use]
pub fn parent(&self) -> Option<&Self> {
let parent_path = self.0.parent()?;
Some(unsafe { Self::assume_absolute(parent_path) })
}
/// Creates an owned [`AbsolutePathBuf`] like `self` but with the extension added.
pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> AbsolutePathBuf {
let path = self.0.with_extension(extension);
unsafe { AbsolutePathBuf::assume_absolute(path) }
}
/// Returns true if `self` ends with `path`.
pub fn ends_with<P: AsRef<Path>>(&self, path: P) -> bool {
self.0.ends_with(path.as_ref())
}
}
/// An Error returned from [`AbsolutePath::strip_prefix`] if the stripped path is not a valid `RelativePath`
#[derive(thiserror::Error, Debug)]
pub struct StripPrefixError<'a> {
pub stripped_path: &'a Path,
#[source]
pub invalid_path_data_error: InvalidPathDataError,
}
impl Display for StripPrefixError<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{}: {}",
self.stripped_path.display(),
&self.invalid_path_data_error
))
}
}
impl AsRef<Path> for AbsolutePath {
fn as_ref(&self) -> &Path {
self.as_path()
}
}
/// An owned path buf that is guaranteed to be absolute
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AbsolutePathBuf(PathBuf);
impl From<AbsolutePathBuf> for Arc<AbsolutePath> {
fn from(path: AbsolutePathBuf) -> Self {
let arc: Arc<Path> = path.0.into();
let arc_raw = Arc::into_raw(arc) as *const AbsolutePath;
unsafe { Self::from_raw(arc_raw) }
}
}
impl AbsolutePathBuf {
#[must_use]
pub fn new(path: PathBuf) -> Option<Self> {
if path.is_absolute() { Some(unsafe { Self::assume_absolute(path) }) } else { None }
}
#[must_use]
pub const unsafe fn assume_absolute(abs_path: PathBuf) -> Self {
Self(abs_path)
}
#[must_use]
pub fn as_absolute_path(&self) -> &AbsolutePath {
unsafe { AbsolutePath::assume_absolute(self.0.as_path()) }
}
/// Extends `self` with `path`.
///
/// `path` replaces `self` only when `path` is absolute. Either way, the resulting `self` is always absolute.
pub fn push<P: AsRef<Path>>(&mut self, path: P) {
self.0.push(path.as_ref());
}
#[must_use]
pub fn into_path_buf(self) -> PathBuf {
self.0
}
}
impl PartialEq<AbsolutePath> for AbsolutePathBuf {
fn eq(&self, other: &AbsolutePath) -> bool {
self.as_absolute_path().eq(other)
}
}
impl PartialEq<&AbsolutePath> for AbsolutePathBuf {
fn eq(&self, other: &&AbsolutePath) -> bool {
self.as_absolute_path().eq(*other)
}
}
impl AsRef<Path> for AbsolutePathBuf {
fn as_ref(&self) -> &Path {
self.as_absolute_path().as_path()
}
}
impl AsRef<AbsolutePath> for AbsolutePathBuf {
fn as_ref(&self) -> &AbsolutePath {
self.as_absolute_path()
}
}
impl Deref for AbsolutePathBuf {
type Target = AbsolutePath;
fn deref(&self) -> &Self::Target {
self.as_absolute_path()
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
#[test]
fn non_absolute() {
assert!(AbsolutePath::new(Path::new("foo/bar")).is_none());
}
#[test]
fn strip_prefix() {
let abs_path = AbsolutePath::new(Path::new(if cfg!(windows) {
"C:\\Users\\foo\\bar"
} else {
"/home/foo/bar"
}))
.unwrap();
let prefix =
AbsolutePath::new(Path::new(if cfg!(windows) { "C:\\Users" } else { "/home" }))
.unwrap();
let rel_path = abs_path.strip_prefix(prefix).unwrap().unwrap();
assert_eq!(rel_path.as_str(), "foo/bar");
assert_eq!(prefix.join(&rel_path), abs_path);
let mut pushed_path = prefix.to_absolute_path_buf();
pushed_path.push(rel_path);
assert_eq!(pushed_path, abs_path);
}
#[test]
fn strip_prefix_trailing_slash() {
let abs_path = AbsolutePath::new(Path::new(if cfg!(windows) {
"C:\\Users\\foo\\bar"
} else {
"/home/foo/bar"
}))
.unwrap();
let prefix =
AbsolutePath::new(Path::new(if cfg!(windows) { "C:\\Users\\" } else { "/home//" }))
.unwrap();
let rel_path = abs_path.strip_prefix(prefix).unwrap().unwrap();
assert_eq!(rel_path.as_str(), "foo/bar");
}
#[test]
fn strip_prefix_not_found() {
let abs_path = AbsolutePath::new(Path::new(if cfg!(windows) {
"C:\\Users\\foo\\bar"
} else {
"/home/foo/bar"
}))
.unwrap();
let prefix = AbsolutePath::new(Path::new(if cfg!(windows) {
"C:\\Users\\barz"
} else {
"/home/baz"
}))
.unwrap();
let rel_path = abs_path.strip_prefix(prefix).unwrap();
assert!(rel_path.is_none());
}
#[cfg(unix)]
#[test]
fn strip_prefix_invalid_relative() {
use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
use assert2::let_assert;
let mut abs_path = b"/home/".to_vec();
abs_path.push(0xC0);
let abs_path = AbsolutePath::new(Path::new(OsStr::from_bytes(&abs_path))).unwrap();
let prefix = AbsolutePath::new(Path::new("/home")).unwrap();
let_assert!(Err(err) = abs_path.strip_prefix(prefix));
assert_eq!(err.stripped_path.as_os_str().as_bytes(), &[0xC0]);
let_assert!(InvalidPathDataError::NonUtf8 = err.invalid_path_data_error);
}
#[test]
#[cfg(not(windows))]
fn with_extension() {
let abs_path = AbsolutePath::new(Path::new("/home/foo/bar")).unwrap();
let abs_path_with_extension = abs_path.with_extension("txt");
assert_eq!(abs_path_with_extension.as_path().as_os_str(), "/home/foo/bar.txt");
let abs_path_with_extension = abs_path.with_extension("txt").with_extension("tgz");
assert_eq!(abs_path_with_extension.as_path().as_os_str(), "/home/foo/bar.tgz");
// abs_path is not changed
assert_eq!(abs_path.as_path().as_os_str(), "/home/foo/bar");
}
#[test]
#[cfg(windows)]
fn with_extension() {
let abs_path = AbsolutePath::new(Path::new("C:\\home\\foo\\bar")).unwrap();
let abs_path_with_extension = abs_path.with_extension("txt");
assert_eq!(abs_path_with_extension.as_path().as_os_str(), "C:\\home\\foo\\bar.txt");
let abs_path_with_extension = abs_path.with_extension("txt").with_extension("tgz");
assert_eq!(abs_path_with_extension.as_path().as_os_str(), "C:\\home\\foo\\bar.tgz");
// abs_path is not changed
assert_eq!(abs_path.as_path().as_os_str(), "C:\\home\\foo\\bar");
}
}