]>
Commit | Line | Data |
---|---|---|
85aaf69f SL |
1 | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT |
2 | // file at the top-level directory of this distribution and at | |
3 | // http://rust-lang.org/COPYRIGHT. | |
4 | // | |
5 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | |
6 | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | |
7 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | |
8 | // option. This file may not be copied, modified, or distributed | |
9 | // except according to those terms. | |
10 | ||
11 | //! Cross-platform path manipulation. | |
12 | //! | |
32a655c1 SL |
13 | //! This module provides two types, [`PathBuf`] and [`Path`][`Path`] (akin to [`String`] |
14 | //! and [`str`]), for working with paths abstractly. These types are thin wrappers | |
15 | //! around [`OsString`] and [`OsStr`] respectively, meaning that they work directly | |
85aaf69f SL |
16 | //! on strings according to the local platform's path syntax. |
17 | //! | |
18 | //! ## Simple usage | |
19 | //! | |
c34b1796 | 20 | //! Path manipulation includes both parsing components from slices and building |
85aaf69f SL |
21 | //! new owned paths. |
22 | //! | |
32a655c1 | 23 | //! To parse a path, you can create a [`Path`] slice from a [`str`] |
85aaf69f SL |
24 | //! slice and start asking questions: |
25 | //! | |
32a655c1 | 26 | //! ``` |
85aaf69f | 27 | //! use std::path::Path; |
476ff2be | 28 | //! use std::ffi::OsStr; |
85aaf69f SL |
29 | //! |
30 | //! let path = Path::new("/tmp/foo/bar.txt"); | |
476ff2be SL |
31 | //! |
32 | //! let parent = path.parent(); | |
33 | //! assert_eq!(parent, Some(Path::new("/tmp/foo"))); | |
34 | //! | |
35 | //! let file_stem = path.file_stem(); | |
36 | //! assert_eq!(file_stem, Some(OsStr::new("bar"))); | |
37 | //! | |
85aaf69f | 38 | //! let extension = path.extension(); |
476ff2be | 39 | //! assert_eq!(extension, Some(OsStr::new("txt"))); |
85aaf69f SL |
40 | //! ``` |
41 | //! | |
32a655c1 | 42 | //! To build or modify paths, use [`PathBuf`]: |
85aaf69f | 43 | //! |
32a655c1 | 44 | //! ``` |
85aaf69f SL |
45 | //! use std::path::PathBuf; |
46 | //! | |
c34b1796 | 47 | //! let mut path = PathBuf::from("c:\\"); |
85aaf69f SL |
48 | //! path.push("windows"); |
49 | //! path.push("system32"); | |
50 | //! path.set_extension("dll"); | |
51 | //! ``` | |
52 | //! | |
53 | //! ## Path components and normalization | |
54 | //! | |
55 | //! The path APIs are built around the notion of "components", which roughly | |
56 | //! correspond to the substrings between path separators (`/` and, on Windows, | |
57 | //! `\`). The APIs for path parsing are largely specified in terms of the path's | |
92a42be0 SL |
58 | //! components, so it's important to clearly understand how those are |
59 | //! determined. | |
85aaf69f | 60 | //! |
c34b1796 AL |
61 | //! A path can always be reconstructed into an *equivalent* path by |
62 | //! putting together its components via `push`. Syntactically, the | |
63 | //! paths may differ by the normalization described below. | |
85aaf69f SL |
64 | //! |
65 | //! ### Component types | |
66 | //! | |
67 | //! Components come in several types: | |
68 | //! | |
69 | //! * Normal components are the default: standard references to files or | |
70 | //! directories. The path `a/b` has two normal components, `a` and `b`. | |
71 | //! | |
72 | //! * Current directory components represent the `.` character. For example, | |
c34b1796 | 73 | //! `./a` has a current directory component and a normal component `a`. |
85aaf69f SL |
74 | //! |
75 | //! * The root directory component represents a separator that designates | |
76 | //! starting from root. For example, `/a/b` has a root directory component | |
77 | //! followed by normal components `a` and `b`. | |
78 | //! | |
c34b1796 | 79 | //! On Windows, an additional component type comes into play: |
85aaf69f SL |
80 | //! |
81 | //! * Prefix components, of which there is a large variety. For example, `C:` | |
82 | //! and `\\server\share` are prefixes. The path `C:windows` has a prefix | |
83 | //! component `C:` and a normal component `windows`; the path `C:\windows` has a | |
84 | //! prefix component `C:`, a root directory component, and a normal component | |
85 | //! `windows`. | |
86 | //! | |
85aaf69f SL |
87 | //! ### Normalization |
88 | //! | |
89 | //! Aside from splitting on the separator(s), there is a small amount of | |
90 | //! "normalization": | |
91 | //! | |
92 | //! * Repeated separators are ignored: `a/b` and `a//b` both have components `a` | |
93 | //! and `b`. | |
94 | //! | |
c34b1796 AL |
95 | //! * Occurrences of `.` are normalized away, *except* if they are at |
96 | //! the beginning of the path (in which case they are often meaningful | |
97 | //! in terms of path searching). So, for example, `a/./b`, `a/b/`, | |
98 | //! `/a/b/.` and `a/b` all have components `a` and `b`, but `./a/b` | |
99 | //! has a leading current directory component. | |
85aaf69f | 100 | //! |
c34b1796 AL |
101 | //! No other normalization takes place by default. In particular, |
102 | //! `a/c` and `a/b/../c` are distinct, to account for the possibility | |
103 | //! that `b` is a symbolic link (so its parent isn't `a`). Further | |
104 | //! normalization is possible to build on top of the components APIs, | |
105 | //! and will be included in this library in the near future. | |
32a655c1 SL |
106 | //! |
107 | //! [`PathBuf`]: ../../std/path/struct.PathBuf.html | |
108 | //! [`Path`]: ../../std/path/struct.Path.html | |
109 | //! [`String`]: ../../std/string/struct.String.html | |
110 | //! [`str`]: ../../std/primitive.str.html | |
111 | //! [`OsString`]: ../../std/ffi/struct.OsString.html | |
112 | //! [`OsStr`]: ../../std/ffi/struct.OsStr.html | |
85aaf69f | 113 | |
c34b1796 | 114 | #![stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 115 | |
85aaf69f | 116 | use ascii::*; |
9e0c209e | 117 | use borrow::{Borrow, Cow}; |
85aaf69f | 118 | use cmp; |
9cc50fc6 | 119 | use error::Error; |
b039eaaf SL |
120 | use fmt; |
121 | use fs; | |
92a42be0 | 122 | use hash::{Hash, Hasher}; |
b039eaaf | 123 | use io; |
9e0c209e | 124 | use iter::{self, FusedIterator}; |
85aaf69f SL |
125 | use mem; |
126 | use ops::{self, Deref}; | |
85aaf69f | 127 | |
9346a6ac | 128 | use ffi::{OsStr, OsString}; |
85aaf69f | 129 | |
c30ab7b3 | 130 | use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix}; |
85aaf69f SL |
131 | |
132 | //////////////////////////////////////////////////////////////////////////////// | |
133 | // GENERAL NOTES | |
134 | //////////////////////////////////////////////////////////////////////////////// | |
135 | // | |
136 | // Parsing in this module is done by directly transmuting OsStr to [u8] slices, | |
137 | // taking advantage of the fact that OsStr always encodes ASCII characters | |
138 | // as-is. Eventually, this transmutation should be replaced by direct uses of | |
139 | // OsStr APIs for parsing, but it will take a while for those to become | |
140 | // available. | |
141 | ||
85aaf69f SL |
142 | //////////////////////////////////////////////////////////////////////////////// |
143 | // Windows Prefixes | |
144 | //////////////////////////////////////////////////////////////////////////////// | |
145 | ||
146 | /// Path prefixes (Windows only). | |
147 | /// | |
148 | /// Windows uses a variety of path styles, including references to drive | |
62682a34 | 149 | /// volumes (like `C:`), network shared folders (like `\\server\share`) and |
85aaf69f SL |
150 | /// others. In addition, some path prefixes are "verbatim", in which case |
151 | /// `/` is *not* treated as a separator and essentially no normalization is | |
152 | /// performed. | |
153 | #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] | |
c34b1796 | 154 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
155 | pub enum Prefix<'a> { |
156 | /// Prefix `\\?\`, together with the given component immediately following it. | |
c34b1796 | 157 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 158 | Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr), |
85aaf69f SL |
159 | |
160 | /// Prefix `\\?\UNC\`, with the "server" and "share" components following it. | |
c34b1796 | 161 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 162 | VerbatimUNC( |
7453a54e SL |
163 | #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr, |
164 | #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr, | |
9cc50fc6 | 165 | ), |
85aaf69f SL |
166 | |
167 | /// Prefix like `\\?\C:\`, for the given drive letter | |
c34b1796 | 168 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 169 | VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8), |
85aaf69f SL |
170 | |
171 | /// Prefix `\\.\`, together with the given component immediately following it. | |
c34b1796 | 172 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 173 | DeviceNS(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr), |
85aaf69f SL |
174 | |
175 | /// Prefix `\\server\share`, with the given "server" and "share" components. | |
c34b1796 | 176 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 177 | UNC( |
7453a54e SL |
178 | #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr, |
179 | #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr, | |
9cc50fc6 | 180 | ), |
85aaf69f SL |
181 | |
182 | /// Prefix `C:` for the given disk drive. | |
c34b1796 | 183 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 184 | Disk(#[stable(feature = "rust1", since = "1.0.0")] u8), |
85aaf69f SL |
185 | } |
186 | ||
187 | impl<'a> Prefix<'a> { | |
188 | #[inline] | |
189 | fn len(&self) -> usize { | |
190 | use self::Prefix::*; | |
191 | fn os_str_len(s: &OsStr) -> usize { | |
192 | os_str_as_u8_slice(s).len() | |
193 | } | |
194 | match *self { | |
195 | Verbatim(x) => 4 + os_str_len(x), | |
92a42be0 SL |
196 | VerbatimUNC(x, y) => { |
197 | 8 + os_str_len(x) + | |
198 | if os_str_len(y) > 0 { | |
199 | 1 + os_str_len(y) | |
200 | } else { | |
201 | 0 | |
202 | } | |
203 | }, | |
85aaf69f | 204 | VerbatimDisk(_) => 6, |
92a42be0 SL |
205 | UNC(x, y) => { |
206 | 2 + os_str_len(x) + | |
207 | if os_str_len(y) > 0 { | |
208 | 1 + os_str_len(y) | |
209 | } else { | |
210 | 0 | |
211 | } | |
212 | }, | |
85aaf69f | 213 | DeviceNS(x) => 4 + os_str_len(x), |
92a42be0 | 214 | Disk(_) => 2, |
85aaf69f SL |
215 | } |
216 | ||
217 | } | |
218 | ||
62682a34 | 219 | /// Determines if the prefix is verbatim, i.e. begins with `\\?\`. |
85aaf69f | 220 | #[inline] |
c34b1796 | 221 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
222 | pub fn is_verbatim(&self) -> bool { |
223 | use self::Prefix::*; | |
224 | match *self { | |
9e0c209e | 225 | Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true, |
62682a34 | 226 | _ => false, |
85aaf69f SL |
227 | } |
228 | } | |
229 | ||
230 | #[inline] | |
231 | fn is_drive(&self) -> bool { | |
232 | match *self { | |
233 | Prefix::Disk(_) => true, | |
234 | _ => false, | |
235 | } | |
236 | } | |
237 | ||
238 | #[inline] | |
239 | fn has_implicit_root(&self) -> bool { | |
240 | !self.is_drive() | |
241 | } | |
242 | } | |
243 | ||
244 | //////////////////////////////////////////////////////////////////////////////// | |
245 | // Exposed parsing helpers | |
246 | //////////////////////////////////////////////////////////////////////////////// | |
247 | ||
9346a6ac | 248 | /// Determines whether the character is one of the permitted path |
85aaf69f | 249 | /// separators for the current platform. |
c34b1796 AL |
250 | /// |
251 | /// # Examples | |
252 | /// | |
253 | /// ``` | |
254 | /// use std::path; | |
255 | /// | |
256 | /// assert!(path::is_separator('/')); | |
257 | /// assert!(!path::is_separator('❤')); | |
258 | /// ``` | |
259 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f | 260 | pub fn is_separator(c: char) -> bool { |
85aaf69f SL |
261 | c.is_ascii() && is_sep_byte(c as u8) |
262 | } | |
263 | ||
476ff2be SL |
264 | /// The primary separator of path components for the current platform. |
265 | /// | |
266 | /// For example, `/` on Unix and `\` on Windows. | |
c34b1796 | 267 | #[stable(feature = "rust1", since = "1.0.0")] |
c30ab7b3 | 268 | pub const MAIN_SEPARATOR: char = ::sys::path::MAIN_SEP; |
85aaf69f SL |
269 | |
270 | //////////////////////////////////////////////////////////////////////////////// | |
271 | // Misc helpers | |
272 | //////////////////////////////////////////////////////////////////////////////// | |
273 | ||
274 | // Iterate through `iter` while it matches `prefix`; return `None` if `prefix` | |
275 | // is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving | |
276 | // `iter` after having exhausted `prefix`. | |
92a42be0 SL |
277 | fn iter_after<A, I, J>(mut iter: I, mut prefix: J) -> Option<I> |
278 | where I: Iterator<Item = A> + Clone, | |
279 | J: Iterator<Item = A>, | |
280 | A: PartialEq | |
85aaf69f SL |
281 | { |
282 | loop { | |
283 | let mut iter_next = iter.clone(); | |
284 | match (iter_next.next(), prefix.next()) { | |
7453a54e SL |
285 | (Some(ref x), Some(ref y)) if x == y => (), |
286 | (Some(_), Some(_)) => return None, | |
85aaf69f SL |
287 | (Some(_), None) => return Some(iter), |
288 | (None, None) => return Some(iter), | |
289 | (None, Some(_)) => return None, | |
290 | } | |
291 | iter = iter_next; | |
292 | } | |
293 | } | |
294 | ||
295 | // See note at the top of this module to understand why these are used: | |
296 | fn os_str_as_u8_slice(s: &OsStr) -> &[u8] { | |
297 | unsafe { mem::transmute(s) } | |
298 | } | |
299 | unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr { | |
300 | mem::transmute(s) | |
301 | } | |
302 | ||
303 | //////////////////////////////////////////////////////////////////////////////// | |
c34b1796 | 304 | // Cross-platform, iterator-independent parsing |
85aaf69f SL |
305 | //////////////////////////////////////////////////////////////////////////////// |
306 | ||
85aaf69f SL |
307 | /// Says whether the first byte after the prefix is a separator. |
308 | fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool { | |
92a42be0 SL |
309 | let path = if let Some(p) = prefix { |
310 | &s[p.len()..] | |
311 | } else { | |
312 | s | |
313 | }; | |
9346a6ac | 314 | !path.is_empty() && is_sep_byte(path[0]) |
85aaf69f SL |
315 | } |
316 | ||
85aaf69f | 317 | // basic workhorse for splitting stem and extension |
85aaf69f SL |
318 | fn split_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) { |
319 | unsafe { | |
92a42be0 SL |
320 | if os_str_as_u8_slice(file) == b".." { |
321 | return (Some(file), None); | |
322 | } | |
85aaf69f SL |
323 | |
324 | // The unsafety here stems from converting between &OsStr and &[u8] | |
325 | // and back. This is safe to do because (1) we only look at ASCII | |
326 | // contents of the encoding and (2) new &OsStr values are produced | |
327 | // only from ASCII-bounded slices of existing &OsStr values. | |
328 | ||
c34b1796 | 329 | let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.'); |
85aaf69f SL |
330 | let after = iter.next(); |
331 | let before = iter.next(); | |
332 | if before == Some(b"") { | |
333 | (Some(file), None) | |
334 | } else { | |
335 | (before.map(|s| u8_slice_as_os_str(s)), | |
336 | after.map(|s| u8_slice_as_os_str(s))) | |
337 | } | |
338 | } | |
339 | } | |
340 | ||
341 | //////////////////////////////////////////////////////////////////////////////// | |
342 | // The core iterators | |
343 | //////////////////////////////////////////////////////////////////////////////// | |
344 | ||
345 | /// Component parsing works by a double-ended state machine; the cursors at the | |
346 | /// front and back of the path each keep track of what parts of the path have | |
347 | /// been consumed so far. | |
348 | /// | |
c34b1796 AL |
349 | /// Going front to back, a path is made up of a prefix, a starting |
350 | /// directory component, and a body (of normal components) | |
85aaf69f SL |
351 | #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] |
352 | enum State { | |
353 | Prefix = 0, // c: | |
c34b1796 | 354 | StartDir = 1, // / or . or nothing |
85aaf69f | 355 | Body = 2, // foo/bar/baz |
c34b1796 AL |
356 | Done = 3, |
357 | } | |
358 | ||
a7813a04 | 359 | /// A Windows path prefix, e.g. `C:` or `\\server\share`. |
c34b1796 AL |
360 | /// |
361 | /// Does not occur on Unix. | |
362 | #[stable(feature = "rust1", since = "1.0.0")] | |
92a42be0 | 363 | #[derive(Copy, Clone, Eq, Debug)] |
c34b1796 AL |
364 | pub struct PrefixComponent<'a> { |
365 | /// The prefix as an unparsed `OsStr` slice. | |
366 | raw: &'a OsStr, | |
367 | ||
368 | /// The parsed prefix data. | |
369 | parsed: Prefix<'a>, | |
370 | } | |
371 | ||
372 | impl<'a> PrefixComponent<'a> { | |
373 | /// The parsed prefix data. | |
374 | #[stable(feature = "rust1", since = "1.0.0")] | |
375 | pub fn kind(&self) -> Prefix<'a> { | |
376 | self.parsed | |
377 | } | |
378 | ||
379 | /// The raw `OsStr` slice for this prefix. | |
380 | #[stable(feature = "rust1", since = "1.0.0")] | |
381 | pub fn as_os_str(&self) -> &'a OsStr { | |
382 | self.raw | |
383 | } | |
384 | } | |
385 | ||
386 | #[stable(feature = "rust1", since = "1.0.0")] | |
387 | impl<'a> cmp::PartialEq for PrefixComponent<'a> { | |
388 | fn eq(&self, other: &PrefixComponent<'a>) -> bool { | |
389 | cmp::PartialEq::eq(&self.parsed, &other.parsed) | |
390 | } | |
391 | } | |
392 | ||
393 | #[stable(feature = "rust1", since = "1.0.0")] | |
394 | impl<'a> cmp::PartialOrd for PrefixComponent<'a> { | |
395 | fn partial_cmp(&self, other: &PrefixComponent<'a>) -> Option<cmp::Ordering> { | |
396 | cmp::PartialOrd::partial_cmp(&self.parsed, &other.parsed) | |
397 | } | |
398 | } | |
399 | ||
400 | #[stable(feature = "rust1", since = "1.0.0")] | |
401 | impl<'a> cmp::Ord for PrefixComponent<'a> { | |
402 | fn cmp(&self, other: &PrefixComponent<'a>) -> cmp::Ordering { | |
403 | cmp::Ord::cmp(&self.parsed, &other.parsed) | |
404 | } | |
85aaf69f SL |
405 | } |
406 | ||
92a42be0 SL |
407 | #[stable(feature = "rust1", since = "1.0.0")] |
408 | impl<'a> Hash for PrefixComponent<'a> { | |
409 | fn hash<H: Hasher>(&self, h: &mut H) { | |
410 | self.parsed.hash(h); | |
411 | } | |
412 | } | |
413 | ||
85aaf69f SL |
414 | /// A single component of a path. |
415 | /// | |
416 | /// See the module documentation for an in-depth explanation of components and | |
417 | /// their role in the API. | |
3157f602 XL |
418 | /// |
419 | /// This `enum` is created from iterating over the [`path::Components`] | |
420 | /// `struct`. | |
421 | /// | |
422 | /// # Examples | |
423 | /// | |
424 | /// ```rust | |
425 | /// use std::path::{Component, Path}; | |
426 | /// | |
427 | /// let path = Path::new("/tmp/foo/bar.txt"); | |
428 | /// let components = path.components().collect::<Vec<_>>(); | |
429 | /// assert_eq!(&components, &[ | |
430 | /// Component::RootDir, | |
431 | /// Component::Normal("tmp".as_ref()), | |
432 | /// Component::Normal("foo".as_ref()), | |
433 | /// Component::Normal("bar.txt".as_ref()), | |
434 | /// ]); | |
435 | /// ``` | |
436 | /// | |
437 | /// [`path::Components`]: struct.Components.html | |
85aaf69f | 438 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] |
c34b1796 | 439 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 440 | pub enum Component<'a> { |
a7813a04 | 441 | /// A Windows path prefix, e.g. `C:` or `\\server\share`. |
85aaf69f SL |
442 | /// |
443 | /// Does not occur on Unix. | |
c34b1796 | 444 | #[stable(feature = "rust1", since = "1.0.0")] |
9cc50fc6 | 445 | Prefix( |
7453a54e | 446 | #[stable(feature = "rust1", since = "1.0.0")] PrefixComponent<'a> |
9cc50fc6 | 447 | ), |
85aaf69f SL |
448 | |
449 | /// The root directory component, appears after any prefix and before anything else | |
c34b1796 | 450 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
451 | RootDir, |
452 | ||
453 | /// A reference to the current directory, i.e. `.` | |
c34b1796 | 454 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
455 | CurDir, |
456 | ||
457 | /// A reference to the parent directory, i.e. `..` | |
c34b1796 | 458 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
459 | ParentDir, |
460 | ||
461 | /// A normal component, i.e. `a` and `b` in `a/b` | |
c34b1796 | 462 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 463 | Normal(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr), |
85aaf69f SL |
464 | } |
465 | ||
466 | impl<'a> Component<'a> { | |
476ff2be SL |
467 | /// Extracts the underlying `OsStr` slice. |
468 | /// | |
469 | /// # Examples | |
470 | /// | |
471 | /// ``` | |
472 | /// use std::path::Path; | |
473 | /// | |
474 | /// let path = Path::new("./tmp/foo/bar.txt"); | |
475 | /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect(); | |
476 | /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]); | |
477 | /// ``` | |
c34b1796 | 478 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
479 | pub fn as_os_str(self) -> &'a OsStr { |
480 | match self { | |
c34b1796 AL |
481 | Component::Prefix(p) => p.as_os_str(), |
482 | Component::RootDir => OsStr::new(MAIN_SEP_STR), | |
483 | Component::CurDir => OsStr::new("."), | |
484 | Component::ParentDir => OsStr::new(".."), | |
85aaf69f SL |
485 | Component::Normal(path) => path, |
486 | } | |
487 | } | |
488 | } | |
489 | ||
c34b1796 AL |
490 | #[stable(feature = "rust1", since = "1.0.0")] |
491 | impl<'a> AsRef<OsStr> for Component<'a> { | |
492 | fn as_ref(&self) -> &OsStr { | |
493 | self.as_os_str() | |
494 | } | |
495 | } | |
496 | ||
85aaf69f SL |
497 | /// The core iterator giving the components of a path. |
498 | /// | |
499 | /// See the module documentation for an in-depth explanation of components and | |
500 | /// their role in the API. | |
c34b1796 | 501 | /// |
3157f602 XL |
502 | /// This `struct` is created by the [`path::Path::components`] method. |
503 | /// | |
c34b1796 AL |
504 | /// # Examples |
505 | /// | |
506 | /// ``` | |
507 | /// use std::path::Path; | |
508 | /// | |
509 | /// let path = Path::new("/tmp/foo/bar.txt"); | |
510 | /// | |
511 | /// for component in path.components() { | |
512 | /// println!("{:?}", component); | |
513 | /// } | |
514 | /// ``` | |
3157f602 XL |
515 | /// |
516 | /// [`path::Path::components`]: struct.Path.html#method.components | |
85aaf69f | 517 | #[derive(Clone)] |
c34b1796 | 518 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
519 | pub struct Components<'a> { |
520 | // The path left to parse components from | |
521 | path: &'a [u8], | |
522 | ||
523 | // The prefix as it was originally parsed, if any | |
524 | prefix: Option<Prefix<'a>>, | |
525 | ||
526 | // true if path *physically* has a root separator; for most Windows | |
527 | // prefixes, it may have a "logical" rootseparator for the purposes of | |
528 | // normalization, e.g. \\server\share == \\server\share\. | |
529 | has_physical_root: bool, | |
530 | ||
531 | // The iterator is double-ended, and these two states keep track of what has | |
532 | // been produced from either end | |
533 | front: State, | |
534 | back: State, | |
535 | } | |
536 | ||
32a655c1 SL |
537 | /// An iterator over the components of a path, as [`OsStr`] slices. |
538 | /// | |
539 | /// [`OsStr`]: ../../std/ffi/struct.OsStr.html | |
85aaf69f | 540 | #[derive(Clone)] |
c34b1796 | 541 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 542 | pub struct Iter<'a> { |
92a42be0 | 543 | inner: Components<'a>, |
85aaf69f SL |
544 | } |
545 | ||
9e0c209e SL |
546 | #[stable(feature = "path_components_debug", since = "1.13.0")] |
547 | impl<'a> fmt::Debug for Components<'a> { | |
548 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
549 | struct DebugHelper<'a>(&'a Path); | |
550 | ||
551 | impl<'a> fmt::Debug for DebugHelper<'a> { | |
552 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
553 | f.debug_list() | |
554 | .entries(self.0.components()) | |
555 | .finish() | |
556 | } | |
557 | } | |
558 | ||
559 | f.debug_tuple("Components") | |
560 | .field(&DebugHelper(self.as_path())) | |
561 | .finish() | |
562 | } | |
563 | } | |
564 | ||
85aaf69f SL |
565 | impl<'a> Components<'a> { |
566 | // how long is the prefix, if any? | |
567 | #[inline] | |
568 | fn prefix_len(&self) -> usize { | |
569 | self.prefix.as_ref().map(Prefix::len).unwrap_or(0) | |
570 | } | |
571 | ||
572 | #[inline] | |
573 | fn prefix_verbatim(&self) -> bool { | |
574 | self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false) | |
575 | } | |
576 | ||
577 | /// how much of the prefix is left from the point of view of iteration? | |
578 | #[inline] | |
579 | fn prefix_remaining(&self) -> usize { | |
e9174d1e SL |
580 | if self.front == State::Prefix { |
581 | self.prefix_len() | |
582 | } else { | |
583 | 0 | |
584 | } | |
85aaf69f SL |
585 | } |
586 | ||
c34b1796 AL |
587 | // Given the iteration so far, how much of the pre-State::Body path is left? |
588 | #[inline] | |
589 | fn len_before_body(&self) -> usize { | |
92a42be0 SL |
590 | let root = if self.front <= State::StartDir && self.has_physical_root { |
591 | 1 | |
592 | } else { | |
593 | 0 | |
594 | }; | |
595 | let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { | |
596 | 1 | |
597 | } else { | |
598 | 0 | |
599 | }; | |
c34b1796 | 600 | self.prefix_remaining() + root + cur_dir |
85aaf69f SL |
601 | } |
602 | ||
603 | // is the iteration complete? | |
604 | #[inline] | |
605 | fn finished(&self) -> bool { | |
606 | self.front == State::Done || self.back == State::Done || self.front > self.back | |
607 | } | |
608 | ||
609 | #[inline] | |
610 | fn is_sep_byte(&self, b: u8) -> bool { | |
611 | if self.prefix_verbatim() { | |
612 | is_verbatim_sep(b) | |
613 | } else { | |
614 | is_sep_byte(b) | |
615 | } | |
616 | } | |
617 | ||
9346a6ac | 618 | /// Extracts a slice corresponding to the portion of the path remaining for iteration. |
c34b1796 AL |
619 | /// |
620 | /// # Examples | |
621 | /// | |
622 | /// ``` | |
623 | /// use std::path::Path; | |
624 | /// | |
e9174d1e SL |
625 | /// let mut components = Path::new("/tmp/foo/bar.txt").components(); |
626 | /// components.next(); | |
627 | /// components.next(); | |
c34b1796 | 628 | /// |
e9174d1e | 629 | /// assert_eq!(Path::new("foo/bar.txt"), components.as_path()); |
c34b1796 AL |
630 | /// ``` |
631 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
632 | pub fn as_path(&self) -> &'a Path { |
633 | let mut comps = self.clone(); | |
92a42be0 SL |
634 | if comps.front == State::Body { |
635 | comps.trim_left(); | |
636 | } | |
637 | if comps.back == State::Body { | |
638 | comps.trim_right(); | |
639 | } | |
c34b1796 | 640 | unsafe { Path::from_u8_slice(comps.path) } |
85aaf69f SL |
641 | } |
642 | ||
643 | /// Is the *original* path rooted? | |
644 | fn has_root(&self) -> bool { | |
92a42be0 SL |
645 | if self.has_physical_root { |
646 | return true; | |
647 | } | |
85aaf69f | 648 | if let Some(p) = self.prefix { |
92a42be0 SL |
649 | if p.has_implicit_root() { |
650 | return true; | |
651 | } | |
85aaf69f SL |
652 | } |
653 | false | |
654 | } | |
655 | ||
c34b1796 AL |
656 | /// Should the normalized path include a leading . ? |
657 | fn include_cur_dir(&self) -> bool { | |
92a42be0 SL |
658 | if self.has_root() { |
659 | return false; | |
660 | } | |
c34b1796 AL |
661 | let mut iter = self.path[self.prefix_len()..].iter(); |
662 | match (iter.next(), iter.next()) { | |
663 | (Some(&b'.'), None) => true, | |
664 | (Some(&b'.'), Some(&b)) => self.is_sep_byte(b), | |
92a42be0 | 665 | _ => false, |
c34b1796 AL |
666 | } |
667 | } | |
668 | ||
669 | // parse a given byte sequence into the corresponding path component | |
670 | fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> { | |
671 | match comp { | |
672 | b"." if self.prefix_verbatim() => Some(Component::CurDir), | |
673 | b"." => None, // . components are normalized away, except at | |
674 | // the beginning of a path, which is treated | |
675 | // separately via `include_cur_dir` | |
676 | b".." => Some(Component::ParentDir), | |
677 | b"" => None, | |
92a42be0 | 678 | _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })), |
c34b1796 AL |
679 | } |
680 | } | |
681 | ||
85aaf69f SL |
682 | // parse a component from the left, saying how many bytes to consume to |
683 | // remove the component | |
684 | fn parse_next_component(&self) -> (usize, Option<Component<'a>>) { | |
685 | debug_assert!(self.front == State::Body); | |
686 | let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) { | |
687 | None => (0, self.path), | |
92a42be0 | 688 | Some(i) => (1, &self.path[..i]), |
85aaf69f | 689 | }; |
c34b1796 | 690 | (comp.len() + extra, self.parse_single_component(comp)) |
85aaf69f SL |
691 | } |
692 | ||
693 | // parse a component from the right, saying how many bytes to consume to | |
694 | // remove the component | |
695 | fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) { | |
696 | debug_assert!(self.back == State::Body); | |
c34b1796 | 697 | let start = self.len_before_body(); |
85aaf69f | 698 | let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) { |
92a42be0 SL |
699 | None => (0, &self.path[start..]), |
700 | Some(i) => (1, &self.path[start + i + 1..]), | |
85aaf69f | 701 | }; |
c34b1796 | 702 | (comp.len() + extra, self.parse_single_component(comp)) |
85aaf69f SL |
703 | } |
704 | ||
9346a6ac | 705 | // trim away repeated separators (i.e. empty components) on the left |
85aaf69f SL |
706 | fn trim_left(&mut self) { |
707 | while !self.path.is_empty() { | |
708 | let (size, comp) = self.parse_next_component(); | |
709 | if comp.is_some() { | |
710 | return; | |
711 | } else { | |
92a42be0 | 712 | self.path = &self.path[size..]; |
85aaf69f SL |
713 | } |
714 | } | |
715 | } | |
716 | ||
9346a6ac | 717 | // trim away repeated separators (i.e. empty components) on the right |
85aaf69f | 718 | fn trim_right(&mut self) { |
c34b1796 | 719 | while self.path.len() > self.len_before_body() { |
85aaf69f SL |
720 | let (size, comp) = self.parse_next_component_back(); |
721 | if comp.is_some() { | |
722 | return; | |
723 | } else { | |
92a42be0 | 724 | self.path = &self.path[..self.path.len() - size]; |
85aaf69f SL |
725 | } |
726 | } | |
727 | } | |
85aaf69f SL |
728 | } |
729 | ||
c34b1796 AL |
730 | #[stable(feature = "rust1", since = "1.0.0")] |
731 | impl<'a> AsRef<Path> for Components<'a> { | |
732 | fn as_ref(&self) -> &Path { | |
733 | self.as_path() | |
734 | } | |
735 | } | |
736 | ||
737 | #[stable(feature = "rust1", since = "1.0.0")] | |
738 | impl<'a> AsRef<OsStr> for Components<'a> { | |
739 | fn as_ref(&self) -> &OsStr { | |
740 | self.as_path().as_os_str() | |
741 | } | |
742 | } | |
743 | ||
9e0c209e SL |
744 | #[stable(feature = "path_iter_debug", since = "1.13.0")] |
745 | impl<'a> fmt::Debug for Iter<'a> { | |
746 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
747 | struct DebugHelper<'a>(&'a Path); | |
748 | ||
749 | impl<'a> fmt::Debug for DebugHelper<'a> { | |
750 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
751 | f.debug_list() | |
752 | .entries(self.0.iter()) | |
753 | .finish() | |
754 | } | |
755 | } | |
756 | ||
757 | f.debug_tuple("Iter") | |
758 | .field(&DebugHelper(self.as_path())) | |
759 | .finish() | |
760 | } | |
761 | } | |
762 | ||
85aaf69f | 763 | impl<'a> Iter<'a> { |
9346a6ac | 764 | /// Extracts a slice corresponding to the portion of the path remaining for iteration. |
c34b1796 | 765 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
766 | pub fn as_path(&self) -> &'a Path { |
767 | self.inner.as_path() | |
768 | } | |
769 | } | |
770 | ||
c34b1796 AL |
771 | #[stable(feature = "rust1", since = "1.0.0")] |
772 | impl<'a> AsRef<Path> for Iter<'a> { | |
773 | fn as_ref(&self) -> &Path { | |
774 | self.as_path() | |
775 | } | |
776 | } | |
777 | ||
778 | #[stable(feature = "rust1", since = "1.0.0")] | |
779 | impl<'a> AsRef<OsStr> for Iter<'a> { | |
780 | fn as_ref(&self) -> &OsStr { | |
781 | self.as_path().as_os_str() | |
782 | } | |
783 | } | |
784 | ||
785 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
786 | impl<'a> Iterator for Iter<'a> { |
787 | type Item = &'a OsStr; | |
788 | ||
789 | fn next(&mut self) -> Option<&'a OsStr> { | |
790 | self.inner.next().map(Component::as_os_str) | |
791 | } | |
792 | } | |
793 | ||
c34b1796 | 794 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
795 | impl<'a> DoubleEndedIterator for Iter<'a> { |
796 | fn next_back(&mut self) -> Option<&'a OsStr> { | |
797 | self.inner.next_back().map(Component::as_os_str) | |
798 | } | |
799 | } | |
800 | ||
9e0c209e SL |
801 | #[unstable(feature = "fused", issue = "35602")] |
802 | impl<'a> FusedIterator for Iter<'a> {} | |
803 | ||
c34b1796 | 804 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
805 | impl<'a> Iterator for Components<'a> { |
806 | type Item = Component<'a>; | |
807 | ||
808 | fn next(&mut self) -> Option<Component<'a>> { | |
809 | while !self.finished() { | |
810 | match self.front { | |
811 | State::Prefix if self.prefix_len() > 0 => { | |
c34b1796 | 812 | self.front = State::StartDir; |
85aaf69f | 813 | debug_assert!(self.prefix_len() <= self.path.len()); |
92a42be0 SL |
814 | let raw = &self.path[..self.prefix_len()]; |
815 | self.path = &self.path[self.prefix_len()..]; | |
c34b1796 | 816 | return Some(Component::Prefix(PrefixComponent { |
85aaf69f | 817 | raw: unsafe { u8_slice_as_os_str(raw) }, |
92a42be0 SL |
818 | parsed: self.prefix.unwrap(), |
819 | })); | |
85aaf69f SL |
820 | } |
821 | State::Prefix => { | |
c34b1796 | 822 | self.front = State::StartDir; |
85aaf69f | 823 | } |
c34b1796 | 824 | State::StartDir => { |
85aaf69f SL |
825 | self.front = State::Body; |
826 | if self.has_physical_root { | |
9346a6ac | 827 | debug_assert!(!self.path.is_empty()); |
85aaf69f | 828 | self.path = &self.path[1..]; |
92a42be0 | 829 | return Some(Component::RootDir); |
85aaf69f SL |
830 | } else if let Some(p) = self.prefix { |
831 | if p.has_implicit_root() && !p.is_verbatim() { | |
92a42be0 | 832 | return Some(Component::RootDir); |
85aaf69f | 833 | } |
c34b1796 | 834 | } else if self.include_cur_dir() { |
9346a6ac | 835 | debug_assert!(!self.path.is_empty()); |
c34b1796 | 836 | self.path = &self.path[1..]; |
92a42be0 | 837 | return Some(Component::CurDir); |
85aaf69f SL |
838 | } |
839 | } | |
840 | State::Body if !self.path.is_empty() => { | |
841 | let (size, comp) = self.parse_next_component(); | |
92a42be0 SL |
842 | self.path = &self.path[size..]; |
843 | if comp.is_some() { | |
844 | return comp; | |
845 | } | |
85aaf69f SL |
846 | } |
847 | State::Body => { | |
85aaf69f | 848 | self.front = State::Done; |
85aaf69f | 849 | } |
92a42be0 | 850 | State::Done => unreachable!(), |
85aaf69f SL |
851 | } |
852 | } | |
853 | None | |
854 | } | |
855 | } | |
856 | ||
c34b1796 | 857 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
858 | impl<'a> DoubleEndedIterator for Components<'a> { |
859 | fn next_back(&mut self) -> Option<Component<'a>> { | |
860 | while !self.finished() { | |
861 | match self.back { | |
c34b1796 | 862 | State::Body if self.path.len() > self.len_before_body() => { |
85aaf69f | 863 | let (size, comp) = self.parse_next_component_back(); |
92a42be0 SL |
864 | self.path = &self.path[..self.path.len() - size]; |
865 | if comp.is_some() { | |
866 | return comp; | |
867 | } | |
85aaf69f SL |
868 | } |
869 | State::Body => { | |
c34b1796 | 870 | self.back = State::StartDir; |
85aaf69f | 871 | } |
c34b1796 | 872 | State::StartDir => { |
85aaf69f SL |
873 | self.back = State::Prefix; |
874 | if self.has_physical_root { | |
92a42be0 SL |
875 | self.path = &self.path[..self.path.len() - 1]; |
876 | return Some(Component::RootDir); | |
85aaf69f SL |
877 | } else if let Some(p) = self.prefix { |
878 | if p.has_implicit_root() && !p.is_verbatim() { | |
92a42be0 | 879 | return Some(Component::RootDir); |
85aaf69f | 880 | } |
c34b1796 | 881 | } else if self.include_cur_dir() { |
92a42be0 SL |
882 | self.path = &self.path[..self.path.len() - 1]; |
883 | return Some(Component::CurDir); | |
85aaf69f SL |
884 | } |
885 | } | |
886 | State::Prefix if self.prefix_len() > 0 => { | |
887 | self.back = State::Done; | |
c34b1796 | 888 | return Some(Component::Prefix(PrefixComponent { |
85aaf69f | 889 | raw: unsafe { u8_slice_as_os_str(self.path) }, |
92a42be0 SL |
890 | parsed: self.prefix.unwrap(), |
891 | })); | |
85aaf69f SL |
892 | } |
893 | State::Prefix => { | |
894 | self.back = State::Done; | |
92a42be0 | 895 | return None; |
85aaf69f | 896 | } |
92a42be0 | 897 | State::Done => unreachable!(), |
85aaf69f SL |
898 | } |
899 | } | |
900 | None | |
901 | } | |
902 | } | |
903 | ||
9e0c209e SL |
904 | #[unstable(feature = "fused", issue = "35602")] |
905 | impl<'a> FusedIterator for Components<'a> {} | |
906 | ||
c34b1796 | 907 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
908 | impl<'a> cmp::PartialEq for Components<'a> { |
909 | fn eq(&self, other: &Components<'a>) -> bool { | |
e9174d1e | 910 | Iterator::eq(self.clone(), other.clone()) |
85aaf69f SL |
911 | } |
912 | } | |
913 | ||
c34b1796 | 914 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
915 | impl<'a> cmp::Eq for Components<'a> {} |
916 | ||
c34b1796 | 917 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
918 | impl<'a> cmp::PartialOrd for Components<'a> { |
919 | fn partial_cmp(&self, other: &Components<'a>) -> Option<cmp::Ordering> { | |
e9174d1e | 920 | Iterator::partial_cmp(self.clone(), other.clone()) |
85aaf69f SL |
921 | } |
922 | } | |
923 | ||
c34b1796 | 924 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
925 | impl<'a> cmp::Ord for Components<'a> { |
926 | fn cmp(&self, other: &Components<'a>) -> cmp::Ordering { | |
e9174d1e | 927 | Iterator::cmp(self.clone(), other.clone()) |
85aaf69f SL |
928 | } |
929 | } | |
930 | ||
931 | //////////////////////////////////////////////////////////////////////////////// | |
932 | // Basic types and traits | |
933 | //////////////////////////////////////////////////////////////////////////////// | |
934 | ||
9e0c209e SL |
935 | /// An owned, mutable path (akin to [`String`]). |
936 | /// | |
937 | /// This type provides methods like [`push`] and [`set_extension`] that mutate | |
938 | /// the path in place. It also implements [`Deref`] to [`Path`], meaning that | |
939 | /// all methods on [`Path`] slices are available on `PathBuf` values as well. | |
85aaf69f | 940 | /// |
9e0c209e SL |
941 | /// [`String`]: ../string/struct.String.html |
942 | /// [`Path`]: struct.Path.html | |
943 | /// [`push`]: struct.PathBuf.html#method.push | |
944 | /// [`set_extension`]: struct.PathBuf.html#method.set_extension | |
c30ab7b3 | 945 | /// [`Deref`]: ../ops/trait.Deref.html |
85aaf69f SL |
946 | /// |
947 | /// More details about the overall approach can be found in | |
948 | /// the module documentation. | |
949 | /// | |
c34b1796 | 950 | /// # Examples |
85aaf69f | 951 | /// |
c34b1796 | 952 | /// ``` |
85aaf69f SL |
953 | /// use std::path::PathBuf; |
954 | /// | |
c34b1796 | 955 | /// let mut path = PathBuf::from("c:\\"); |
85aaf69f SL |
956 | /// path.push("windows"); |
957 | /// path.push("system32"); | |
958 | /// path.set_extension("dll"); | |
959 | /// ``` | |
92a42be0 | 960 | #[derive(Clone)] |
c34b1796 | 961 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 962 | pub struct PathBuf { |
92a42be0 | 963 | inner: OsString, |
85aaf69f SL |
964 | } |
965 | ||
966 | impl PathBuf { | |
967 | fn as_mut_vec(&mut self) -> &mut Vec<u8> { | |
e9174d1e | 968 | unsafe { &mut *(self as *mut PathBuf as *mut Vec<u8>) } |
85aaf69f SL |
969 | } |
970 | ||
9346a6ac | 971 | /// Allocates an empty `PathBuf`. |
9e0c209e SL |
972 | /// |
973 | /// # Examples | |
974 | /// | |
975 | /// ``` | |
976 | /// use std::path::PathBuf; | |
977 | /// | |
978 | /// let path = PathBuf::new(); | |
979 | /// ``` | |
c34b1796 AL |
980 | #[stable(feature = "rust1", since = "1.0.0")] |
981 | pub fn new() -> PathBuf { | |
982 | PathBuf { inner: OsString::new() } | |
983 | } | |
984 | ||
9e0c209e SL |
985 | /// Coerces to a [`Path`] slice. |
986 | /// | |
987 | /// [`Path`]: struct.Path.html | |
988 | /// | |
989 | /// # Examples | |
990 | /// | |
991 | /// ``` | |
992 | /// use std::path::{Path, PathBuf}; | |
993 | /// | |
994 | /// let p = PathBuf::from("/test"); | |
995 | /// assert_eq!(Path::new("/test"), p.as_path()); | |
996 | /// ``` | |
c34b1796 AL |
997 | #[stable(feature = "rust1", since = "1.0.0")] |
998 | pub fn as_path(&self) -> &Path { | |
999 | self | |
85aaf69f SL |
1000 | } |
1001 | ||
9346a6ac | 1002 | /// Extends `self` with `path`. |
85aaf69f SL |
1003 | /// |
1004 | /// If `path` is absolute, it replaces the current path. | |
1005 | /// | |
1006 | /// On Windows: | |
1007 | /// | |
1008 | /// * if `path` has a root but no prefix (e.g. `\windows`), it | |
1009 | /// replaces everything except for the prefix (if any) of `self`. | |
e9174d1e | 1010 | /// * if `path` has a prefix but no root, it replaces `self`. |
92a42be0 SL |
1011 | /// |
1012 | /// # Examples | |
1013 | /// | |
476ff2be SL |
1014 | /// Pushing a relative path extends the existing path: |
1015 | /// | |
92a42be0 SL |
1016 | /// ``` |
1017 | /// use std::path::PathBuf; | |
1018 | /// | |
476ff2be | 1019 | /// let mut path = PathBuf::from("/tmp"); |
92a42be0 SL |
1020 | /// path.push("file.bk"); |
1021 | /// assert_eq!(path, PathBuf::from("/tmp/file.bk")); | |
476ff2be SL |
1022 | /// ``` |
1023 | /// | |
1024 | /// Pushing an absolute path replaces the existing path: | |
1025 | /// | |
1026 | /// ``` | |
1027 | /// use std::path::PathBuf; | |
92a42be0 | 1028 | /// |
476ff2be SL |
1029 | /// let mut path = PathBuf::from("/tmp"); |
1030 | /// path.push("/etc"); | |
1031 | /// assert_eq!(path, PathBuf::from("/etc")); | |
92a42be0 | 1032 | /// ``` |
c34b1796 AL |
1033 | #[stable(feature = "rust1", since = "1.0.0")] |
1034 | pub fn push<P: AsRef<Path>>(&mut self, path: P) { | |
e9174d1e SL |
1035 | self._push(path.as_ref()) |
1036 | } | |
c34b1796 | 1037 | |
e9174d1e | 1038 | fn _push(&mut self, path: &Path) { |
85aaf69f SL |
1039 | // in general, a separator is needed if the rightmost byte is not a separator |
1040 | let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false); | |
1041 | ||
1042 | // in the special case of `C:` on Windows, do *not* add a separator | |
1043 | { | |
1044 | let comps = self.components(); | |
92a42be0 SL |
1045 | if comps.prefix_len() > 0 && comps.prefix_len() == comps.path.len() && |
1046 | comps.prefix.unwrap().is_drive() { | |
85aaf69f SL |
1047 | need_sep = false |
1048 | } | |
1049 | } | |
1050 | ||
85aaf69f SL |
1051 | // absolute `path` replaces `self` |
1052 | if path.is_absolute() || path.prefix().is_some() { | |
1053 | self.as_mut_vec().truncate(0); | |
1054 | ||
1055 | // `path` has a root but no prefix, e.g. `\windows` (Windows only) | |
1056 | } else if path.has_root() { | |
1057 | let prefix_len = self.components().prefix_remaining(); | |
1058 | self.as_mut_vec().truncate(prefix_len); | |
1059 | ||
1060 | // `path` is a pure relative path | |
1061 | } else if need_sep { | |
c34b1796 | 1062 | self.inner.push(MAIN_SEP_STR); |
85aaf69f SL |
1063 | } |
1064 | ||
c34b1796 | 1065 | self.inner.push(path); |
85aaf69f SL |
1066 | } |
1067 | ||
9e0c209e | 1068 | /// Truncate `self` to [`self.parent()`]. |
85aaf69f | 1069 | /// |
9e0c209e | 1070 | /// Returns false and does nothing if [`self.file_name()`] is `None`. |
85aaf69f | 1071 | /// Otherwise, returns `true`. |
9e0c209e SL |
1072 | /// |
1073 | /// [`self.parent()`]: struct.PathBuf.html#method.parent | |
1074 | /// [`self.file_name()`]: struct.PathBuf.html#method.file_name | |
1075 | /// | |
1076 | /// # Examples | |
1077 | /// | |
1078 | /// ``` | |
1079 | /// use std::path::{Path, PathBuf}; | |
1080 | /// | |
1081 | /// let mut p = PathBuf::from("/test/test.rs"); | |
1082 | /// | |
1083 | /// p.pop(); | |
1084 | /// assert_eq!(Path::new("/test"), p); | |
1085 | /// p.pop(); | |
1086 | /// assert_eq!(Path::new("/"), p); | |
1087 | /// ``` | |
c34b1796 | 1088 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1089 | pub fn pop(&mut self) -> bool { |
1090 | match self.parent().map(|p| p.as_u8_slice().len()) { | |
1091 | Some(len) => { | |
1092 | self.as_mut_vec().truncate(len); | |
1093 | true | |
1094 | } | |
92a42be0 | 1095 | None => false, |
85aaf69f SL |
1096 | } |
1097 | } | |
1098 | ||
9e0c209e | 1099 | /// Updates [`self.file_name()`] to `file_name`. |
85aaf69f | 1100 | /// |
32a655c1 | 1101 | /// If [`self.file_name()`] was [`None`], this is equivalent to pushing |
85aaf69f SL |
1102 | /// `file_name`. |
1103 | /// | |
9e0c209e | 1104 | /// [`self.file_name()`]: struct.PathBuf.html#method.file_name |
32a655c1 | 1105 | /// [`None`]: ../../std/option/enum.Option.html#variant.None |
9e0c209e | 1106 | /// |
85aaf69f SL |
1107 | /// # Examples |
1108 | /// | |
c34b1796 AL |
1109 | /// ``` |
1110 | /// use std::path::PathBuf; | |
85aaf69f | 1111 | /// |
c34b1796 | 1112 | /// let mut buf = PathBuf::from("/"); |
85aaf69f SL |
1113 | /// assert!(buf.file_name() == None); |
1114 | /// buf.set_file_name("bar"); | |
c34b1796 | 1115 | /// assert!(buf == PathBuf::from("/bar")); |
85aaf69f SL |
1116 | /// assert!(buf.file_name().is_some()); |
1117 | /// buf.set_file_name("baz.txt"); | |
c34b1796 | 1118 | /// assert!(buf == PathBuf::from("/baz.txt")); |
85aaf69f | 1119 | /// ``` |
c34b1796 AL |
1120 | #[stable(feature = "rust1", since = "1.0.0")] |
1121 | pub fn set_file_name<S: AsRef<OsStr>>(&mut self, file_name: S) { | |
e9174d1e SL |
1122 | self._set_file_name(file_name.as_ref()) |
1123 | } | |
1124 | ||
1125 | fn _set_file_name(&mut self, file_name: &OsStr) { | |
c34b1796 AL |
1126 | if self.file_name().is_some() { |
1127 | let popped = self.pop(); | |
1128 | debug_assert!(popped); | |
85aaf69f | 1129 | } |
e9174d1e | 1130 | self.push(file_name); |
85aaf69f SL |
1131 | } |
1132 | ||
9e0c209e SL |
1133 | /// Updates [`self.extension()`] to `extension`. |
1134 | /// | |
1135 | /// If [`self.file_name()`] is `None`, does nothing and returns `false`. | |
1136 | /// | |
32a655c1 | 1137 | /// Otherwise, returns `true`; if [`self.extension()`] is [`None`], the |
9e0c209e | 1138 | /// extension is added; otherwise it is replaced. |
85aaf69f | 1139 | /// |
9e0c209e SL |
1140 | /// [`self.file_name()`]: struct.PathBuf.html#method.file_name |
1141 | /// [`self.extension()`]: struct.PathBuf.html#method.extension | |
32a655c1 | 1142 | /// [`None`]: ../../std/option/enum.Option.html#variant.None |
85aaf69f | 1143 | /// |
9e0c209e SL |
1144 | /// # Examples |
1145 | /// | |
1146 | /// ``` | |
1147 | /// use std::path::{Path, PathBuf}; | |
1148 | /// | |
1149 | /// let mut p = PathBuf::from("/feel/the"); | |
1150 | /// | |
1151 | /// p.set_extension("force"); | |
1152 | /// assert_eq!(Path::new("/feel/the.force"), p.as_path()); | |
1153 | /// | |
1154 | /// p.set_extension("dark_side"); | |
1155 | /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path()); | |
1156 | /// ``` | |
c34b1796 AL |
1157 | #[stable(feature = "rust1", since = "1.0.0")] |
1158 | pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool { | |
e9174d1e SL |
1159 | self._set_extension(extension.as_ref()) |
1160 | } | |
1161 | ||
1162 | fn _set_extension(&mut self, extension: &OsStr) -> bool { | |
92a42be0 SL |
1163 | if self.file_name().is_none() { |
1164 | return false; | |
1165 | } | |
85aaf69f SL |
1166 | |
1167 | let mut stem = match self.file_stem() { | |
1168 | Some(stem) => stem.to_os_string(), | |
c34b1796 | 1169 | None => OsString::new(), |
85aaf69f SL |
1170 | }; |
1171 | ||
9346a6ac | 1172 | if !os_str_as_u8_slice(extension).is_empty() { |
c34b1796 AL |
1173 | stem.push("."); |
1174 | stem.push(extension); | |
85aaf69f SL |
1175 | } |
1176 | self.set_file_name(&stem); | |
1177 | ||
1178 | true | |
1179 | } | |
1180 | ||
9e0c209e SL |
1181 | /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage. |
1182 | /// | |
1183 | /// [`OsString`]: ../ffi/struct.OsString.html | |
1184 | /// | |
1185 | /// # Examples | |
1186 | /// | |
1187 | /// ``` | |
1188 | /// use std::path::PathBuf; | |
1189 | /// | |
1190 | /// let p = PathBuf::from("/the/head"); | |
1191 | /// let os_str = p.into_os_string(); | |
1192 | /// ``` | |
c34b1796 | 1193 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1194 | pub fn into_os_string(self) -> OsString { |
1195 | self.inner | |
1196 | } | |
8bb4bdeb XL |
1197 | |
1198 | /// Converts this `PathBuf` into a boxed `Path`. | |
1199 | #[unstable(feature = "into_boxed_path", issue = "0")] | |
1200 | pub fn into_boxed_path(self) -> Box<Path> { | |
1201 | unsafe { mem::transmute(self.inner.into_boxed_os_str()) } | |
1202 | } | |
1203 | } | |
1204 | ||
1205 | #[stable(feature = "box_from_path", since = "1.17.0")] | |
1206 | impl<'a> From<&'a Path> for Box<Path> { | |
1207 | fn from(path: &'a Path) -> Box<Path> { | |
1208 | let boxed: Box<OsStr> = path.inner.into(); | |
1209 | unsafe { mem::transmute(boxed) } | |
1210 | } | |
85aaf69f SL |
1211 | } |
1212 | ||
c34b1796 AL |
1213 | #[stable(feature = "rust1", since = "1.0.0")] |
1214 | impl<'a, T: ?Sized + AsRef<OsStr>> From<&'a T> for PathBuf { | |
1215 | fn from(s: &'a T) -> PathBuf { | |
1216 | PathBuf::from(s.as_ref().to_os_string()) | |
1217 | } | |
1218 | } | |
1219 | ||
1220 | #[stable(feature = "rust1", since = "1.0.0")] | |
1221 | impl From<OsString> for PathBuf { | |
1222 | fn from(s: OsString) -> PathBuf { | |
1223 | PathBuf { inner: s } | |
1224 | } | |
1225 | } | |
1226 | ||
c30ab7b3 SL |
1227 | #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")] |
1228 | impl From<PathBuf> for OsString { | |
1229 | fn from(path_buf : PathBuf) -> OsString { | |
1230 | path_buf.inner | |
1231 | } | |
1232 | } | |
1233 | ||
c34b1796 AL |
1234 | #[stable(feature = "rust1", since = "1.0.0")] |
1235 | impl From<String> for PathBuf { | |
1236 | fn from(s: String) -> PathBuf { | |
1237 | PathBuf::from(OsString::from(s)) | |
1238 | } | |
1239 | } | |
1240 | ||
1241 | #[stable(feature = "rust1", since = "1.0.0")] | |
1242 | impl<P: AsRef<Path>> iter::FromIterator<P> for PathBuf { | |
1243 | fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBuf { | |
1244 | let mut buf = PathBuf::new(); | |
85aaf69f SL |
1245 | buf.extend(iter); |
1246 | buf | |
1247 | } | |
1248 | } | |
1249 | ||
c34b1796 AL |
1250 | #[stable(feature = "rust1", since = "1.0.0")] |
1251 | impl<P: AsRef<Path>> iter::Extend<P> for PathBuf { | |
1252 | fn extend<I: IntoIterator<Item = P>>(&mut self, iter: I) { | |
85aaf69f | 1253 | for p in iter { |
e9174d1e | 1254 | self.push(p.as_ref()) |
85aaf69f SL |
1255 | } |
1256 | } | |
1257 | } | |
1258 | ||
c34b1796 | 1259 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1260 | impl fmt::Debug for PathBuf { |
1261 | fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { | |
1262 | fmt::Debug::fmt(&**self, formatter) | |
1263 | } | |
1264 | } | |
1265 | ||
c34b1796 | 1266 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1267 | impl ops::Deref for PathBuf { |
1268 | type Target = Path; | |
1269 | ||
1270 | fn deref(&self) -> &Path { | |
e9174d1e | 1271 | Path::new(&self.inner) |
85aaf69f SL |
1272 | } |
1273 | } | |
1274 | ||
c34b1796 | 1275 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1276 | impl Borrow<Path> for PathBuf { |
1277 | fn borrow(&self) -> &Path { | |
1278 | self.deref() | |
1279 | } | |
1280 | } | |
1281 | ||
8bb4bdeb XL |
1282 | #[stable(feature = "default_for_pathbuf", since = "1.16.0")] |
1283 | impl Default for PathBuf { | |
1284 | fn default() -> Self { | |
1285 | PathBuf::new() | |
1286 | } | |
1287 | } | |
1288 | ||
92a42be0 SL |
1289 | #[stable(feature = "cow_from_path", since = "1.6.0")] |
1290 | impl<'a> From<&'a Path> for Cow<'a, Path> { | |
1291 | #[inline] | |
1292 | fn from(s: &'a Path) -> Cow<'a, Path> { | |
1293 | Cow::Borrowed(s) | |
1294 | } | |
1295 | } | |
1296 | ||
1297 | #[stable(feature = "cow_from_path", since = "1.6.0")] | |
1298 | impl<'a> From<PathBuf> for Cow<'a, Path> { | |
1299 | #[inline] | |
1300 | fn from(s: PathBuf) -> Cow<'a, Path> { | |
1301 | Cow::Owned(s) | |
1302 | } | |
1303 | } | |
1304 | ||
c34b1796 | 1305 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1306 | impl ToOwned for Path { |
1307 | type Owned = PathBuf; | |
92a42be0 SL |
1308 | fn to_owned(&self) -> PathBuf { |
1309 | self.to_path_buf() | |
1310 | } | |
85aaf69f SL |
1311 | } |
1312 | ||
c34b1796 | 1313 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1314 | impl cmp::PartialEq for PathBuf { |
1315 | fn eq(&self, other: &PathBuf) -> bool { | |
1316 | self.components() == other.components() | |
1317 | } | |
1318 | } | |
1319 | ||
92a42be0 SL |
1320 | #[stable(feature = "rust1", since = "1.0.0")] |
1321 | impl Hash for PathBuf { | |
1322 | fn hash<H: Hasher>(&self, h: &mut H) { | |
1323 | self.as_path().hash(h) | |
1324 | } | |
1325 | } | |
1326 | ||
c34b1796 | 1327 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1328 | impl cmp::Eq for PathBuf {} |
1329 | ||
c34b1796 | 1330 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1331 | impl cmp::PartialOrd for PathBuf { |
1332 | fn partial_cmp(&self, other: &PathBuf) -> Option<cmp::Ordering> { | |
e9174d1e | 1333 | self.components().partial_cmp(other.components()) |
85aaf69f SL |
1334 | } |
1335 | } | |
1336 | ||
c34b1796 | 1337 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1338 | impl cmp::Ord for PathBuf { |
1339 | fn cmp(&self, other: &PathBuf) -> cmp::Ordering { | |
e9174d1e | 1340 | self.components().cmp(other.components()) |
85aaf69f SL |
1341 | } |
1342 | } | |
1343 | ||
c34b1796 AL |
1344 | #[stable(feature = "rust1", since = "1.0.0")] |
1345 | impl AsRef<OsStr> for PathBuf { | |
1346 | fn as_ref(&self) -> &OsStr { | |
1347 | &self.inner[..] | |
1348 | } | |
1349 | } | |
1350 | ||
9e0c209e | 1351 | /// A slice of a path (akin to [`str`]). |
85aaf69f SL |
1352 | /// |
1353 | /// This type supports a number of operations for inspecting a path, including | |
1354 | /// breaking the path into its components (separated by `/` or `\`, depending on | |
1355 | /// the platform), extracting the file name, determining whether the path is | |
c30ab7b3 | 1356 | /// absolute, and so on. |
85aaf69f | 1357 | /// |
d9579d0f | 1358 | /// This is an *unsized* type, meaning that it must always be used behind a |
c30ab7b3 SL |
1359 | /// pointer like `&` or [`Box`]. For an owned version of this type, |
1360 | /// see [`PathBuf`]. | |
9e0c209e SL |
1361 | /// |
1362 | /// [`str`]: ../primitive.str.html | |
1363 | /// [`Box`]: ../boxed/struct.Box.html | |
c30ab7b3 SL |
1364 | /// [`PathBuf`]: struct.PathBuf.html |
1365 | /// | |
1366 | /// More details about the overall approach can be found in | |
1367 | /// the module documentation. | |
85aaf69f | 1368 | /// |
c34b1796 | 1369 | /// # Examples |
85aaf69f | 1370 | /// |
c34b1796 | 1371 | /// ``` |
85aaf69f | 1372 | /// use std::path::Path; |
476ff2be | 1373 | /// use std::ffi::OsStr; |
85aaf69f SL |
1374 | /// |
1375 | /// let path = Path::new("/tmp/foo/bar.txt"); | |
476ff2be SL |
1376 | /// |
1377 | /// let parent = path.parent(); | |
1378 | /// assert_eq!(parent, Some(Path::new("/tmp/foo"))); | |
1379 | /// | |
1380 | /// let file_stem = path.file_stem(); | |
1381 | /// assert_eq!(file_stem, Some(OsStr::new("bar"))); | |
1382 | /// | |
85aaf69f | 1383 | /// let extension = path.extension(); |
476ff2be | 1384 | /// assert_eq!(extension, Some(OsStr::new("txt"))); |
85aaf69f | 1385 | /// ``` |
c34b1796 | 1386 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1387 | pub struct Path { |
92a42be0 | 1388 | inner: OsStr, |
85aaf69f SL |
1389 | } |
1390 | ||
32a655c1 | 1391 | /// An error returned from the [`Path::strip_prefix`] method indicating that the |
9cc50fc6 | 1392 | /// prefix was not found in `self`. |
32a655c1 SL |
1393 | /// |
1394 | /// [`Path::strip_prefix`]: struct.Path.html#method.strip_prefix | |
9cc50fc6 SL |
1395 | #[derive(Debug, Clone, PartialEq, Eq)] |
1396 | #[stable(since = "1.7.0", feature = "strip_prefix")] | |
1397 | pub struct StripPrefixError(()); | |
1398 | ||
85aaf69f SL |
1399 | impl Path { |
1400 | // The following (private!) function allows construction of a path from a u8 | |
1401 | // slice, which is only safe when it is known to follow the OsStr encoding. | |
1402 | unsafe fn from_u8_slice(s: &[u8]) -> &Path { | |
e9174d1e | 1403 | Path::new(u8_slice_as_os_str(s)) |
85aaf69f SL |
1404 | } |
1405 | // The following (private!) function reveals the byte encoding used for OsStr. | |
1406 | fn as_u8_slice(&self) -> &[u8] { | |
e9174d1e | 1407 | os_str_as_u8_slice(&self.inner) |
85aaf69f SL |
1408 | } |
1409 | ||
1410 | /// Directly wrap a string slice as a `Path` slice. | |
1411 | /// | |
1412 | /// This is a cost-free conversion. | |
c34b1796 AL |
1413 | /// |
1414 | /// # Examples | |
1415 | /// | |
1416 | /// ``` | |
1417 | /// use std::path::Path; | |
1418 | /// | |
1419 | /// Path::new("foo.txt"); | |
1420 | /// ``` | |
bd371182 AL |
1421 | /// |
1422 | /// You can create `Path`s from `String`s, or even other `Path`s: | |
1423 | /// | |
1424 | /// ``` | |
1425 | /// use std::path::Path; | |
1426 | /// | |
62682a34 SL |
1427 | /// let string = String::from("foo.txt"); |
1428 | /// let from_string = Path::new(&string); | |
1429 | /// let from_path = Path::new(&from_string); | |
1430 | /// assert_eq!(from_string, from_path); | |
bd371182 | 1431 | /// ``` |
c34b1796 AL |
1432 | #[stable(feature = "rust1", since = "1.0.0")] |
1433 | pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path { | |
1434 | unsafe { mem::transmute(s.as_ref()) } | |
1435 | } | |
1436 | ||
9e0c209e SL |
1437 | /// Yields the underlying [`OsStr`] slice. |
1438 | /// | |
1439 | /// [`OsStr`]: ../ffi/struct.OsStr.html | |
c34b1796 AL |
1440 | /// |
1441 | /// # Examples | |
1442 | /// | |
1443 | /// ``` | |
1444 | /// use std::path::Path; | |
1445 | /// | |
1446 | /// let os_str = Path::new("foo.txt").as_os_str(); | |
62682a34 | 1447 | /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt")); |
c34b1796 AL |
1448 | /// ``` |
1449 | #[stable(feature = "rust1", since = "1.0.0")] | |
1450 | pub fn as_os_str(&self) -> &OsStr { | |
1451 | &self.inner | |
85aaf69f SL |
1452 | } |
1453 | ||
9e0c209e | 1454 | /// Yields a [`&str`] slice if the `Path` is valid unicode. |
85aaf69f SL |
1455 | /// |
1456 | /// This conversion may entail doing a check for UTF-8 validity. | |
c34b1796 | 1457 | /// |
9e0c209e SL |
1458 | /// [`&str`]: ../primitive.str.html |
1459 | /// | |
c34b1796 AL |
1460 | /// # Examples |
1461 | /// | |
1462 | /// ``` | |
1463 | /// use std::path::Path; | |
1464 | /// | |
32a655c1 SL |
1465 | /// let path = Path::new("foo.txt"); |
1466 | /// assert_eq!(path.to_str(), Some("foo.txt")); | |
c34b1796 AL |
1467 | /// ``` |
1468 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
1469 | pub fn to_str(&self) -> Option<&str> { |
1470 | self.inner.to_str() | |
1471 | } | |
1472 | ||
9e0c209e | 1473 | /// Converts a `Path` to a [`Cow<str>`]. |
85aaf69f SL |
1474 | /// |
1475 | /// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER. | |
c34b1796 | 1476 | /// |
9e0c209e SL |
1477 | /// [`Cow<str>`]: ../borrow/enum.Cow.html |
1478 | /// | |
c34b1796 AL |
1479 | /// # Examples |
1480 | /// | |
32a655c1 SL |
1481 | /// Calling `to_string_lossy` on a `Path` with valid unicode: |
1482 | /// | |
c34b1796 AL |
1483 | /// ``` |
1484 | /// use std::path::Path; | |
1485 | /// | |
32a655c1 SL |
1486 | /// let path = Path::new("foo.txt"); |
1487 | /// assert_eq!(path.to_string_lossy(), "foo.txt"); | |
c34b1796 | 1488 | /// ``` |
32a655c1 SL |
1489 | /// |
1490 | /// Had `os_str` contained invalid unicode, the `to_string_lossy` call might | |
1491 | /// have returned `"fo�.txt"`. | |
c34b1796 | 1492 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1493 | pub fn to_string_lossy(&self) -> Cow<str> { |
1494 | self.inner.to_string_lossy() | |
1495 | } | |
1496 | ||
9e0c209e SL |
1497 | /// Converts a `Path` to an owned [`PathBuf`]. |
1498 | /// | |
1499 | /// [`PathBuf`]: struct.PathBuf.html | |
c34b1796 AL |
1500 | /// |
1501 | /// # Examples | |
1502 | /// | |
1503 | /// ``` | |
1504 | /// use std::path::Path; | |
1505 | /// | |
62682a34 SL |
1506 | /// let path_buf = Path::new("foo.txt").to_path_buf(); |
1507 | /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt")); | |
c34b1796 AL |
1508 | /// ``` |
1509 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f | 1510 | pub fn to_path_buf(&self) -> PathBuf { |
c34b1796 | 1511 | PathBuf::from(self.inner.to_os_string()) |
85aaf69f SL |
1512 | } |
1513 | ||
1514 | /// A path is *absolute* if it is independent of the current directory. | |
1515 | /// | |
1516 | /// * On Unix, a path is absolute if it starts with the root, so | |
1517 | /// `is_absolute` and `has_root` are equivalent. | |
1518 | /// | |
1519 | /// * On Windows, a path is absolute if it has a prefix and starts with the | |
3157f602 | 1520 | /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. |
c34b1796 AL |
1521 | /// |
1522 | /// # Examples | |
1523 | /// | |
1524 | /// ``` | |
1525 | /// use std::path::Path; | |
1526 | /// | |
62682a34 | 1527 | /// assert!(!Path::new("foo.txt").is_absolute()); |
c34b1796 AL |
1528 | /// ``` |
1529 | #[stable(feature = "rust1", since = "1.0.0")] | |
9cc50fc6 | 1530 | #[allow(deprecated)] |
85aaf69f | 1531 | pub fn is_absolute(&self) -> bool { |
32a655c1 SL |
1532 | // FIXME: Remove target_os = "redox" and allow Redox prefixes |
1533 | self.has_root() && (cfg!(unix) || cfg!(target_os = "redox") || self.prefix().is_some()) | |
85aaf69f SL |
1534 | } |
1535 | ||
1536 | /// A path is *relative* if it is not absolute. | |
c34b1796 AL |
1537 | /// |
1538 | /// # Examples | |
1539 | /// | |
1540 | /// ``` | |
1541 | /// use std::path::Path; | |
1542 | /// | |
1543 | /// assert!(Path::new("foo.txt").is_relative()); | |
1544 | /// ``` | |
1545 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
1546 | pub fn is_relative(&self) -> bool { |
1547 | !self.is_absolute() | |
1548 | } | |
1549 | ||
54a0048b | 1550 | fn prefix(&self) -> Option<Prefix> { |
c34b1796 | 1551 | self.components().prefix |
85aaf69f SL |
1552 | } |
1553 | ||
1554 | /// A path has a root if the body of the path begins with the directory separator. | |
1555 | /// | |
1556 | /// * On Unix, a path has a root if it begins with `/`. | |
1557 | /// | |
1558 | /// * On Windows, a path has a root if it: | |
1559 | /// * has no prefix and begins with a separator, e.g. `\\windows` | |
1560 | /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows` | |
1561 | /// * has any non-disk prefix, e.g. `\\server\share` | |
c34b1796 AL |
1562 | /// |
1563 | /// # Examples | |
1564 | /// | |
1565 | /// ``` | |
1566 | /// use std::path::Path; | |
1567 | /// | |
1568 | /// assert!(Path::new("/etc/passwd").has_root()); | |
1569 | /// ``` | |
1570 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f | 1571 | pub fn has_root(&self) -> bool { |
92a42be0 | 1572 | self.components().has_root() |
85aaf69f SL |
1573 | } |
1574 | ||
c34b1796 | 1575 | /// The path without its final component, if any. |
85aaf69f | 1576 | /// |
32a655c1 SL |
1577 | /// Returns [`None`] if the path terminates in a root or prefix. |
1578 | /// | |
1579 | /// [`None`]: ../../std/option/enum.Option.html#variant.None | |
85aaf69f SL |
1580 | /// |
1581 | /// # Examples | |
1582 | /// | |
c34b1796 | 1583 | /// ``` |
85aaf69f SL |
1584 | /// use std::path::Path; |
1585 | /// | |
1586 | /// let path = Path::new("/foo/bar"); | |
62682a34 SL |
1587 | /// let parent = path.parent().unwrap(); |
1588 | /// assert_eq!(parent, Path::new("/foo")); | |
c34b1796 | 1589 | /// |
62682a34 SL |
1590 | /// let grand_parent = parent.parent().unwrap(); |
1591 | /// assert_eq!(grand_parent, Path::new("/")); | |
1592 | /// assert_eq!(grand_parent.parent(), None); | |
85aaf69f | 1593 | /// ``` |
c34b1796 | 1594 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
1595 | pub fn parent(&self) -> Option<&Path> { |
1596 | let mut comps = self.components(); | |
1597 | let comp = comps.next_back(); | |
92a42be0 SL |
1598 | comp.and_then(|p| { |
1599 | match p { | |
1600 | Component::Normal(_) | | |
1601 | Component::CurDir | | |
1602 | Component::ParentDir => Some(comps.as_path()), | |
1603 | _ => None, | |
1604 | } | |
c34b1796 | 1605 | }) |
85aaf69f SL |
1606 | } |
1607 | ||
1608 | /// The final component of the path, if it is a normal file. | |
1609 | /// | |
32a655c1 SL |
1610 | /// If the path terminates in `..`, `file_name` will return [`None`]. |
1611 | /// | |
1612 | /// [`None`]: ../../std/option/enum.Option.html#variant.None | |
c34b1796 AL |
1613 | /// |
1614 | /// # Examples | |
1615 | /// | |
1616 | /// ``` | |
1617 | /// use std::path::Path; | |
62682a34 | 1618 | /// use std::ffi::OsStr; |
c34b1796 | 1619 | /// |
62682a34 SL |
1620 | /// let path = Path::new("foo.txt"); |
1621 | /// let os_str = OsStr::new("foo.txt"); | |
c34b1796 | 1622 | /// |
62682a34 | 1623 | /// assert_eq!(Some(os_str), path.file_name()); |
c34b1796 | 1624 | /// ``` |
5bcae85e SL |
1625 | /// |
1626 | /// # Other examples | |
1627 | /// | |
1628 | /// ``` | |
1629 | /// use std::path::Path; | |
1630 | /// use std::ffi::OsStr; | |
1631 | /// | |
1632 | /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name()); | |
1633 | /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name()); | |
1634 | /// assert_eq!(None, Path::new("foo.txt/..").file_name()); | |
1635 | /// ``` | |
c34b1796 | 1636 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 1637 | pub fn file_name(&self) -> Option<&OsStr> { |
92a42be0 SL |
1638 | self.components().next_back().and_then(|p| { |
1639 | match p { | |
1640 | Component::Normal(p) => Some(p.as_ref()), | |
1641 | _ => None, | |
1642 | } | |
85aaf69f SL |
1643 | }) |
1644 | } | |
1645 | ||
9cc50fc6 SL |
1646 | /// Returns a path that, when joined onto `base`, yields `self`. |
1647 | /// | |
7453a54e SL |
1648 | /// # Errors |
1649 | /// | |
32a655c1 SL |
1650 | /// If `base` is not a prefix of `self` (i.e. [`starts_with`] |
1651 | /// returns `false`), returns [`Err`]. | |
1652 | /// | |
1653 | /// [`starts_with`]: #method.starts_with | |
1654 | /// [`Err`]: ../../std/result/enum.Result.html#variant.Err | |
9e0c209e SL |
1655 | /// |
1656 | /// # Examples | |
1657 | /// | |
1658 | /// ``` | |
1659 | /// use std::path::Path; | |
1660 | /// | |
1661 | /// let path = Path::new("/test/haha/foo.txt"); | |
1662 | /// | |
1663 | /// assert_eq!(path.strip_prefix("/test"), Ok(Path::new("haha/foo.txt"))); | |
1664 | /// assert_eq!(path.strip_prefix("test").is_ok(), false); | |
1665 | /// assert_eq!(path.strip_prefix("/haha").is_ok(), false); | |
1666 | /// ``` | |
9cc50fc6 SL |
1667 | #[stable(since = "1.7.0", feature = "path_strip_prefix")] |
1668 | pub fn strip_prefix<'a, P: ?Sized>(&'a self, base: &'a P) | |
1669 | -> Result<&'a Path, StripPrefixError> | |
1670 | where P: AsRef<Path> | |
1671 | { | |
1672 | self._strip_prefix(base.as_ref()) | |
e9174d1e SL |
1673 | } |
1674 | ||
9cc50fc6 SL |
1675 | fn _strip_prefix<'a>(&'a self, base: &'a Path) |
1676 | -> Result<&'a Path, StripPrefixError> { | |
1677 | iter_after(self.components(), base.components()) | |
1678 | .map(|c| c.as_path()) | |
1679 | .ok_or(StripPrefixError(())) | |
85aaf69f SL |
1680 | } |
1681 | ||
1682 | /// Determines whether `base` is a prefix of `self`. | |
c34b1796 | 1683 | /// |
d9579d0f AL |
1684 | /// Only considers whole path components to match. |
1685 | /// | |
c34b1796 AL |
1686 | /// # Examples |
1687 | /// | |
1688 | /// ``` | |
1689 | /// use std::path::Path; | |
1690 | /// | |
1691 | /// let path = Path::new("/etc/passwd"); | |
1692 | /// | |
1693 | /// assert!(path.starts_with("/etc")); | |
d9579d0f AL |
1694 | /// |
1695 | /// assert!(!path.starts_with("/e")); | |
c34b1796 AL |
1696 | /// ``` |
1697 | #[stable(feature = "rust1", since = "1.0.0")] | |
1698 | pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool { | |
e9174d1e SL |
1699 | self._starts_with(base.as_ref()) |
1700 | } | |
1701 | ||
1702 | fn _starts_with(&self, base: &Path) -> bool { | |
1703 | iter_after(self.components(), base.components()).is_some() | |
85aaf69f SL |
1704 | } |
1705 | ||
c34b1796 AL |
1706 | /// Determines whether `child` is a suffix of `self`. |
1707 | /// | |
d9579d0f AL |
1708 | /// Only considers whole path components to match. |
1709 | /// | |
c34b1796 AL |
1710 | /// # Examples |
1711 | /// | |
1712 | /// ``` | |
1713 | /// use std::path::Path; | |
1714 | /// | |
1715 | /// let path = Path::new("/etc/passwd"); | |
1716 | /// | |
1717 | /// assert!(path.ends_with("passwd")); | |
1718 | /// ``` | |
1719 | #[stable(feature = "rust1", since = "1.0.0")] | |
1720 | pub fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool { | |
e9174d1e SL |
1721 | self._ends_with(child.as_ref()) |
1722 | } | |
1723 | ||
1724 | fn _ends_with(&self, child: &Path) -> bool { | |
1725 | iter_after(self.components().rev(), child.components().rev()).is_some() | |
85aaf69f SL |
1726 | } |
1727 | ||
9e0c209e SL |
1728 | /// Extracts the stem (non-extension) portion of [`self.file_name()`]. |
1729 | /// | |
1730 | /// [`self.file_name()`]: struct.Path.html#method.file_name | |
85aaf69f SL |
1731 | /// |
1732 | /// The stem is: | |
1733 | /// | |
32a655c1 | 1734 | /// * [`None`], if there is no file name; |
85aaf69f SL |
1735 | /// * The entire file name if there is no embedded `.`; |
1736 | /// * The entire file name if the file name begins with `.` and has no other `.`s within; | |
1737 | /// * Otherwise, the portion of the file name before the final `.` | |
c34b1796 | 1738 | /// |
32a655c1 SL |
1739 | /// [`None`]: ../../std/option/enum.Option.html#variant.None |
1740 | /// | |
c34b1796 AL |
1741 | /// # Examples |
1742 | /// | |
1743 | /// ``` | |
1744 | /// use std::path::Path; | |
1745 | /// | |
1746 | /// let path = Path::new("foo.rs"); | |
1747 | /// | |
1748 | /// assert_eq!("foo", path.file_stem().unwrap()); | |
1749 | /// ``` | |
1750 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
1751 | pub fn file_stem(&self) -> Option<&OsStr> { |
1752 | self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.or(after)) | |
1753 | } | |
1754 | ||
9e0c209e SL |
1755 | /// Extracts the extension of [`self.file_name()`], if possible. |
1756 | /// | |
85aaf69f SL |
1757 | /// The extension is: |
1758 | /// | |
32a655c1 SL |
1759 | /// * [`None`], if there is no file name; |
1760 | /// * [`None`], if there is no embedded `.`; | |
1761 | /// * [`None`], if the file name begins with `.` and has no other `.`s within; | |
85aaf69f | 1762 | /// * Otherwise, the portion of the file name after the final `.` |
c34b1796 | 1763 | /// |
32a655c1 SL |
1764 | /// [`self.file_name()`]: struct.Path.html#method.file_name |
1765 | /// [`None`]: ../../std/option/enum.Option.html#variant.None | |
1766 | /// | |
c34b1796 AL |
1767 | /// # Examples |
1768 | /// | |
1769 | /// ``` | |
1770 | /// use std::path::Path; | |
1771 | /// | |
1772 | /// let path = Path::new("foo.rs"); | |
1773 | /// | |
1774 | /// assert_eq!("rs", path.extension().unwrap()); | |
1775 | /// ``` | |
1776 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
1777 | pub fn extension(&self) -> Option<&OsStr> { |
1778 | self.file_name().map(split_file_at_dot).and_then(|(before, after)| before.and(after)) | |
1779 | } | |
1780 | ||
9e0c209e SL |
1781 | /// Creates an owned [`PathBuf`] with `path` adjoined to `self`. |
1782 | /// | |
1783 | /// See [`PathBuf::push`] for more details on what it means to adjoin a path. | |
85aaf69f | 1784 | /// |
9e0c209e SL |
1785 | /// [`PathBuf`]: struct.PathBuf.html |
1786 | /// [`PathBuf::push`]: struct.PathBuf.html#method.push | |
c34b1796 AL |
1787 | /// |
1788 | /// # Examples | |
1789 | /// | |
1790 | /// ``` | |
62682a34 | 1791 | /// use std::path::{Path, PathBuf}; |
c34b1796 | 1792 | /// |
62682a34 | 1793 | /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd")); |
c34b1796 AL |
1794 | /// ``` |
1795 | #[stable(feature = "rust1", since = "1.0.0")] | |
1796 | pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf { | |
e9174d1e SL |
1797 | self._join(path.as_ref()) |
1798 | } | |
1799 | ||
1800 | fn _join(&self, path: &Path) -> PathBuf { | |
85aaf69f SL |
1801 | let mut buf = self.to_path_buf(); |
1802 | buf.push(path); | |
1803 | buf | |
1804 | } | |
1805 | ||
9e0c209e SL |
1806 | /// Creates an owned [`PathBuf`] like `self` but with the given file name. |
1807 | /// | |
1808 | /// See [`PathBuf::set_file_name`] for more details. | |
85aaf69f | 1809 | /// |
9e0c209e SL |
1810 | /// [`PathBuf`]: struct.PathBuf.html |
1811 | /// [`PathBuf::set_file_name`]: struct.PathBuf.html#method.set_file_name | |
c34b1796 AL |
1812 | /// |
1813 | /// # Examples | |
1814 | /// | |
1815 | /// ``` | |
62682a34 | 1816 | /// use std::path::{Path, PathBuf}; |
c34b1796 | 1817 | /// |
62682a34 SL |
1818 | /// let path = Path::new("/tmp/foo.txt"); |
1819 | /// assert_eq!(path.with_file_name("bar.txt"), PathBuf::from("/tmp/bar.txt")); | |
c34b1796 AL |
1820 | /// ``` |
1821 | #[stable(feature = "rust1", since = "1.0.0")] | |
1822 | pub fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf { | |
e9174d1e SL |
1823 | self._with_file_name(file_name.as_ref()) |
1824 | } | |
1825 | ||
1826 | fn _with_file_name(&self, file_name: &OsStr) -> PathBuf { | |
85aaf69f SL |
1827 | let mut buf = self.to_path_buf(); |
1828 | buf.set_file_name(file_name); | |
1829 | buf | |
1830 | } | |
1831 | ||
9e0c209e | 1832 | /// Creates an owned [`PathBuf`] like `self` but with the given extension. |
85aaf69f | 1833 | /// |
9e0c209e SL |
1834 | /// See [`PathBuf::set_extension`] for more details. |
1835 | /// | |
1836 | /// [`PathBuf`]: struct.PathBuf.html | |
1837 | /// [`PathBuf::set_extension`]: struct.PathBuf.html#method.set_extension | |
c34b1796 AL |
1838 | /// |
1839 | /// # Examples | |
1840 | /// | |
1841 | /// ``` | |
9346a6ac | 1842 | /// use std::path::{Path, PathBuf}; |
c34b1796 | 1843 | /// |
62682a34 SL |
1844 | /// let path = Path::new("foo.rs"); |
1845 | /// assert_eq!(path.with_extension("txt"), PathBuf::from("foo.txt")); | |
c34b1796 AL |
1846 | /// ``` |
1847 | #[stable(feature = "rust1", since = "1.0.0")] | |
1848 | pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf { | |
e9174d1e SL |
1849 | self._with_extension(extension.as_ref()) |
1850 | } | |
1851 | ||
1852 | fn _with_extension(&self, extension: &OsStr) -> PathBuf { | |
85aaf69f SL |
1853 | let mut buf = self.to_path_buf(); |
1854 | buf.set_extension(extension); | |
1855 | buf | |
1856 | } | |
1857 | ||
1858 | /// Produce an iterator over the components of the path. | |
c34b1796 AL |
1859 | /// |
1860 | /// # Examples | |
1861 | /// | |
1862 | /// ``` | |
62682a34 SL |
1863 | /// use std::path::{Path, Component}; |
1864 | /// use std::ffi::OsStr; | |
c34b1796 | 1865 | /// |
62682a34 | 1866 | /// let mut components = Path::new("/tmp/foo.txt").components(); |
c34b1796 | 1867 | /// |
62682a34 SL |
1868 | /// assert_eq!(components.next(), Some(Component::RootDir)); |
1869 | /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("tmp")))); | |
1870 | /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt")))); | |
1871 | /// assert_eq!(components.next(), None) | |
c34b1796 AL |
1872 | /// ``` |
1873 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
1874 | pub fn components(&self) -> Components { |
1875 | let prefix = parse_prefix(self.as_os_str()); | |
1876 | Components { | |
1877 | path: self.as_u8_slice(), | |
1878 | prefix: prefix, | |
1879 | has_physical_root: has_physical_root(self.as_u8_slice(), prefix), | |
1880 | front: State::Prefix, | |
c34b1796 | 1881 | back: State::Body, |
85aaf69f SL |
1882 | } |
1883 | } | |
1884 | ||
9e0c209e SL |
1885 | /// Produce an iterator over the path's components viewed as [`OsStr`] slices. |
1886 | /// | |
1887 | /// [`OsStr`]: ../ffi/struct.OsStr.html | |
c34b1796 AL |
1888 | /// |
1889 | /// # Examples | |
1890 | /// | |
1891 | /// ``` | |
62682a34 SL |
1892 | /// use std::path::{self, Path}; |
1893 | /// use std::ffi::OsStr; | |
1894 | /// | |
1895 | /// let mut it = Path::new("/tmp/foo.txt").iter(); | |
1896 | /// assert_eq!(it.next(), Some(OsStr::new(&path::MAIN_SEPARATOR.to_string()))); | |
1897 | /// assert_eq!(it.next(), Some(OsStr::new("tmp"))); | |
1898 | /// assert_eq!(it.next(), Some(OsStr::new("foo.txt"))); | |
1899 | /// assert_eq!(it.next(), None) | |
c34b1796 AL |
1900 | /// ``` |
1901 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
1902 | pub fn iter(&self) -> Iter { |
1903 | Iter { inner: self.components() } | |
1904 | } | |
1905 | ||
9e0c209e | 1906 | /// Returns an object that implements [`Display`] for safely printing paths |
85aaf69f | 1907 | /// that may contain non-Unicode data. |
c34b1796 | 1908 | /// |
9e0c209e SL |
1909 | /// [`Display`]: ../fmt/trait.Display.html |
1910 | /// | |
c34b1796 AL |
1911 | /// # Examples |
1912 | /// | |
1913 | /// ``` | |
1914 | /// use std::path::Path; | |
1915 | /// | |
1916 | /// let path = Path::new("/tmp/foo.rs"); | |
1917 | /// | |
1918 | /// println!("{}", path.display()); | |
1919 | /// ``` | |
1920 | #[stable(feature = "rust1", since = "1.0.0")] | |
85aaf69f SL |
1921 | pub fn display(&self) -> Display { |
1922 | Display { path: self } | |
1923 | } | |
b039eaaf | 1924 | |
7453a54e | 1925 | /// Query the file system to get information about a file, directory, etc. |
b039eaaf | 1926 | /// |
7453a54e SL |
1927 | /// This function will traverse symbolic links to query information about the |
1928 | /// destination file. | |
b039eaaf | 1929 | /// |
3157f602 XL |
1930 | /// This is an alias to [`fs::metadata`]. |
1931 | /// | |
1932 | /// [`fs::metadata`]: ../fs/fn.metadata.html | |
32a655c1 SL |
1933 | /// |
1934 | /// # Examples | |
1935 | /// | |
1936 | /// ```no_run | |
1937 | /// use std::path::Path; | |
1938 | /// | |
1939 | /// let path = Path::new("/Minas/tirith"); | |
1940 | /// let metadata = path.metadata().expect("metadata call failed"); | |
1941 | /// println!("{:?}", metadata.file_type()); | |
1942 | /// ``` | |
b039eaaf SL |
1943 | #[stable(feature = "path_ext", since = "1.5.0")] |
1944 | pub fn metadata(&self) -> io::Result<fs::Metadata> { | |
1945 | fs::metadata(self) | |
1946 | } | |
1947 | ||
7453a54e | 1948 | /// Query the metadata about a file without following symlinks. |
b039eaaf | 1949 | /// |
3157f602 XL |
1950 | /// This is an alias to [`fs::symlink_metadata`]. |
1951 | /// | |
1952 | /// [`fs::symlink_metadata`]: ../fs/fn.symlink_metadata.html | |
32a655c1 SL |
1953 | /// |
1954 | /// # Examples | |
1955 | /// | |
1956 | /// ```no_run | |
1957 | /// use std::path::Path; | |
1958 | /// | |
1959 | /// let path = Path::new("/Minas/tirith"); | |
1960 | /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed"); | |
1961 | /// println!("{:?}", metadata.file_type()); | |
1962 | /// ``` | |
b039eaaf SL |
1963 | #[stable(feature = "path_ext", since = "1.5.0")] |
1964 | pub fn symlink_metadata(&self) -> io::Result<fs::Metadata> { | |
1965 | fs::symlink_metadata(self) | |
1966 | } | |
1967 | ||
7453a54e SL |
1968 | /// Returns the canonical form of the path with all intermediate components |
1969 | /// normalized and symbolic links resolved. | |
b039eaaf | 1970 | /// |
3157f602 XL |
1971 | /// This is an alias to [`fs::canonicalize`]. |
1972 | /// | |
1973 | /// [`fs::canonicalize`]: ../fs/fn.canonicalize.html | |
32a655c1 SL |
1974 | /// |
1975 | /// # Examples | |
1976 | /// | |
1977 | /// ```no_run | |
1978 | /// use std::path::{Path, PathBuf}; | |
1979 | /// | |
1980 | /// let path = Path::new("/foo/test/../test/bar.rs"); | |
1981 | /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs")); | |
1982 | /// ``` | |
b039eaaf SL |
1983 | #[stable(feature = "path_ext", since = "1.5.0")] |
1984 | pub fn canonicalize(&self) -> io::Result<PathBuf> { | |
1985 | fs::canonicalize(self) | |
1986 | } | |
1987 | ||
7453a54e | 1988 | /// Reads a symbolic link, returning the file that the link points to. |
b039eaaf | 1989 | /// |
3157f602 XL |
1990 | /// This is an alias to [`fs::read_link`]. |
1991 | /// | |
1992 | /// [`fs::read_link`]: ../fs/fn.read_link.html | |
32a655c1 SL |
1993 | /// |
1994 | /// # Examples | |
1995 | /// | |
1996 | /// ```no_run | |
1997 | /// use std::path::Path; | |
1998 | /// | |
1999 | /// let path = Path::new("/laputa/sky_castle.rs"); | |
2000 | /// let path_link = path.read_link().expect("read_link call failed"); | |
2001 | /// ``` | |
b039eaaf SL |
2002 | #[stable(feature = "path_ext", since = "1.5.0")] |
2003 | pub fn read_link(&self) -> io::Result<PathBuf> { | |
2004 | fs::read_link(self) | |
2005 | } | |
2006 | ||
7453a54e | 2007 | /// Returns an iterator over the entries within a directory. |
b039eaaf | 2008 | /// |
9e0c209e SL |
2009 | /// The iterator will yield instances of [`io::Result`]`<`[`DirEntry`]`>`. New |
2010 | /// errors may be encountered after an iterator is initially constructed. | |
7453a54e | 2011 | /// |
3157f602 XL |
2012 | /// This is an alias to [`fs::read_dir`]. |
2013 | /// | |
9e0c209e SL |
2014 | /// [`io::Result`]: ../io/type.Result.html |
2015 | /// [`DirEntry`]: ../fs/struct.DirEntry.html | |
3157f602 | 2016 | /// [`fs::read_dir`]: ../fs/fn.read_dir.html |
32a655c1 SL |
2017 | /// |
2018 | /// # Examples | |
2019 | /// | |
2020 | /// ```no_run | |
2021 | /// use std::path::Path; | |
2022 | /// | |
2023 | /// let path = Path::new("/laputa"); | |
2024 | /// for entry in path.read_dir().expect("read_dir call failed") { | |
2025 | /// if let Ok(entry) = entry { | |
2026 | /// println!("{:?}", entry.path()); | |
2027 | /// } | |
2028 | /// } | |
2029 | /// ``` | |
b039eaaf SL |
2030 | #[stable(feature = "path_ext", since = "1.5.0")] |
2031 | pub fn read_dir(&self) -> io::Result<fs::ReadDir> { | |
2032 | fs::read_dir(self) | |
2033 | } | |
2034 | ||
7453a54e SL |
2035 | /// Returns whether the path points at an existing entity. |
2036 | /// | |
2037 | /// This function will traverse symbolic links to query information about the | |
2038 | /// destination file. In case of broken symbolic links this will return `false`. | |
2039 | /// | |
2040 | /// # Examples | |
2041 | /// | |
2042 | /// ```no_run | |
2043 | /// use std::path::Path; | |
2044 | /// assert_eq!(Path::new("does_not_exist.txt").exists(), false); | |
2045 | /// ``` | |
b039eaaf SL |
2046 | #[stable(feature = "path_ext", since = "1.5.0")] |
2047 | pub fn exists(&self) -> bool { | |
2048 | fs::metadata(self).is_ok() | |
2049 | } | |
2050 | ||
7453a54e SL |
2051 | /// Returns whether the path is pointing at a regular file. |
2052 | /// | |
2053 | /// This function will traverse symbolic links to query information about the | |
2054 | /// destination file. In case of broken symbolic links this will return `false`. | |
2055 | /// | |
2056 | /// # Examples | |
2057 | /// | |
2058 | /// ```no_run | |
2059 | /// use std::path::Path; | |
2060 | /// assert_eq!(Path::new("./is_a_directory/").is_file(), false); | |
2061 | /// assert_eq!(Path::new("a_file.txt").is_file(), true); | |
2062 | /// ``` | |
b039eaaf SL |
2063 | #[stable(feature = "path_ext", since = "1.5.0")] |
2064 | pub fn is_file(&self) -> bool { | |
2065 | fs::metadata(self).map(|m| m.is_file()).unwrap_or(false) | |
2066 | } | |
2067 | ||
7453a54e SL |
2068 | /// Returns whether the path is pointing at a directory. |
2069 | /// | |
2070 | /// This function will traverse symbolic links to query information about the | |
2071 | /// destination file. In case of broken symbolic links this will return `false`. | |
2072 | /// | |
2073 | /// # Examples | |
2074 | /// | |
2075 | /// ```no_run | |
2076 | /// use std::path::Path; | |
2077 | /// assert_eq!(Path::new("./is_a_directory/").is_dir(), true); | |
2078 | /// assert_eq!(Path::new("a_file.txt").is_dir(), false); | |
2079 | /// ``` | |
b039eaaf SL |
2080 | #[stable(feature = "path_ext", since = "1.5.0")] |
2081 | pub fn is_dir(&self) -> bool { | |
2082 | fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false) | |
2083 | } | |
85aaf69f SL |
2084 | } |
2085 | ||
c34b1796 AL |
2086 | #[stable(feature = "rust1", since = "1.0.0")] |
2087 | impl AsRef<OsStr> for Path { | |
2088 | fn as_ref(&self) -> &OsStr { | |
2089 | &self.inner | |
2090 | } | |
2091 | } | |
2092 | ||
c34b1796 | 2093 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2094 | impl fmt::Debug for Path { |
2095 | fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { | |
2096 | self.inner.fmt(formatter) | |
2097 | } | |
2098 | } | |
2099 | ||
2100 | /// Helper struct for safely printing paths with `format!()` and `{}` | |
c34b1796 | 2101 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f | 2102 | pub struct Display<'a> { |
92a42be0 | 2103 | path: &'a Path, |
85aaf69f SL |
2104 | } |
2105 | ||
c34b1796 | 2106 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2107 | impl<'a> fmt::Debug for Display<'a> { |
2108 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2109 | fmt::Debug::fmt(&self.path.to_string_lossy(), f) | |
2110 | } | |
2111 | } | |
2112 | ||
c34b1796 | 2113 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2114 | impl<'a> fmt::Display for Display<'a> { |
2115 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2116 | fmt::Display::fmt(&self.path.to_string_lossy(), f) | |
2117 | } | |
2118 | } | |
2119 | ||
c34b1796 | 2120 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2121 | impl cmp::PartialEq for Path { |
2122 | fn eq(&self, other: &Path) -> bool { | |
e9174d1e | 2123 | self.components().eq(other.components()) |
85aaf69f SL |
2124 | } |
2125 | } | |
2126 | ||
92a42be0 SL |
2127 | #[stable(feature = "rust1", since = "1.0.0")] |
2128 | impl Hash for Path { | |
2129 | fn hash<H: Hasher>(&self, h: &mut H) { | |
2130 | for component in self.components() { | |
2131 | component.hash(h); | |
2132 | } | |
2133 | } | |
2134 | } | |
2135 | ||
c34b1796 | 2136 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2137 | impl cmp::Eq for Path {} |
2138 | ||
c34b1796 | 2139 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2140 | impl cmp::PartialOrd for Path { |
2141 | fn partial_cmp(&self, other: &Path) -> Option<cmp::Ordering> { | |
e9174d1e | 2142 | self.components().partial_cmp(other.components()) |
85aaf69f SL |
2143 | } |
2144 | } | |
2145 | ||
c34b1796 | 2146 | #[stable(feature = "rust1", since = "1.0.0")] |
85aaf69f SL |
2147 | impl cmp::Ord for Path { |
2148 | fn cmp(&self, other: &Path) -> cmp::Ordering { | |
e9174d1e | 2149 | self.components().cmp(other.components()) |
85aaf69f SL |
2150 | } |
2151 | } | |
2152 | ||
c34b1796 AL |
2153 | #[stable(feature = "rust1", since = "1.0.0")] |
2154 | impl AsRef<Path> for Path { | |
92a42be0 SL |
2155 | fn as_ref(&self) -> &Path { |
2156 | self | |
2157 | } | |
c34b1796 AL |
2158 | } |
2159 | ||
2160 | #[stable(feature = "rust1", since = "1.0.0")] | |
2161 | impl AsRef<Path> for OsStr { | |
92a42be0 SL |
2162 | fn as_ref(&self) -> &Path { |
2163 | Path::new(self) | |
2164 | } | |
c34b1796 AL |
2165 | } |
2166 | ||
7453a54e SL |
2167 | #[stable(feature = "cow_os_str_as_ref_path", since = "1.8.0")] |
2168 | impl<'a> AsRef<Path> for Cow<'a, OsStr> { | |
2169 | fn as_ref(&self) -> &Path { | |
2170 | Path::new(self) | |
2171 | } | |
2172 | } | |
2173 | ||
c34b1796 AL |
2174 | #[stable(feature = "rust1", since = "1.0.0")] |
2175 | impl AsRef<Path> for OsString { | |
92a42be0 SL |
2176 | fn as_ref(&self) -> &Path { |
2177 | Path::new(self) | |
2178 | } | |
c34b1796 AL |
2179 | } |
2180 | ||
2181 | #[stable(feature = "rust1", since = "1.0.0")] | |
2182 | impl AsRef<Path> for str { | |
92a42be0 SL |
2183 | fn as_ref(&self) -> &Path { |
2184 | Path::new(self) | |
2185 | } | |
c34b1796 AL |
2186 | } |
2187 | ||
2188 | #[stable(feature = "rust1", since = "1.0.0")] | |
2189 | impl AsRef<Path> for String { | |
92a42be0 SL |
2190 | fn as_ref(&self) -> &Path { |
2191 | Path::new(self) | |
2192 | } | |
c34b1796 AL |
2193 | } |
2194 | ||
2195 | #[stable(feature = "rust1", since = "1.0.0")] | |
2196 | impl AsRef<Path> for PathBuf { | |
92a42be0 SL |
2197 | fn as_ref(&self) -> &Path { |
2198 | self | |
2199 | } | |
2200 | } | |
2201 | ||
2202 | #[stable(feature = "path_into_iter", since = "1.6.0")] | |
2203 | impl<'a> IntoIterator for &'a PathBuf { | |
2204 | type Item = &'a OsStr; | |
2205 | type IntoIter = Iter<'a>; | |
2206 | fn into_iter(self) -> Iter<'a> { self.iter() } | |
2207 | } | |
2208 | ||
2209 | #[stable(feature = "path_into_iter", since = "1.6.0")] | |
2210 | impl<'a> IntoIterator for &'a Path { | |
2211 | type Item = &'a OsStr; | |
2212 | type IntoIter = Iter<'a>; | |
2213 | fn into_iter(self) -> Iter<'a> { self.iter() } | |
2214 | } | |
2215 | ||
7453a54e | 2216 | macro_rules! impl_cmp { |
92a42be0 SL |
2217 | ($lhs:ty, $rhs: ty) => { |
2218 | #[stable(feature = "partialeq_path", since = "1.6.0")] | |
2219 | impl<'a, 'b> PartialEq<$rhs> for $lhs { | |
2220 | #[inline] | |
2221 | fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other) } | |
2222 | } | |
2223 | ||
2224 | #[stable(feature = "partialeq_path", since = "1.6.0")] | |
2225 | impl<'a, 'b> PartialEq<$lhs> for $rhs { | |
2226 | #[inline] | |
2227 | fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self, other) } | |
2228 | } | |
2229 | ||
7453a54e SL |
2230 | #[stable(feature = "cmp_path", since = "1.8.0")] |
2231 | impl<'a, 'b> PartialOrd<$rhs> for $lhs { | |
2232 | #[inline] | |
2233 | fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> { | |
2234 | <Path as PartialOrd>::partial_cmp(self, other) | |
2235 | } | |
2236 | } | |
2237 | ||
2238 | #[stable(feature = "cmp_path", since = "1.8.0")] | |
2239 | impl<'a, 'b> PartialOrd<$lhs> for $rhs { | |
2240 | #[inline] | |
2241 | fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> { | |
2242 | <Path as PartialOrd>::partial_cmp(self, other) | |
2243 | } | |
2244 | } | |
2245 | } | |
2246 | } | |
2247 | ||
2248 | impl_cmp!(PathBuf, Path); | |
2249 | impl_cmp!(PathBuf, &'a Path); | |
2250 | impl_cmp!(Cow<'a, Path>, Path); | |
2251 | impl_cmp!(Cow<'a, Path>, &'b Path); | |
2252 | impl_cmp!(Cow<'a, Path>, PathBuf); | |
2253 | ||
2254 | macro_rules! impl_cmp_os_str { | |
2255 | ($lhs:ty, $rhs: ty) => { | |
2256 | #[stable(feature = "cmp_path", since = "1.8.0")] | |
2257 | impl<'a, 'b> PartialEq<$rhs> for $lhs { | |
2258 | #[inline] | |
2259 | fn eq(&self, other: &$rhs) -> bool { <Path as PartialEq>::eq(self, other.as_ref()) } | |
2260 | } | |
2261 | ||
2262 | #[stable(feature = "cmp_path", since = "1.8.0")] | |
2263 | impl<'a, 'b> PartialEq<$lhs> for $rhs { | |
2264 | #[inline] | |
2265 | fn eq(&self, other: &$lhs) -> bool { <Path as PartialEq>::eq(self.as_ref(), other) } | |
2266 | } | |
2267 | ||
2268 | #[stable(feature = "cmp_path", since = "1.8.0")] | |
2269 | impl<'a, 'b> PartialOrd<$rhs> for $lhs { | |
2270 | #[inline] | |
2271 | fn partial_cmp(&self, other: &$rhs) -> Option<cmp::Ordering> { | |
2272 | <Path as PartialOrd>::partial_cmp(self, other.as_ref()) | |
2273 | } | |
2274 | } | |
2275 | ||
2276 | #[stable(feature = "cmp_path", since = "1.8.0")] | |
2277 | impl<'a, 'b> PartialOrd<$lhs> for $rhs { | |
2278 | #[inline] | |
2279 | fn partial_cmp(&self, other: &$lhs) -> Option<cmp::Ordering> { | |
2280 | <Path as PartialOrd>::partial_cmp(self.as_ref(), other) | |
2281 | } | |
2282 | } | |
92a42be0 | 2283 | } |
c34b1796 AL |
2284 | } |
2285 | ||
7453a54e SL |
2286 | impl_cmp_os_str!(PathBuf, OsStr); |
2287 | impl_cmp_os_str!(PathBuf, &'a OsStr); | |
2288 | impl_cmp_os_str!(PathBuf, Cow<'a, OsStr>); | |
2289 | impl_cmp_os_str!(PathBuf, OsString); | |
2290 | impl_cmp_os_str!(Path, OsStr); | |
2291 | impl_cmp_os_str!(Path, &'a OsStr); | |
2292 | impl_cmp_os_str!(Path, Cow<'a, OsStr>); | |
2293 | impl_cmp_os_str!(Path, OsString); | |
2294 | impl_cmp_os_str!(&'a Path, OsStr); | |
2295 | impl_cmp_os_str!(&'a Path, Cow<'b, OsStr>); | |
2296 | impl_cmp_os_str!(&'a Path, OsString); | |
2297 | impl_cmp_os_str!(Cow<'a, Path>, OsStr); | |
2298 | impl_cmp_os_str!(Cow<'a, Path>, &'b OsStr); | |
2299 | impl_cmp_os_str!(Cow<'a, Path>, OsString); | |
92a42be0 | 2300 | |
9cc50fc6 SL |
2301 | #[stable(since = "1.7.0", feature = "strip_prefix")] |
2302 | impl fmt::Display for StripPrefixError { | |
2303 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
2304 | self.description().fmt(f) | |
2305 | } | |
2306 | } | |
2307 | ||
2308 | #[stable(since = "1.7.0", feature = "strip_prefix")] | |
2309 | impl Error for StripPrefixError { | |
2310 | fn description(&self) -> &str { "prefix not found" } | |
2311 | } | |
2312 | ||
85aaf69f SL |
2313 | #[cfg(test)] |
2314 | mod tests { | |
2315 | use super::*; | |
85aaf69f SL |
2316 | |
2317 | macro_rules! t( | |
2318 | ($path:expr, iter: $iter:expr) => ( | |
2319 | { | |
2320 | let path = Path::new($path); | |
2321 | ||
2322 | // Forward iteration | |
2323 | let comps = path.iter() | |
2324 | .map(|p| p.to_string_lossy().into_owned()) | |
2325 | .collect::<Vec<String>>(); | |
2326 | let exp: &[&str] = &$iter; | |
2327 | let exps = exp.iter().map(|s| s.to_string()).collect::<Vec<String>>(); | |
2328 | assert!(comps == exps, "iter: Expected {:?}, found {:?}", | |
2329 | exps, comps); | |
2330 | ||
2331 | // Reverse iteration | |
2332 | let comps = Path::new($path).iter().rev() | |
2333 | .map(|p| p.to_string_lossy().into_owned()) | |
2334 | .collect::<Vec<String>>(); | |
2335 | let exps = exps.into_iter().rev().collect::<Vec<String>>(); | |
2336 | assert!(comps == exps, "iter().rev(): Expected {:?}, found {:?}", | |
2337 | exps, comps); | |
2338 | } | |
2339 | ); | |
2340 | ||
2341 | ($path:expr, has_root: $has_root:expr, is_absolute: $is_absolute:expr) => ( | |
2342 | { | |
2343 | let path = Path::new($path); | |
2344 | ||
2345 | let act_root = path.has_root(); | |
2346 | assert!(act_root == $has_root, "has_root: Expected {:?}, found {:?}", | |
2347 | $has_root, act_root); | |
2348 | ||
2349 | let act_abs = path.is_absolute(); | |
2350 | assert!(act_abs == $is_absolute, "is_absolute: Expected {:?}, found {:?}", | |
2351 | $is_absolute, act_abs); | |
2352 | } | |
2353 | ); | |
2354 | ||
2355 | ($path:expr, parent: $parent:expr, file_name: $file:expr) => ( | |
2356 | { | |
2357 | let path = Path::new($path); | |
2358 | ||
2359 | let parent = path.parent().map(|p| p.to_str().unwrap()); | |
2360 | let exp_parent: Option<&str> = $parent; | |
2361 | assert!(parent == exp_parent, "parent: Expected {:?}, found {:?}", | |
2362 | exp_parent, parent); | |
2363 | ||
2364 | let file = path.file_name().map(|p| p.to_str().unwrap()); | |
2365 | let exp_file: Option<&str> = $file; | |
2366 | assert!(file == exp_file, "file_name: Expected {:?}, found {:?}", | |
2367 | exp_file, file); | |
2368 | } | |
2369 | ); | |
2370 | ||
2371 | ($path:expr, file_stem: $file_stem:expr, extension: $extension:expr) => ( | |
2372 | { | |
2373 | let path = Path::new($path); | |
2374 | ||
2375 | let stem = path.file_stem().map(|p| p.to_str().unwrap()); | |
2376 | let exp_stem: Option<&str> = $file_stem; | |
2377 | assert!(stem == exp_stem, "file_stem: Expected {:?}, found {:?}", | |
2378 | exp_stem, stem); | |
2379 | ||
2380 | let ext = path.extension().map(|p| p.to_str().unwrap()); | |
2381 | let exp_ext: Option<&str> = $extension; | |
2382 | assert!(ext == exp_ext, "extension: Expected {:?}, found {:?}", | |
2383 | exp_ext, ext); | |
2384 | } | |
2385 | ); | |
2386 | ||
2387 | ($path:expr, iter: $iter:expr, | |
2388 | has_root: $has_root:expr, is_absolute: $is_absolute:expr, | |
2389 | parent: $parent:expr, file_name: $file:expr, | |
2390 | file_stem: $file_stem:expr, extension: $extension:expr) => ( | |
2391 | { | |
2392 | t!($path, iter: $iter); | |
2393 | t!($path, has_root: $has_root, is_absolute: $is_absolute); | |
2394 | t!($path, parent: $parent, file_name: $file); | |
2395 | t!($path, file_stem: $file_stem, extension: $extension); | |
2396 | } | |
2397 | ); | |
2398 | ); | |
2399 | ||
92a42be0 SL |
2400 | #[test] |
2401 | fn into() { | |
2402 | use borrow::Cow; | |
2403 | ||
2404 | let static_path = Path::new("/home/foo"); | |
2405 | let static_cow_path: Cow<'static, Path> = static_path.into(); | |
2406 | let pathbuf = PathBuf::from("/home/foo"); | |
2407 | ||
2408 | { | |
2409 | let path: &Path = &pathbuf; | |
2410 | let borrowed_cow_path: Cow<Path> = path.into(); | |
2411 | ||
2412 | assert_eq!(static_cow_path, borrowed_cow_path); | |
2413 | } | |
2414 | ||
2415 | let owned_cow_path: Cow<'static, Path> = pathbuf.into(); | |
2416 | ||
2417 | assert_eq!(static_cow_path, owned_cow_path); | |
2418 | } | |
2419 | ||
85aaf69f SL |
2420 | #[test] |
2421 | #[cfg(unix)] | |
2422 | pub fn test_decompositions_unix() { | |
2423 | t!("", | |
2424 | iter: [], | |
2425 | has_root: false, | |
2426 | is_absolute: false, | |
2427 | parent: None, | |
2428 | file_name: None, | |
2429 | file_stem: None, | |
2430 | extension: None | |
2431 | ); | |
2432 | ||
2433 | t!("foo", | |
2434 | iter: ["foo"], | |
2435 | has_root: false, | |
2436 | is_absolute: false, | |
c34b1796 | 2437 | parent: Some(""), |
85aaf69f SL |
2438 | file_name: Some("foo"), |
2439 | file_stem: Some("foo"), | |
2440 | extension: None | |
2441 | ); | |
2442 | ||
2443 | t!("/", | |
c34b1796 | 2444 | iter: ["/"], |
85aaf69f SL |
2445 | has_root: true, |
2446 | is_absolute: true, | |
2447 | parent: None, | |
2448 | file_name: None, | |
2449 | file_stem: None, | |
2450 | extension: None | |
2451 | ); | |
2452 | ||
2453 | t!("/foo", | |
2454 | iter: ["/", "foo"], | |
2455 | has_root: true, | |
2456 | is_absolute: true, | |
2457 | parent: Some("/"), | |
2458 | file_name: Some("foo"), | |
2459 | file_stem: Some("foo"), | |
2460 | extension: None | |
2461 | ); | |
2462 | ||
2463 | t!("foo/", | |
c34b1796 | 2464 | iter: ["foo"], |
85aaf69f SL |
2465 | has_root: false, |
2466 | is_absolute: false, | |
c34b1796 AL |
2467 | parent: Some(""), |
2468 | file_name: Some("foo"), | |
2469 | file_stem: Some("foo"), | |
85aaf69f SL |
2470 | extension: None |
2471 | ); | |
2472 | ||
2473 | t!("/foo/", | |
c34b1796 | 2474 | iter: ["/", "foo"], |
85aaf69f SL |
2475 | has_root: true, |
2476 | is_absolute: true, | |
c34b1796 AL |
2477 | parent: Some("/"), |
2478 | file_name: Some("foo"), | |
2479 | file_stem: Some("foo"), | |
85aaf69f SL |
2480 | extension: None |
2481 | ); | |
2482 | ||
2483 | t!("foo/bar", | |
2484 | iter: ["foo", "bar"], | |
2485 | has_root: false, | |
2486 | is_absolute: false, | |
2487 | parent: Some("foo"), | |
2488 | file_name: Some("bar"), | |
2489 | file_stem: Some("bar"), | |
2490 | extension: None | |
2491 | ); | |
2492 | ||
2493 | t!("/foo/bar", | |
2494 | iter: ["/", "foo", "bar"], | |
2495 | has_root: true, | |
2496 | is_absolute: true, | |
2497 | parent: Some("/foo"), | |
2498 | file_name: Some("bar"), | |
2499 | file_stem: Some("bar"), | |
2500 | extension: None | |
2501 | ); | |
2502 | ||
2503 | t!("///foo///", | |
c34b1796 | 2504 | iter: ["/", "foo"], |
85aaf69f SL |
2505 | has_root: true, |
2506 | is_absolute: true, | |
c34b1796 AL |
2507 | parent: Some("/"), |
2508 | file_name: Some("foo"), | |
2509 | file_stem: Some("foo"), | |
85aaf69f SL |
2510 | extension: None |
2511 | ); | |
2512 | ||
2513 | t!("///foo///bar", | |
2514 | iter: ["/", "foo", "bar"], | |
2515 | has_root: true, | |
2516 | is_absolute: true, | |
2517 | parent: Some("///foo"), | |
2518 | file_name: Some("bar"), | |
2519 | file_stem: Some("bar"), | |
2520 | extension: None | |
2521 | ); | |
2522 | ||
2523 | t!("./.", | |
c34b1796 | 2524 | iter: ["."], |
85aaf69f SL |
2525 | has_root: false, |
2526 | is_absolute: false, | |
c34b1796 | 2527 | parent: Some(""), |
85aaf69f SL |
2528 | file_name: None, |
2529 | file_stem: None, | |
2530 | extension: None | |
2531 | ); | |
2532 | ||
2533 | t!("/..", | |
2534 | iter: ["/", ".."], | |
2535 | has_root: true, | |
2536 | is_absolute: true, | |
2537 | parent: Some("/"), | |
2538 | file_name: None, | |
2539 | file_stem: None, | |
2540 | extension: None | |
2541 | ); | |
2542 | ||
2543 | t!("../", | |
c34b1796 | 2544 | iter: [".."], |
85aaf69f SL |
2545 | has_root: false, |
2546 | is_absolute: false, | |
c34b1796 | 2547 | parent: Some(""), |
85aaf69f SL |
2548 | file_name: None, |
2549 | file_stem: None, | |
2550 | extension: None | |
2551 | ); | |
2552 | ||
2553 | t!("foo/.", | |
c34b1796 | 2554 | iter: ["foo"], |
85aaf69f SL |
2555 | has_root: false, |
2556 | is_absolute: false, | |
c34b1796 AL |
2557 | parent: Some(""), |
2558 | file_name: Some("foo"), | |
2559 | file_stem: Some("foo"), | |
85aaf69f SL |
2560 | extension: None |
2561 | ); | |
2562 | ||
2563 | t!("foo/..", | |
2564 | iter: ["foo", ".."], | |
2565 | has_root: false, | |
2566 | is_absolute: false, | |
2567 | parent: Some("foo"), | |
2568 | file_name: None, | |
2569 | file_stem: None, | |
2570 | extension: None | |
2571 | ); | |
2572 | ||
2573 | t!("foo/./", | |
c34b1796 | 2574 | iter: ["foo"], |
85aaf69f SL |
2575 | has_root: false, |
2576 | is_absolute: false, | |
c34b1796 AL |
2577 | parent: Some(""), |
2578 | file_name: Some("foo"), | |
2579 | file_stem: Some("foo"), | |
85aaf69f SL |
2580 | extension: None |
2581 | ); | |
2582 | ||
2583 | t!("foo/./bar", | |
c34b1796 | 2584 | iter: ["foo", "bar"], |
85aaf69f SL |
2585 | has_root: false, |
2586 | is_absolute: false, | |
c34b1796 | 2587 | parent: Some("foo"), |
85aaf69f SL |
2588 | file_name: Some("bar"), |
2589 | file_stem: Some("bar"), | |
2590 | extension: None | |
2591 | ); | |
2592 | ||
2593 | t!("foo/../", | |
c34b1796 | 2594 | iter: ["foo", ".."], |
85aaf69f SL |
2595 | has_root: false, |
2596 | is_absolute: false, | |
c34b1796 | 2597 | parent: Some("foo"), |
85aaf69f SL |
2598 | file_name: None, |
2599 | file_stem: None, | |
2600 | extension: None | |
2601 | ); | |
2602 | ||
2603 | t!("foo/../bar", | |
2604 | iter: ["foo", "..", "bar"], | |
2605 | has_root: false, | |
2606 | is_absolute: false, | |
2607 | parent: Some("foo/.."), | |
2608 | file_name: Some("bar"), | |
2609 | file_stem: Some("bar"), | |
2610 | extension: None | |
2611 | ); | |
2612 | ||
2613 | t!("./a", | |
2614 | iter: [".", "a"], | |
2615 | has_root: false, | |
2616 | is_absolute: false, | |
2617 | parent: Some("."), | |
2618 | file_name: Some("a"), | |
2619 | file_stem: Some("a"), | |
2620 | extension: None | |
2621 | ); | |
2622 | ||
2623 | t!(".", | |
2624 | iter: ["."], | |
2625 | has_root: false, | |
2626 | is_absolute: false, | |
c34b1796 | 2627 | parent: Some(""), |
85aaf69f SL |
2628 | file_name: None, |
2629 | file_stem: None, | |
2630 | extension: None | |
2631 | ); | |
2632 | ||
2633 | t!("./", | |
c34b1796 | 2634 | iter: ["."], |
85aaf69f SL |
2635 | has_root: false, |
2636 | is_absolute: false, | |
c34b1796 | 2637 | parent: Some(""), |
85aaf69f SL |
2638 | file_name: None, |
2639 | file_stem: None, | |
2640 | extension: None | |
2641 | ); | |
2642 | ||
2643 | t!("a/b", | |
2644 | iter: ["a", "b"], | |
2645 | has_root: false, | |
2646 | is_absolute: false, | |
2647 | parent: Some("a"), | |
2648 | file_name: Some("b"), | |
2649 | file_stem: Some("b"), | |
2650 | extension: None | |
2651 | ); | |
2652 | ||
2653 | t!("a//b", | |
2654 | iter: ["a", "b"], | |
2655 | has_root: false, | |
2656 | is_absolute: false, | |
2657 | parent: Some("a"), | |
2658 | file_name: Some("b"), | |
2659 | file_stem: Some("b"), | |
2660 | extension: None | |
2661 | ); | |
2662 | ||
2663 | t!("a/./b", | |
c34b1796 | 2664 | iter: ["a", "b"], |
85aaf69f SL |
2665 | has_root: false, |
2666 | is_absolute: false, | |
c34b1796 | 2667 | parent: Some("a"), |
85aaf69f SL |
2668 | file_name: Some("b"), |
2669 | file_stem: Some("b"), | |
2670 | extension: None | |
2671 | ); | |
2672 | ||
2673 | t!("a/b/c", | |
2674 | iter: ["a", "b", "c"], | |
2675 | has_root: false, | |
2676 | is_absolute: false, | |
2677 | parent: Some("a/b"), | |
2678 | file_name: Some("c"), | |
2679 | file_stem: Some("c"), | |
2680 | extension: None | |
2681 | ); | |
c34b1796 AL |
2682 | |
2683 | t!(".foo", | |
2684 | iter: [".foo"], | |
2685 | has_root: false, | |
2686 | is_absolute: false, | |
2687 | parent: Some(""), | |
2688 | file_name: Some(".foo"), | |
2689 | file_stem: Some(".foo"), | |
2690 | extension: None | |
2691 | ); | |
85aaf69f SL |
2692 | } |
2693 | ||
2694 | #[test] | |
2695 | #[cfg(windows)] | |
2696 | pub fn test_decompositions_windows() { | |
2697 | t!("", | |
2698 | iter: [], | |
2699 | has_root: false, | |
2700 | is_absolute: false, | |
2701 | parent: None, | |
2702 | file_name: None, | |
2703 | file_stem: None, | |
2704 | extension: None | |
2705 | ); | |
2706 | ||
2707 | t!("foo", | |
2708 | iter: ["foo"], | |
2709 | has_root: false, | |
2710 | is_absolute: false, | |
c34b1796 | 2711 | parent: Some(""), |
85aaf69f SL |
2712 | file_name: Some("foo"), |
2713 | file_stem: Some("foo"), | |
2714 | extension: None | |
2715 | ); | |
2716 | ||
2717 | t!("/", | |
c34b1796 | 2718 | iter: ["\\"], |
85aaf69f SL |
2719 | has_root: true, |
2720 | is_absolute: false, | |
2721 | parent: None, | |
2722 | file_name: None, | |
2723 | file_stem: None, | |
2724 | extension: None | |
2725 | ); | |
2726 | ||
2727 | t!("\\", | |
c34b1796 | 2728 | iter: ["\\"], |
85aaf69f SL |
2729 | has_root: true, |
2730 | is_absolute: false, | |
2731 | parent: None, | |
2732 | file_name: None, | |
2733 | file_stem: None, | |
2734 | extension: None | |
2735 | ); | |
2736 | ||
2737 | t!("c:", | |
c34b1796 | 2738 | iter: ["c:"], |
85aaf69f SL |
2739 | has_root: false, |
2740 | is_absolute: false, | |
2741 | parent: None, | |
2742 | file_name: None, | |
2743 | file_stem: None, | |
2744 | extension: None | |
2745 | ); | |
2746 | ||
2747 | t!("c:\\", | |
c34b1796 | 2748 | iter: ["c:", "\\"], |
85aaf69f SL |
2749 | has_root: true, |
2750 | is_absolute: true, | |
2751 | parent: None, | |
2752 | file_name: None, | |
2753 | file_stem: None, | |
2754 | extension: None | |
2755 | ); | |
2756 | ||
2757 | t!("c:/", | |
c34b1796 | 2758 | iter: ["c:", "\\"], |
85aaf69f SL |
2759 | has_root: true, |
2760 | is_absolute: true, | |
2761 | parent: None, | |
2762 | file_name: None, | |
2763 | file_stem: None, | |
2764 | extension: None | |
2765 | ); | |
2766 | ||
2767 | t!("/foo", | |
2768 | iter: ["\\", "foo"], | |
2769 | has_root: true, | |
2770 | is_absolute: false, | |
2771 | parent: Some("/"), | |
2772 | file_name: Some("foo"), | |
2773 | file_stem: Some("foo"), | |
2774 | extension: None | |
2775 | ); | |
2776 | ||
2777 | t!("foo/", | |
c34b1796 | 2778 | iter: ["foo"], |
85aaf69f SL |
2779 | has_root: false, |
2780 | is_absolute: false, | |
c34b1796 AL |
2781 | parent: Some(""), |
2782 | file_name: Some("foo"), | |
2783 | file_stem: Some("foo"), | |
85aaf69f SL |
2784 | extension: None |
2785 | ); | |
2786 | ||
2787 | t!("/foo/", | |
c34b1796 | 2788 | iter: ["\\", "foo"], |
85aaf69f SL |
2789 | has_root: true, |
2790 | is_absolute: false, | |
c34b1796 AL |
2791 | parent: Some("/"), |
2792 | file_name: Some("foo"), | |
2793 | file_stem: Some("foo"), | |
85aaf69f SL |
2794 | extension: None |
2795 | ); | |
2796 | ||
2797 | t!("foo/bar", | |
2798 | iter: ["foo", "bar"], | |
2799 | has_root: false, | |
2800 | is_absolute: false, | |
2801 | parent: Some("foo"), | |
2802 | file_name: Some("bar"), | |
2803 | file_stem: Some("bar"), | |
2804 | extension: None | |
2805 | ); | |
2806 | ||
2807 | t!("/foo/bar", | |
2808 | iter: ["\\", "foo", "bar"], | |
2809 | has_root: true, | |
2810 | is_absolute: false, | |
2811 | parent: Some("/foo"), | |
2812 | file_name: Some("bar"), | |
2813 | file_stem: Some("bar"), | |
2814 | extension: None | |
2815 | ); | |
2816 | ||
2817 | t!("///foo///", | |
c34b1796 | 2818 | iter: ["\\", "foo"], |
85aaf69f SL |
2819 | has_root: true, |
2820 | is_absolute: false, | |
c34b1796 AL |
2821 | parent: Some("/"), |
2822 | file_name: Some("foo"), | |
2823 | file_stem: Some("foo"), | |
85aaf69f SL |
2824 | extension: None |
2825 | ); | |
2826 | ||
2827 | t!("///foo///bar", | |
2828 | iter: ["\\", "foo", "bar"], | |
2829 | has_root: true, | |
2830 | is_absolute: false, | |
2831 | parent: Some("///foo"), | |
2832 | file_name: Some("bar"), | |
2833 | file_stem: Some("bar"), | |
2834 | extension: None | |
2835 | ); | |
2836 | ||
2837 | t!("./.", | |
c34b1796 | 2838 | iter: ["."], |
85aaf69f SL |
2839 | has_root: false, |
2840 | is_absolute: false, | |
c34b1796 | 2841 | parent: Some(""), |
85aaf69f SL |
2842 | file_name: None, |
2843 | file_stem: None, | |
2844 | extension: None | |
2845 | ); | |
2846 | ||
2847 | t!("/..", | |
2848 | iter: ["\\", ".."], | |
2849 | has_root: true, | |
2850 | is_absolute: false, | |
2851 | parent: Some("/"), | |
2852 | file_name: None, | |
2853 | file_stem: None, | |
2854 | extension: None | |
2855 | ); | |
2856 | ||
2857 | t!("../", | |
c34b1796 | 2858 | iter: [".."], |
85aaf69f SL |
2859 | has_root: false, |
2860 | is_absolute: false, | |
c34b1796 | 2861 | parent: Some(""), |
85aaf69f SL |
2862 | file_name: None, |
2863 | file_stem: None, | |
2864 | extension: None | |
2865 | ); | |
2866 | ||
2867 | t!("foo/.", | |
c34b1796 | 2868 | iter: ["foo"], |
85aaf69f SL |
2869 | has_root: false, |
2870 | is_absolute: false, | |
c34b1796 AL |
2871 | parent: Some(""), |
2872 | file_name: Some("foo"), | |
2873 | file_stem: Some("foo"), | |
85aaf69f SL |
2874 | extension: None |
2875 | ); | |
2876 | ||
2877 | t!("foo/..", | |
2878 | iter: ["foo", ".."], | |
2879 | has_root: false, | |
2880 | is_absolute: false, | |
2881 | parent: Some("foo"), | |
2882 | file_name: None, | |
2883 | file_stem: None, | |
2884 | extension: None | |
2885 | ); | |
2886 | ||
2887 | t!("foo/./", | |
c34b1796 | 2888 | iter: ["foo"], |
85aaf69f SL |
2889 | has_root: false, |
2890 | is_absolute: false, | |
c34b1796 AL |
2891 | parent: Some(""), |
2892 | file_name: Some("foo"), | |
2893 | file_stem: Some("foo"), | |
85aaf69f SL |
2894 | extension: None |
2895 | ); | |
2896 | ||
2897 | t!("foo/./bar", | |
c34b1796 | 2898 | iter: ["foo", "bar"], |
85aaf69f SL |
2899 | has_root: false, |
2900 | is_absolute: false, | |
c34b1796 | 2901 | parent: Some("foo"), |
85aaf69f SL |
2902 | file_name: Some("bar"), |
2903 | file_stem: Some("bar"), | |
2904 | extension: None | |
2905 | ); | |
2906 | ||
2907 | t!("foo/../", | |
c34b1796 | 2908 | iter: ["foo", ".."], |
85aaf69f SL |
2909 | has_root: false, |
2910 | is_absolute: false, | |
c34b1796 | 2911 | parent: Some("foo"), |
85aaf69f SL |
2912 | file_name: None, |
2913 | file_stem: None, | |
2914 | extension: None | |
2915 | ); | |
2916 | ||
2917 | t!("foo/../bar", | |
2918 | iter: ["foo", "..", "bar"], | |
2919 | has_root: false, | |
2920 | is_absolute: false, | |
2921 | parent: Some("foo/.."), | |
2922 | file_name: Some("bar"), | |
2923 | file_stem: Some("bar"), | |
2924 | extension: None | |
2925 | ); | |
2926 | ||
2927 | t!("./a", | |
2928 | iter: [".", "a"], | |
2929 | has_root: false, | |
2930 | is_absolute: false, | |
2931 | parent: Some("."), | |
2932 | file_name: Some("a"), | |
2933 | file_stem: Some("a"), | |
2934 | extension: None | |
2935 | ); | |
2936 | ||
2937 | t!(".", | |
2938 | iter: ["."], | |
2939 | has_root: false, | |
2940 | is_absolute: false, | |
c34b1796 | 2941 | parent: Some(""), |
85aaf69f SL |
2942 | file_name: None, |
2943 | file_stem: None, | |
2944 | extension: None | |
2945 | ); | |
2946 | ||
2947 | t!("./", | |
c34b1796 | 2948 | iter: ["."], |
85aaf69f SL |
2949 | has_root: false, |
2950 | is_absolute: false, | |
c34b1796 | 2951 | parent: Some(""), |
85aaf69f SL |
2952 | file_name: None, |
2953 | file_stem: None, | |
2954 | extension: None | |
2955 | ); | |
2956 | ||
2957 | t!("a/b", | |
2958 | iter: ["a", "b"], | |
2959 | has_root: false, | |
2960 | is_absolute: false, | |
2961 | parent: Some("a"), | |
2962 | file_name: Some("b"), | |
2963 | file_stem: Some("b"), | |
2964 | extension: None | |
2965 | ); | |
2966 | ||
2967 | t!("a//b", | |
2968 | iter: ["a", "b"], | |
2969 | has_root: false, | |
2970 | is_absolute: false, | |
2971 | parent: Some("a"), | |
2972 | file_name: Some("b"), | |
2973 | file_stem: Some("b"), | |
2974 | extension: None | |
2975 | ); | |
2976 | ||
2977 | t!("a/./b", | |
c34b1796 | 2978 | iter: ["a", "b"], |
85aaf69f SL |
2979 | has_root: false, |
2980 | is_absolute: false, | |
c34b1796 | 2981 | parent: Some("a"), |
85aaf69f SL |
2982 | file_name: Some("b"), |
2983 | file_stem: Some("b"), | |
2984 | extension: None | |
2985 | ); | |
2986 | ||
2987 | t!("a/b/c", | |
2988 | iter: ["a", "b", "c"], | |
2989 | has_root: false, | |
2990 | is_absolute: false, | |
2991 | parent: Some("a/b"), | |
2992 | file_name: Some("c"), | |
2993 | file_stem: Some("c"), | |
2994 | extension: None); | |
2995 | ||
2996 | t!("a\\b\\c", | |
2997 | iter: ["a", "b", "c"], | |
2998 | has_root: false, | |
2999 | is_absolute: false, | |
3000 | parent: Some("a\\b"), | |
3001 | file_name: Some("c"), | |
3002 | file_stem: Some("c"), | |
3003 | extension: None | |
3004 | ); | |
3005 | ||
3006 | t!("\\a", | |
3007 | iter: ["\\", "a"], | |
3008 | has_root: true, | |
3009 | is_absolute: false, | |
3010 | parent: Some("\\"), | |
3011 | file_name: Some("a"), | |
3012 | file_stem: Some("a"), | |
3013 | extension: None | |
3014 | ); | |
3015 | ||
3016 | t!("c:\\foo.txt", | |
3017 | iter: ["c:", "\\", "foo.txt"], | |
3018 | has_root: true, | |
3019 | is_absolute: true, | |
3020 | parent: Some("c:\\"), | |
3021 | file_name: Some("foo.txt"), | |
3022 | file_stem: Some("foo"), | |
3023 | extension: Some("txt") | |
3024 | ); | |
3025 | ||
3026 | t!("\\\\server\\share\\foo.txt", | |
3027 | iter: ["\\\\server\\share", "\\", "foo.txt"], | |
3028 | has_root: true, | |
3029 | is_absolute: true, | |
3030 | parent: Some("\\\\server\\share\\"), | |
3031 | file_name: Some("foo.txt"), | |
3032 | file_stem: Some("foo"), | |
3033 | extension: Some("txt") | |
3034 | ); | |
3035 | ||
3036 | t!("\\\\server\\share", | |
c34b1796 | 3037 | iter: ["\\\\server\\share", "\\"], |
85aaf69f SL |
3038 | has_root: true, |
3039 | is_absolute: true, | |
3040 | parent: None, | |
3041 | file_name: None, | |
3042 | file_stem: None, | |
3043 | extension: None | |
3044 | ); | |
3045 | ||
3046 | t!("\\\\server", | |
3047 | iter: ["\\", "server"], | |
3048 | has_root: true, | |
3049 | is_absolute: false, | |
3050 | parent: Some("\\"), | |
3051 | file_name: Some("server"), | |
3052 | file_stem: Some("server"), | |
3053 | extension: None | |
3054 | ); | |
3055 | ||
3056 | t!("\\\\?\\bar\\foo.txt", | |
3057 | iter: ["\\\\?\\bar", "\\", "foo.txt"], | |
3058 | has_root: true, | |
3059 | is_absolute: true, | |
3060 | parent: Some("\\\\?\\bar\\"), | |
3061 | file_name: Some("foo.txt"), | |
3062 | file_stem: Some("foo"), | |
3063 | extension: Some("txt") | |
3064 | ); | |
3065 | ||
3066 | t!("\\\\?\\bar", | |
3067 | iter: ["\\\\?\\bar"], | |
3068 | has_root: true, | |
3069 | is_absolute: true, | |
3070 | parent: None, | |
3071 | file_name: None, | |
3072 | file_stem: None, | |
3073 | extension: None | |
3074 | ); | |
3075 | ||
3076 | t!("\\\\?\\", | |
3077 | iter: ["\\\\?\\"], | |
3078 | has_root: true, | |
3079 | is_absolute: true, | |
3080 | parent: None, | |
3081 | file_name: None, | |
3082 | file_stem: None, | |
3083 | extension: None | |
3084 | ); | |
3085 | ||
3086 | t!("\\\\?\\UNC\\server\\share\\foo.txt", | |
3087 | iter: ["\\\\?\\UNC\\server\\share", "\\", "foo.txt"], | |
3088 | has_root: true, | |
3089 | is_absolute: true, | |
3090 | parent: Some("\\\\?\\UNC\\server\\share\\"), | |
3091 | file_name: Some("foo.txt"), | |
3092 | file_stem: Some("foo"), | |
3093 | extension: Some("txt") | |
3094 | ); | |
3095 | ||
3096 | t!("\\\\?\\UNC\\server", | |
3097 | iter: ["\\\\?\\UNC\\server"], | |
3098 | has_root: true, | |
3099 | is_absolute: true, | |
3100 | parent: None, | |
3101 | file_name: None, | |
3102 | file_stem: None, | |
3103 | extension: None | |
3104 | ); | |
3105 | ||
3106 | t!("\\\\?\\UNC\\", | |
3107 | iter: ["\\\\?\\UNC\\"], | |
3108 | has_root: true, | |
3109 | is_absolute: true, | |
3110 | parent: None, | |
3111 | file_name: None, | |
3112 | file_stem: None, | |
3113 | extension: None | |
3114 | ); | |
3115 | ||
3116 | t!("\\\\?\\C:\\foo.txt", | |
3117 | iter: ["\\\\?\\C:", "\\", "foo.txt"], | |
3118 | has_root: true, | |
3119 | is_absolute: true, | |
3120 | parent: Some("\\\\?\\C:\\"), | |
3121 | file_name: Some("foo.txt"), | |
3122 | file_stem: Some("foo"), | |
3123 | extension: Some("txt") | |
3124 | ); | |
3125 | ||
3126 | ||
3127 | t!("\\\\?\\C:\\", | |
c34b1796 | 3128 | iter: ["\\\\?\\C:", "\\"], |
85aaf69f SL |
3129 | has_root: true, |
3130 | is_absolute: true, | |
3131 | parent: None, | |
3132 | file_name: None, | |
3133 | file_stem: None, | |
3134 | extension: None | |
3135 | ); | |
3136 | ||
3137 | ||
3138 | t!("\\\\?\\C:", | |
3139 | iter: ["\\\\?\\C:"], | |
3140 | has_root: true, | |
3141 | is_absolute: true, | |
3142 | parent: None, | |
3143 | file_name: None, | |
3144 | file_stem: None, | |
3145 | extension: None | |
3146 | ); | |
3147 | ||
3148 | ||
3149 | t!("\\\\?\\foo/bar", | |
3150 | iter: ["\\\\?\\foo/bar"], | |
3151 | has_root: true, | |
3152 | is_absolute: true, | |
3153 | parent: None, | |
3154 | file_name: None, | |
3155 | file_stem: None, | |
3156 | extension: None | |
3157 | ); | |
3158 | ||
3159 | ||
3160 | t!("\\\\?\\C:/foo", | |
3161 | iter: ["\\\\?\\C:/foo"], | |
3162 | has_root: true, | |
3163 | is_absolute: true, | |
3164 | parent: None, | |
3165 | file_name: None, | |
3166 | file_stem: None, | |
3167 | extension: None | |
3168 | ); | |
3169 | ||
3170 | ||
3171 | t!("\\\\.\\foo\\bar", | |
3172 | iter: ["\\\\.\\foo", "\\", "bar"], | |
3173 | has_root: true, | |
3174 | is_absolute: true, | |
3175 | parent: Some("\\\\.\\foo\\"), | |
3176 | file_name: Some("bar"), | |
3177 | file_stem: Some("bar"), | |
3178 | extension: None | |
3179 | ); | |
3180 | ||
3181 | ||
3182 | t!("\\\\.\\foo", | |
c34b1796 | 3183 | iter: ["\\\\.\\foo", "\\"], |
85aaf69f SL |
3184 | has_root: true, |
3185 | is_absolute: true, | |
3186 | parent: None, | |
3187 | file_name: None, | |
3188 | file_stem: None, | |
3189 | extension: None | |
3190 | ); | |
3191 | ||
3192 | ||
3193 | t!("\\\\.\\foo/bar", | |
c34b1796 | 3194 | iter: ["\\\\.\\foo/bar", "\\"], |
85aaf69f SL |
3195 | has_root: true, |
3196 | is_absolute: true, | |
3197 | parent: None, | |
3198 | file_name: None, | |
3199 | file_stem: None, | |
3200 | extension: None | |
3201 | ); | |
3202 | ||
3203 | ||
3204 | t!("\\\\.\\foo\\bar/baz", | |
3205 | iter: ["\\\\.\\foo", "\\", "bar", "baz"], | |
3206 | has_root: true, | |
3207 | is_absolute: true, | |
3208 | parent: Some("\\\\.\\foo\\bar"), | |
3209 | file_name: Some("baz"), | |
3210 | file_stem: Some("baz"), | |
3211 | extension: None | |
3212 | ); | |
3213 | ||
3214 | ||
3215 | t!("\\\\.\\", | |
c34b1796 | 3216 | iter: ["\\\\.\\", "\\"], |
85aaf69f SL |
3217 | has_root: true, |
3218 | is_absolute: true, | |
3219 | parent: None, | |
3220 | file_name: None, | |
3221 | file_stem: None, | |
3222 | extension: None | |
3223 | ); | |
3224 | ||
3225 | t!("\\\\?\\a\\b\\", | |
c34b1796 | 3226 | iter: ["\\\\?\\a", "\\", "b"], |
85aaf69f SL |
3227 | has_root: true, |
3228 | is_absolute: true, | |
c34b1796 AL |
3229 | parent: Some("\\\\?\\a\\"), |
3230 | file_name: Some("b"), | |
3231 | file_stem: Some("b"), | |
85aaf69f SL |
3232 | extension: None |
3233 | ); | |
3234 | } | |
3235 | ||
3236 | #[test] | |
3237 | pub fn test_stem_ext() { | |
3238 | t!("foo", | |
3239 | file_stem: Some("foo"), | |
3240 | extension: None | |
3241 | ); | |
3242 | ||
3243 | t!("foo.", | |
3244 | file_stem: Some("foo"), | |
3245 | extension: Some("") | |
3246 | ); | |
3247 | ||
3248 | t!(".foo", | |
3249 | file_stem: Some(".foo"), | |
3250 | extension: None | |
3251 | ); | |
3252 | ||
3253 | t!("foo.txt", | |
3254 | file_stem: Some("foo"), | |
3255 | extension: Some("txt") | |
3256 | ); | |
3257 | ||
3258 | t!("foo.bar.txt", | |
3259 | file_stem: Some("foo.bar"), | |
3260 | extension: Some("txt") | |
3261 | ); | |
3262 | ||
3263 | t!("foo.bar.", | |
3264 | file_stem: Some("foo.bar"), | |
3265 | extension: Some("") | |
3266 | ); | |
3267 | ||
3268 | t!(".", | |
3269 | file_stem: None, | |
3270 | extension: None | |
3271 | ); | |
3272 | ||
3273 | t!("..", | |
3274 | file_stem: None, | |
3275 | extension: None | |
3276 | ); | |
3277 | ||
3278 | t!("", | |
3279 | file_stem: None, | |
3280 | extension: None | |
3281 | ); | |
3282 | } | |
3283 | ||
3284 | #[test] | |
3285 | pub fn test_push() { | |
3286 | macro_rules! tp( | |
3287 | ($path:expr, $push:expr, $expected:expr) => ( { | |
c34b1796 | 3288 | let mut actual = PathBuf::from($path); |
85aaf69f SL |
3289 | actual.push($push); |
3290 | assert!(actual.to_str() == Some($expected), | |
3291 | "pushing {:?} onto {:?}: Expected {:?}, got {:?}", | |
3292 | $push, $path, $expected, actual.to_str().unwrap()); | |
3293 | }); | |
3294 | ); | |
3295 | ||
3296 | if cfg!(unix) { | |
3297 | tp!("", "foo", "foo"); | |
3298 | tp!("foo", "bar", "foo/bar"); | |
3299 | tp!("foo/", "bar", "foo/bar"); | |
3300 | tp!("foo//", "bar", "foo//bar"); | |
3301 | tp!("foo/.", "bar", "foo/./bar"); | |
3302 | tp!("foo./.", "bar", "foo././bar"); | |
3303 | tp!("foo", "", "foo/"); | |
3304 | tp!("foo", ".", "foo/."); | |
3305 | tp!("foo", "..", "foo/.."); | |
3306 | tp!("foo", "/", "/"); | |
3307 | tp!("/foo/bar", "/", "/"); | |
3308 | tp!("/foo/bar", "/baz", "/baz"); | |
3309 | tp!("/foo/bar", "./baz", "/foo/bar/./baz"); | |
3310 | } else { | |
3311 | tp!("", "foo", "foo"); | |
3312 | tp!("foo", "bar", r"foo\bar"); | |
3313 | tp!("foo/", "bar", r"foo/bar"); | |
3314 | tp!(r"foo\", "bar", r"foo\bar"); | |
3315 | tp!("foo//", "bar", r"foo//bar"); | |
3316 | tp!(r"foo\\", "bar", r"foo\\bar"); | |
3317 | tp!("foo/.", "bar", r"foo/.\bar"); | |
3318 | tp!("foo./.", "bar", r"foo./.\bar"); | |
3319 | tp!(r"foo\.", "bar", r"foo\.\bar"); | |
3320 | tp!(r"foo.\.", "bar", r"foo.\.\bar"); | |
3321 | tp!("foo", "", "foo\\"); | |
3322 | tp!("foo", ".", r"foo\."); | |
3323 | tp!("foo", "..", r"foo\.."); | |
3324 | tp!("foo", "/", "/"); | |
3325 | tp!("foo", r"\", r"\"); | |
3326 | tp!("/foo/bar", "/", "/"); | |
3327 | tp!(r"\foo\bar", r"\", r"\"); | |
3328 | tp!("/foo/bar", "/baz", "/baz"); | |
3329 | tp!("/foo/bar", r"\baz", r"\baz"); | |
3330 | tp!("/foo/bar", "./baz", r"/foo/bar\./baz"); | |
3331 | tp!("/foo/bar", r".\baz", r"/foo/bar\.\baz"); | |
3332 | ||
3333 | tp!("c:\\", "windows", "c:\\windows"); | |
3334 | tp!("c:", "windows", "c:windows"); | |
3335 | ||
3336 | tp!("a\\b\\c", "d", "a\\b\\c\\d"); | |
3337 | tp!("\\a\\b\\c", "d", "\\a\\b\\c\\d"); | |
3338 | tp!("a\\b", "c\\d", "a\\b\\c\\d"); | |
3339 | tp!("a\\b", "\\c\\d", "\\c\\d"); | |
3340 | tp!("a\\b", ".", "a\\b\\."); | |
3341 | tp!("a\\b", "..\\c", "a\\b\\..\\c"); | |
3342 | tp!("a\\b", "C:a.txt", "C:a.txt"); | |
3343 | tp!("a\\b", "C:\\a.txt", "C:\\a.txt"); | |
3344 | tp!("C:\\a", "C:\\b.txt", "C:\\b.txt"); | |
3345 | tp!("C:\\a\\b\\c", "C:d", "C:d"); | |
3346 | tp!("C:a\\b\\c", "C:d", "C:d"); | |
3347 | tp!("C:", r"a\b\c", r"C:a\b\c"); | |
3348 | tp!("C:", r"..\a", r"C:..\a"); | |
92a42be0 SL |
3349 | tp!("\\\\server\\share\\foo", |
3350 | "bar", | |
3351 | "\\\\server\\share\\foo\\bar"); | |
85aaf69f SL |
3352 | tp!("\\\\server\\share\\foo", "C:baz", "C:baz"); |
3353 | tp!("\\\\?\\C:\\a\\b", "C:c\\d", "C:c\\d"); | |
3354 | tp!("\\\\?\\C:a\\b", "C:c\\d", "C:c\\d"); | |
3355 | tp!("\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d"); | |
3356 | tp!("\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz"); | |
92a42be0 SL |
3357 | tp!("\\\\?\\UNC\\server\\share\\foo", |
3358 | "bar", | |
3359 | "\\\\?\\UNC\\server\\share\\foo\\bar"); | |
85aaf69f SL |
3360 | tp!("\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a"); |
3361 | tp!("\\\\?\\UNC\\server\\share", "C:a", "C:a"); | |
3362 | ||
3363 | // Note: modified from old path API | |
3364 | tp!("\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\foo"); | |
3365 | ||
92a42be0 SL |
3366 | tp!("C:\\a", |
3367 | "\\\\?\\UNC\\server\\share", | |
3368 | "\\\\?\\UNC\\server\\share"); | |
85aaf69f SL |
3369 | tp!("\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz"); |
3370 | tp!("\\\\.\\foo\\bar", "C:a", "C:a"); | |
3371 | // again, not sure about the following, but I'm assuming \\.\ should be verbatim | |
3372 | tp!("\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar"); | |
3373 | ||
3374 | tp!("\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one | |
3375 | } | |
3376 | } | |
3377 | ||
3378 | #[test] | |
3379 | pub fn test_pop() { | |
3380 | macro_rules! tp( | |
3381 | ($path:expr, $expected:expr, $output:expr) => ( { | |
c34b1796 | 3382 | let mut actual = PathBuf::from($path); |
85aaf69f SL |
3383 | let output = actual.pop(); |
3384 | assert!(actual.to_str() == Some($expected) && output == $output, | |
3385 | "popping from {:?}: Expected {:?}/{:?}, got {:?}/{:?}", | |
3386 | $path, $expected, $output, | |
3387 | actual.to_str().unwrap(), output); | |
3388 | }); | |
3389 | ); | |
3390 | ||
3391 | tp!("", "", false); | |
3392 | tp!("/", "/", false); | |
c34b1796 AL |
3393 | tp!("foo", "", true); |
3394 | tp!(".", "", true); | |
85aaf69f SL |
3395 | tp!("/foo", "/", true); |
3396 | tp!("/foo/bar", "/foo", true); | |
3397 | tp!("foo/bar", "foo", true); | |
c34b1796 | 3398 | tp!("foo/.", "", true); |
85aaf69f SL |
3399 | tp!("foo//bar", "foo", true); |
3400 | ||
3401 | if cfg!(windows) { | |
3402 | tp!("a\\b\\c", "a\\b", true); | |
3403 | tp!("\\a", "\\", true); | |
3404 | tp!("\\", "\\", false); | |
3405 | ||
3406 | tp!("C:\\a\\b", "C:\\a", true); | |
3407 | tp!("C:\\a", "C:\\", true); | |
3408 | tp!("C:\\", "C:\\", false); | |
3409 | tp!("C:a\\b", "C:a", true); | |
3410 | tp!("C:a", "C:", true); | |
3411 | tp!("C:", "C:", false); | |
3412 | tp!("\\\\server\\share\\a\\b", "\\\\server\\share\\a", true); | |
3413 | tp!("\\\\server\\share\\a", "\\\\server\\share\\", true); | |
3414 | tp!("\\\\server\\share", "\\\\server\\share", false); | |
3415 | tp!("\\\\?\\a\\b\\c", "\\\\?\\a\\b", true); | |
3416 | tp!("\\\\?\\a\\b", "\\\\?\\a\\", true); | |
3417 | tp!("\\\\?\\a", "\\\\?\\a", false); | |
3418 | tp!("\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true); | |
3419 | tp!("\\\\?\\C:\\a", "\\\\?\\C:\\", true); | |
3420 | tp!("\\\\?\\C:\\", "\\\\?\\C:\\", false); | |
92a42be0 SL |
3421 | tp!("\\\\?\\UNC\\server\\share\\a\\b", |
3422 | "\\\\?\\UNC\\server\\share\\a", | |
3423 | true); | |
3424 | tp!("\\\\?\\UNC\\server\\share\\a", | |
3425 | "\\\\?\\UNC\\server\\share\\", | |
3426 | true); | |
3427 | tp!("\\\\?\\UNC\\server\\share", | |
3428 | "\\\\?\\UNC\\server\\share", | |
3429 | false); | |
85aaf69f SL |
3430 | tp!("\\\\.\\a\\b\\c", "\\\\.\\a\\b", true); |
3431 | tp!("\\\\.\\a\\b", "\\\\.\\a\\", true); | |
3432 | tp!("\\\\.\\a", "\\\\.\\a", false); | |
3433 | ||
c34b1796 | 3434 | tp!("\\\\?\\a\\b\\", "\\\\?\\a\\", true); |
85aaf69f SL |
3435 | } |
3436 | } | |
3437 | ||
3438 | #[test] | |
3439 | pub fn test_set_file_name() { | |
3440 | macro_rules! tfn( | |
3441 | ($path:expr, $file:expr, $expected:expr) => ( { | |
c34b1796 | 3442 | let mut p = PathBuf::from($path); |
85aaf69f SL |
3443 | p.set_file_name($file); |
3444 | assert!(p.to_str() == Some($expected), | |
3445 | "setting file name of {:?} to {:?}: Expected {:?}, got {:?}", | |
3446 | $path, $file, $expected, | |
3447 | p.to_str().unwrap()); | |
3448 | }); | |
3449 | ); | |
3450 | ||
3451 | tfn!("foo", "foo", "foo"); | |
3452 | tfn!("foo", "bar", "bar"); | |
3453 | tfn!("foo", "", ""); | |
3454 | tfn!("", "foo", "foo"); | |
3455 | if cfg!(unix) { | |
3456 | tfn!(".", "foo", "./foo"); | |
c34b1796 AL |
3457 | tfn!("foo/", "bar", "bar"); |
3458 | tfn!("foo/.", "bar", "bar"); | |
85aaf69f SL |
3459 | tfn!("..", "foo", "../foo"); |
3460 | tfn!("foo/..", "bar", "foo/../bar"); | |
3461 | tfn!("/", "foo", "/foo"); | |
3462 | } else { | |
3463 | tfn!(".", "foo", r".\foo"); | |
c34b1796 AL |
3464 | tfn!(r"foo\", "bar", r"bar"); |
3465 | tfn!(r"foo\.", "bar", r"bar"); | |
85aaf69f SL |
3466 | tfn!("..", "foo", r"..\foo"); |
3467 | tfn!(r"foo\..", "bar", r"foo\..\bar"); | |
3468 | tfn!(r"\", "foo", r"\foo"); | |
3469 | } | |
3470 | } | |
3471 | ||
3472 | #[test] | |
3473 | pub fn test_set_extension() { | |
3474 | macro_rules! tfe( | |
3475 | ($path:expr, $ext:expr, $expected:expr, $output:expr) => ( { | |
c34b1796 | 3476 | let mut p = PathBuf::from($path); |
85aaf69f SL |
3477 | let output = p.set_extension($ext); |
3478 | assert!(p.to_str() == Some($expected) && output == $output, | |
3479 | "setting extension of {:?} to {:?}: Expected {:?}/{:?}, got {:?}/{:?}", | |
3480 | $path, $ext, $expected, $output, | |
3481 | p.to_str().unwrap(), output); | |
3482 | }); | |
3483 | ); | |
3484 | ||
3485 | tfe!("foo", "txt", "foo.txt", true); | |
3486 | tfe!("foo.bar", "txt", "foo.txt", true); | |
3487 | tfe!("foo.bar.baz", "txt", "foo.bar.txt", true); | |
3488 | tfe!(".test", "txt", ".test.txt", true); | |
3489 | tfe!("foo.txt", "", "foo", true); | |
3490 | tfe!("foo", "", "foo", true); | |
3491 | tfe!("", "foo", "", false); | |
3492 | tfe!(".", "foo", ".", false); | |
c34b1796 AL |
3493 | tfe!("foo/", "bar", "foo.bar", true); |
3494 | tfe!("foo/.", "bar", "foo.bar", true); | |
92a42be0 | 3495 | tfe!("..", "foo", "..", false); |
85aaf69f SL |
3496 | tfe!("foo/..", "bar", "foo/..", false); |
3497 | tfe!("/", "foo", "/", false); | |
3498 | } | |
3499 | ||
92a42be0 SL |
3500 | #[test] |
3501 | fn test_eq_recievers() { | |
3502 | use borrow::Cow; | |
3503 | ||
3504 | let borrowed: &Path = Path::new("foo/bar"); | |
3505 | let mut owned: PathBuf = PathBuf::new(); | |
3506 | owned.push("foo"); | |
3507 | owned.push("bar"); | |
3508 | let borrowed_cow: Cow<Path> = borrowed.into(); | |
3509 | let owned_cow: Cow<Path> = owned.clone().into(); | |
3510 | ||
3511 | macro_rules! t { | |
3512 | ($($current:expr),+) => { | |
3513 | $( | |
3514 | assert_eq!($current, borrowed); | |
3515 | assert_eq!($current, owned); | |
3516 | assert_eq!($current, borrowed_cow); | |
3517 | assert_eq!($current, owned_cow); | |
3518 | )+ | |
3519 | } | |
3520 | } | |
3521 | ||
3522 | t!(borrowed, owned, borrowed_cow, owned_cow); | |
3523 | } | |
3524 | ||
85aaf69f SL |
3525 | #[test] |
3526 | pub fn test_compare() { | |
9e0c209e SL |
3527 | use hash::{Hash, Hasher}; |
3528 | use collections::hash_map::DefaultHasher; | |
92a42be0 SL |
3529 | |
3530 | fn hash<T: Hash>(t: T) -> u64 { | |
9e0c209e | 3531 | let mut s = DefaultHasher::new(); |
92a42be0 SL |
3532 | t.hash(&mut s); |
3533 | s.finish() | |
3534 | } | |
3535 | ||
85aaf69f SL |
3536 | macro_rules! tc( |
3537 | ($path1:expr, $path2:expr, eq: $eq:expr, | |
3538 | starts_with: $starts_with:expr, ends_with: $ends_with:expr, | |
3539 | relative_from: $relative_from:expr) => ({ | |
3540 | let path1 = Path::new($path1); | |
3541 | let path2 = Path::new($path2); | |
3542 | ||
3543 | let eq = path1 == path2; | |
3544 | assert!(eq == $eq, "{:?} == {:?}, expected {:?}, got {:?}", | |
3545 | $path1, $path2, $eq, eq); | |
92a42be0 SL |
3546 | assert!($eq == (hash(path1) == hash(path2)), |
3547 | "{:?} == {:?}, expected {:?}, got {} and {}", | |
3548 | $path1, $path2, $eq, hash(path1), hash(path2)); | |
85aaf69f SL |
3549 | |
3550 | let starts_with = path1.starts_with(path2); | |
3551 | assert!(starts_with == $starts_with, | |
3552 | "{:?}.starts_with({:?}), expected {:?}, got {:?}", $path1, $path2, | |
3553 | $starts_with, starts_with); | |
3554 | ||
3555 | let ends_with = path1.ends_with(path2); | |
3556 | assert!(ends_with == $ends_with, | |
3557 | "{:?}.ends_with({:?}), expected {:?}, got {:?}", $path1, $path2, | |
3558 | $ends_with, ends_with); | |
3559 | ||
7453a54e SL |
3560 | let relative_from = path1.strip_prefix(path2) |
3561 | .map(|p| p.to_str().unwrap()) | |
3562 | .ok(); | |
85aaf69f SL |
3563 | let exp: Option<&str> = $relative_from; |
3564 | assert!(relative_from == exp, | |
7453a54e SL |
3565 | "{:?}.strip_prefix({:?}), expected {:?}, got {:?}", |
3566 | $path1, $path2, exp, relative_from); | |
85aaf69f SL |
3567 | }); |
3568 | ); | |
3569 | ||
3570 | tc!("", "", | |
3571 | eq: true, | |
3572 | starts_with: true, | |
3573 | ends_with: true, | |
3574 | relative_from: Some("") | |
3575 | ); | |
3576 | ||
3577 | tc!("foo", "", | |
3578 | eq: false, | |
3579 | starts_with: true, | |
3580 | ends_with: true, | |
3581 | relative_from: Some("foo") | |
3582 | ); | |
3583 | ||
3584 | tc!("", "foo", | |
3585 | eq: false, | |
3586 | starts_with: false, | |
3587 | ends_with: false, | |
3588 | relative_from: None | |
3589 | ); | |
3590 | ||
3591 | tc!("foo", "foo", | |
3592 | eq: true, | |
3593 | starts_with: true, | |
3594 | ends_with: true, | |
3595 | relative_from: Some("") | |
3596 | ); | |
3597 | ||
3598 | tc!("foo/", "foo", | |
c34b1796 | 3599 | eq: true, |
85aaf69f | 3600 | starts_with: true, |
c34b1796 AL |
3601 | ends_with: true, |
3602 | relative_from: Some("") | |
85aaf69f SL |
3603 | ); |
3604 | ||
3605 | tc!("foo/bar", "foo", | |
3606 | eq: false, | |
3607 | starts_with: true, | |
3608 | ends_with: false, | |
3609 | relative_from: Some("bar") | |
3610 | ); | |
3611 | ||
3612 | tc!("foo/bar/baz", "foo/bar", | |
3613 | eq: false, | |
3614 | starts_with: true, | |
3615 | ends_with: false, | |
3616 | relative_from: Some("baz") | |
3617 | ); | |
3618 | ||
3619 | tc!("foo/bar", "foo/bar/baz", | |
3620 | eq: false, | |
3621 | starts_with: false, | |
3622 | ends_with: false, | |
3623 | relative_from: None | |
3624 | ); | |
3625 | ||
3626 | tc!("./foo/bar/", ".", | |
3627 | eq: false, | |
3628 | starts_with: true, | |
c34b1796 AL |
3629 | ends_with: false, |
3630 | relative_from: Some("foo/bar") | |
85aaf69f | 3631 | ); |
c34b1796 AL |
3632 | |
3633 | if cfg!(windows) { | |
3634 | tc!(r"C:\src\rust\cargo-test\test\Cargo.toml", | |
3635 | r"c:\src\rust\cargo-test\test", | |
3636 | eq: false, | |
3637 | starts_with: true, | |
3638 | ends_with: false, | |
3639 | relative_from: Some("Cargo.toml") | |
3640 | ); | |
3641 | ||
3642 | tc!(r"c:\foo", r"C:\foo", | |
3643 | eq: true, | |
3644 | starts_with: true, | |
3645 | ends_with: true, | |
3646 | relative_from: Some("") | |
3647 | ); | |
3648 | } | |
85aaf69f | 3649 | } |
9e0c209e SL |
3650 | |
3651 | #[test] | |
3652 | fn test_components_debug() { | |
3653 | let path = Path::new("/tmp"); | |
3654 | ||
3655 | let mut components = path.components(); | |
3656 | ||
3657 | let expected = "Components([RootDir, Normal(\"tmp\")])"; | |
3658 | let actual = format!("{:?}", components); | |
3659 | assert_eq!(expected, actual); | |
3660 | ||
3661 | let _ = components.next().unwrap(); | |
3662 | let expected = "Components([Normal(\"tmp\")])"; | |
3663 | let actual = format!("{:?}", components); | |
3664 | assert_eq!(expected, actual); | |
3665 | ||
3666 | let _ = components.next().unwrap(); | |
3667 | let expected = "Components([])"; | |
3668 | let actual = format!("{:?}", components); | |
3669 | assert_eq!(expected, actual); | |
3670 | } | |
3671 | ||
3672 | #[cfg(unix)] | |
3673 | #[test] | |
3674 | fn test_iter_debug() { | |
3675 | let path = Path::new("/tmp"); | |
3676 | ||
3677 | let mut iter = path.iter(); | |
3678 | ||
3679 | let expected = "Iter([\"/\", \"tmp\"])"; | |
3680 | let actual = format!("{:?}", iter); | |
3681 | assert_eq!(expected, actual); | |
3682 | ||
3683 | let _ = iter.next().unwrap(); | |
3684 | let expected = "Iter([\"tmp\"])"; | |
3685 | let actual = format!("{:?}", iter); | |
3686 | assert_eq!(expected, actual); | |
3687 | ||
3688 | let _ = iter.next().unwrap(); | |
3689 | let expected = "Iter([])"; | |
3690 | let actual = format!("{:?}", iter); | |
3691 | assert_eq!(expected, actual); | |
3692 | } | |
8bb4bdeb XL |
3693 | |
3694 | #[test] | |
3695 | fn into_boxed() { | |
3696 | let orig: &str = "some/sort/of/path"; | |
3697 | let path = Path::new(orig); | |
3698 | let path_buf = path.to_owned(); | |
3699 | let box1: Box<Path> = Box::from(path); | |
3700 | let box2 = path_buf.into_boxed_path(); | |
3701 | assert_eq!(path, &*box1); | |
3702 | assert_eq!(box1, box2); | |
3703 | assert_eq!(&*box2, path); | |
3704 | } | |
85aaf69f | 3705 | } |