1 // Copyright 2013-2014 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.
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.
11 // ignore-lexer-test FIXME #15883
13 //! Windows file path handling
16 use c_str::{CString, ToCStr};
18 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
19 use collections::{Collection, MutableSeq};
20 use from_str::FromStr;
23 use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Iterator, Map};
25 use option::{Option, Some, None};
26 use slice::{Slice, ImmutableSlice};
27 use str::{CharSplits, Str, StrAllocating, StrVector, StrSlice};
29 use unicode::char::UnicodeChar;
32 use super::{contains_nul, BytesContainer, GenericPath, GenericPathUnsafe};
34 /// Iterator that yields successive components of a Path as &str
36 /// Each component is yielded as Option<&str> for compatibility with PosixPath, but
37 /// every component in WindowsPath is guaranteed to be Some.
38 pub type StrComponents<'a> = Map<'a, &'a str, Option<&'a str>,
39 CharSplits<'a, char>>;
41 /// Iterator that yields successive components of a Path as &[u8]
42 pub type Components<'a> = Map<'a, Option<&'a str>, &'a [u8],
45 /// Represents a Windows path
46 // Notes for Windows path impl:
47 // The MAX_PATH is 260, but 253 is the practical limit due to some API bugs
48 // See http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx for good information
49 // about windows paths.
50 // That same page puts a bunch of restrictions on allowed characters in a path.
51 // `\foo.txt` means "relative to current drive", but will not be considered to be absolute here
52 // as `∃P | P.join("\foo.txt") != "\foo.txt"`.
53 // `C:` is interesting, that means "the current directory on drive C".
54 // Long absolute paths need to have \\?\ prefix (or, for UNC, \\?\UNC\). I think that can be
55 // ignored for now, though, and only added in a hypothetical .to_pwstr() function.
56 // However, if a path is parsed that has \\?\, this needs to be preserved as it disables the
57 // processing of "." and ".." components and / as a separator.
58 // Experimentally, \\?\foo is not the same thing as \foo.
59 // Also, \\foo is not valid either (certainly not equivalent to \foo).
60 // Similarly, C:\\Users is not equivalent to C:\Users, although C:\Users\\foo is equivalent
61 // to C:\Users\foo. In fact the command prompt treats C:\\foo\bar as UNC path. But it might be
62 // best to just ignore that and normalize it to C:\foo\bar.
64 // Based on all this, I think the right approach is to do the following:
65 // * Require valid utf-8 paths. Windows API may use WCHARs, but we don't, and utf-8 is convertible
66 // to UTF-16 anyway (though does Windows use UTF-16 or UCS-2? Not sure).
67 // * Parse the prefixes \\?\UNC\, \\?\, and \\.\ explicitly.
68 // * If \\?\UNC\, treat following two path components as server\share. Don't error for missing
70 // * If \\?\, parse disk from following component, if present. Don't error for missing disk.
71 // * If \\.\, treat rest of path as just regular components. I don't know how . and .. are handled
72 // here, they probably aren't, but I'm not going to worry about that.
73 // * Else if starts with \\, treat following two components as server\share. Don't error for missing
75 // * Otherwise, attempt to parse drive from start of path.
77 // The only error condition imposed here is valid utf-8. All other invalid paths are simply
78 // preserved by the data structure; let the Windows API error out on them.
81 repr: String, // assumed to never be empty
82 prefix: Option<PathPrefix>,
83 sepidx: Option<uint> // index of the final separator in the non-prefix portion of repr
86 impl PartialEq for Path {
88 fn eq(&self, other: &Path) -> bool {
89 self.repr == other.repr
95 impl PartialOrd for Path {
96 fn partial_cmp(&self, other: &Path) -> Option<Ordering> {
102 fn cmp(&self, other: &Path) -> Ordering {
103 self.repr.cmp(&other.repr)
107 impl FromStr for Path {
108 fn from_str(s: &str) -> Option<Path> {
113 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
114 // we cannot usefully take ToCStr arguments by reference (without forcing an
115 // additional & around &str). So we are instead temporarily adding an instance
116 // for &Path, so that we can take ToCStr as owned. When DST lands, the &Path
117 // instance should be removed, and arguments bound by ToCStr should be passed by
120 impl ToCStr for Path {
122 fn to_c_str(&self) -> CString {
123 // The Path impl guarantees no internal NUL
124 unsafe { self.to_c_str_unchecked() }
128 unsafe fn to_c_str_unchecked(&self) -> CString {
129 self.as_vec().to_c_str_unchecked()
133 impl<'a> ToCStr for &'a Path {
135 fn to_c_str(&self) -> CString {
140 unsafe fn to_c_str_unchecked(&self) -> CString {
141 (*self).to_c_str_unchecked()
145 impl<S: hash::Writer> hash::Hash<S> for Path {
148 fn hash(&self, state: &mut S) {
149 self.repr.hash(state)
154 fn hash(&self, _: &mut S) {
155 // No-op because the `hash` implementation will be wrong.
159 impl BytesContainer for Path {
161 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
165 fn container_into_owned_bytes(self) -> Vec<u8> {
169 fn container_as_str<'a>(&'a self) -> Option<&'a str> {
173 fn is_str(_: Option<Path>) -> bool { true }
176 impl<'a> BytesContainer for &'a Path {
178 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
182 fn container_as_str<'a>(&'a self) -> Option<&'a str> {
186 fn is_str(_: Option<&'a Path>) -> bool { true }
189 impl GenericPathUnsafe for Path {
190 /// See `GenericPathUnsafe::from_vec_unchecked`.
194 /// Fails if not valid UTF-8.
196 unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
197 let (prefix, path) = Path::normalize_(path.container_as_str().unwrap());
198 assert!(!path.is_empty());
199 let mut ret = Path{ repr: path, prefix: prefix, sepidx: None };
204 /// See `GenericPathUnsafe::set_filename_unchecked`.
208 /// Fails if not valid UTF-8.
209 unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
210 let filename = filename.container_as_str().unwrap();
211 match self.sepidx_or_prefix_len() {
212 None if ".." == self.repr.as_slice() => {
213 let mut s = String::with_capacity(3 + filename.len());
216 s.push_str(filename);
217 self.update_normalized(s);
220 self.update_normalized(filename);
222 Some((_,idxa,end)) if self.repr.as_slice().slice(idxa,end) == ".." => {
223 let mut s = String::with_capacity(end + 1 + filename.len());
224 s.push_str(self.repr.as_slice().slice_to(end));
226 s.push_str(filename);
227 self.update_normalized(s);
229 Some((idxb,idxa,_)) if self.prefix == Some(DiskPrefix) && idxa == self.prefix_len() => {
230 let mut s = String::with_capacity(idxb + filename.len());
231 s.push_str(self.repr.as_slice().slice_to(idxb));
232 s.push_str(filename);
233 self.update_normalized(s);
235 Some((idxb,_,_)) => {
236 let mut s = String::with_capacity(idxb + 1 + filename.len());
237 s.push_str(self.repr.as_slice().slice_to(idxb));
239 s.push_str(filename);
240 self.update_normalized(s);
245 /// See `GenericPathUnsafe::push_unchecked`.
247 /// Concatenating two Windows Paths is rather complicated.
248 /// For the most part, it will behave as expected, except in the case of
249 /// pushing a volume-relative path, e.g. `C:foo.txt`. Because we have no
250 /// concept of per-volume cwds like Windows does, we can't behave exactly
251 /// like Windows will. Instead, if the receiver is an absolute path on
252 /// the same volume as the new path, it will be treated as the cwd that
253 /// the new path is relative to. Otherwise, the new path will be treated
254 /// as if it were absolute and will replace the receiver outright.
255 unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
256 let path = path.container_as_str().unwrap();
257 fn is_vol_abs(path: &str, prefix: Option<PathPrefix>) -> bool {
258 // assume prefix is Some(DiskPrefix)
259 let rest = path.slice_from(prefix_len(prefix));
260 !rest.is_empty() && rest.as_bytes()[0].is_ascii() && is_sep(rest.as_bytes()[0] as char)
262 fn shares_volume(me: &Path, path: &str) -> bool {
263 // path is assumed to have a prefix of Some(DiskPrefix)
264 let repr = me.repr.as_slice();
266 Some(DiskPrefix) => {
267 repr.as_bytes()[0] == path.as_bytes()[0].to_ascii().to_upper().to_byte()
269 Some(VerbatimDiskPrefix) => {
270 repr.as_bytes()[4] == path.as_bytes()[0].to_ascii().to_upper().to_byte()
275 fn is_sep_(prefix: Option<PathPrefix>, u: u8) -> bool {
276 if prefix_is_verbatim(prefix) { is_sep_verbatim(u as char) }
277 else { is_sep(u as char) }
280 fn replace_path(me: &mut Path, path: &str, prefix: Option<PathPrefix>) {
281 let newpath = Path::normalize__(path, prefix);
282 me.repr = match newpath {
284 None => String::from_str(path)
289 fn append_path(me: &mut Path, path: &str) {
290 // appends a path that has no prefix
291 // if me is verbatim, we need to pre-normalize the new path
292 let path_ = if is_verbatim(me) { Path::normalize__(path, None) }
294 let pathlen = path_.as_ref().map_or(path.len(), |p| p.len());
295 let mut s = String::with_capacity(me.repr.len() + 1 + pathlen);
296 s.push_str(me.repr.as_slice());
297 let plen = me.prefix_len();
298 // if me is "C:" we don't want to add a path separator
300 Some(DiskPrefix) if me.repr.len() == plen => (),
301 _ if !(me.repr.len() > plen && me.repr.as_bytes()[me.repr.len()-1] == SEP_BYTE) => {
307 None => s.push_str(path),
308 Some(p) => s.push_str(p.as_slice())
310 me.update_normalized(s)
313 if !path.is_empty() {
314 let prefix = parse_prefix(path);
316 Some(DiskPrefix) if !is_vol_abs(path, prefix) && shares_volume(self, path) => {
317 // cwd-relative path, self is on the same volume
318 append_path(self, path.slice_from(prefix_len(prefix)));
321 // absolute path, or cwd-relative and self is not same volume
322 replace_path(self, path, prefix);
324 None if !path.is_empty() && is_sep_(self.prefix, path.as_bytes()[0]) => {
325 // volume-relative path
326 if self.prefix.is_some() {
327 // truncate self down to the prefix, then append
328 let n = self.prefix_len();
329 self.repr.truncate(n);
330 append_path(self, path);
332 // we have no prefix, so nothing to be relative to
333 replace_path(self, path, prefix);
338 append_path(self, path);
345 impl GenericPath for Path {
347 fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
348 match path.container_as_str() {
354 Some(unsafe { GenericPathUnsafe::new_unchecked(*s) })
360 /// See `GenericPath::as_str` for info.
361 /// Always returns a `Some` value.
363 fn as_str<'a>(&'a self) -> Option<&'a str> {
364 Some(self.repr.as_slice())
368 fn as_vec<'a>(&'a self) -> &'a [u8] {
373 fn into_vec(self) -> Vec<u8> {
374 Vec::from_slice(self.repr.as_bytes())
378 fn dirname<'a>(&'a self) -> &'a [u8] {
379 self.dirname_str().unwrap().as_bytes()
382 /// See `GenericPath::dirname_str` for info.
383 /// Always returns a `Some` value.
384 fn dirname_str<'a>(&'a self) -> Option<&'a str> {
385 Some(match self.sepidx_or_prefix_len() {
386 None if ".." == self.repr.as_slice() => self.repr.as_slice(),
388 Some((_,idxa,end)) if self.repr.as_slice().slice(idxa, end) == ".." => {
391 Some((idxb,_,end)) if self.repr.as_slice().slice(idxb, end) == "\\" => {
394 Some((0,idxa,_)) => self.repr.as_slice().slice_to(idxa),
395 Some((idxb,idxa,_)) => {
397 Some(DiskPrefix) | Some(VerbatimDiskPrefix) if idxb == self.prefix_len() => {
398 self.repr.as_slice().slice_to(idxa)
400 _ => self.repr.as_slice().slice_to(idxb)
407 fn filename<'a>(&'a self) -> Option<&'a [u8]> {
408 self.filename_str().map(|x| x.as_bytes())
411 /// See `GenericPath::filename_str` for info.
412 /// Always returns a `Some` value if `filename` returns a `Some` value.
413 fn filename_str<'a>(&'a self) -> Option<&'a str> {
414 let repr = self.repr.as_slice();
415 match self.sepidx_or_prefix_len() {
416 None if "." == repr || ".." == repr => None,
418 Some((_,idxa,end)) if repr.slice(idxa, end) == ".." => None,
419 Some((_,idxa,end)) if idxa == end => None,
420 Some((_,idxa,end)) => Some(repr.slice(idxa, end))
424 /// See `GenericPath::filestem_str` for info.
425 /// Always returns a `Some` value if `filestem` returns a `Some` value.
427 fn filestem_str<'a>(&'a self) -> Option<&'a str> {
428 // filestem() returns a byte vector that's guaranteed valid UTF-8
429 self.filestem().map(|t| unsafe { mem::transmute(t) })
433 fn extension_str<'a>(&'a self) -> Option<&'a str> {
434 // extension() returns a byte vector that's guaranteed valid UTF-8
435 self.extension().map(|t| unsafe { mem::transmute(t) })
438 fn dir_path(&self) -> Path {
439 unsafe { GenericPathUnsafe::new_unchecked(self.dirname_str().unwrap()) }
443 fn pop(&mut self) -> bool {
444 match self.sepidx_or_prefix_len() {
445 None if "." == self.repr.as_slice() => false,
447 self.repr = String::from_str(".");
451 Some((idxb,idxa,end)) if idxb == idxa && idxb == end => false,
452 Some((idxb,_,end)) if self.repr.as_slice().slice(idxb, end) == "\\" => false,
453 Some((idxb,idxa,_)) => {
454 let trunc = match self.prefix {
455 Some(DiskPrefix) | Some(VerbatimDiskPrefix) | None => {
456 let plen = self.prefix_len();
457 if idxb == plen { idxa } else { idxb }
461 self.repr.truncate(trunc);
462 self.update_sepidx();
468 fn root_path(&self) -> Option<Path> {
469 if self.prefix.is_some() {
470 Some(Path::new(match self.prefix {
471 Some(DiskPrefix) if self.is_absolute() => {
472 self.repr.as_slice().slice_to(self.prefix_len()+1)
474 Some(VerbatimDiskPrefix) => {
475 self.repr.as_slice().slice_to(self.prefix_len()+1)
477 _ => self.repr.as_slice().slice_to(self.prefix_len())
479 } else if is_vol_relative(self) {
480 Some(Path::new(self.repr.as_slice().slice_to(1)))
486 /// See `GenericPath::is_absolute` for info.
488 /// A Windows Path is considered absolute only if it has a non-volume prefix,
489 /// or if it has a volume prefix and the path starts with '\'.
490 /// A path of `\foo` is not considered absolute because it's actually
491 /// relative to the "current volume". A separate method `Path::is_vol_relative`
492 /// is provided to indicate this case. Similarly a path of `C:foo` is not
493 /// considered absolute because it's relative to the cwd on volume C:. A
494 /// separate method `Path::is_cwd_relative` is provided to indicate this case.
496 fn is_absolute(&self) -> bool {
498 Some(DiskPrefix) => {
499 let rest = self.repr.as_slice().slice_from(self.prefix_len());
500 rest.len() > 0 && rest.as_bytes()[0] == SEP_BYTE
508 fn is_relative(&self) -> bool {
509 self.prefix.is_none() && !is_vol_relative(self)
512 fn is_ancestor_of(&self, other: &Path) -> bool {
513 if !self.equiv_prefix(other) {
515 } else if self.is_absolute() != other.is_absolute() ||
516 is_vol_relative(self) != is_vol_relative(other) {
519 let mut ita = self.str_components().map(|x|x.unwrap());
520 let mut itb = other.str_components().map(|x|x.unwrap());
521 if "." == self.repr.as_slice() {
522 return itb.next() != Some("..");
525 match (ita.next(), itb.next()) {
527 (Some(a), Some(b)) if a == b => { continue },
528 (Some(a), _) if a == ".." => {
529 // if ita contains only .. components, it's an ancestor
530 return ita.all(|x| x == "..");
539 fn path_relative_from(&self, base: &Path) -> Option<Path> {
540 fn comp_requires_verbatim(s: &str) -> bool {
541 s == "." || s == ".." || s.contains_char(SEP2)
544 if !self.equiv_prefix(base) {
546 if self.is_absolute() {
548 } else if self.prefix == Some(DiskPrefix) && base.prefix == Some(DiskPrefix) {
549 // both drives, drive letters must differ or they'd be equiv
554 } else if self.is_absolute() != base.is_absolute() {
555 if self.is_absolute() {
560 } else if is_vol_relative(self) != is_vol_relative(base) {
561 if is_vol_relative(self) {
567 let mut ita = self.str_components().map(|x|x.unwrap());
568 let mut itb = base.str_components().map(|x|x.unwrap());
569 let mut comps = vec![];
571 let a_verb = is_verbatim(self);
572 let b_verb = is_verbatim(base);
574 match (ita.next(), itb.next()) {
575 (None, None) => break,
576 (Some(a), None) if a_verb && comp_requires_verbatim(a) => {
577 return Some(self.clone())
582 comps.extend(ita.by_ref());
586 (None, _) => comps.push(".."),
587 (Some(a), Some(b)) if comps.is_empty() && a == b => (),
588 (Some(a), Some(b)) if !b_verb && b == "." => {
589 if a_verb && comp_requires_verbatim(a) {
590 return Some(self.clone())
591 } else { comps.push(a) }
593 (Some(_), Some(b)) if !b_verb && b == ".." => return None,
594 (Some(a), Some(_)) if a_verb && comp_requires_verbatim(a) => {
595 return Some(self.clone())
597 (Some(a), Some(_)) => {
604 comps.extend(ita.by_ref());
610 Some(Path::new(comps.connect("\\")))
614 fn ends_with_path(&self, child: &Path) -> bool {
615 if !child.is_relative() { return false; }
616 let mut selfit = self.str_components().rev();
617 let mut childit = child.str_components().rev();
619 match (selfit.next(), childit.next()) {
620 (Some(a), Some(b)) => if a != b { return false; },
621 (Some(_), None) => break,
622 (None, Some(_)) => return false,
623 (None, None) => break
631 /// Returns a new Path from a byte vector or string
635 /// Fails the task if the vector contains a NUL.
636 /// Fails if invalid UTF-8.
638 pub fn new<T: BytesContainer>(path: T) -> Path {
639 GenericPath::new(path)
642 /// Returns a new Path from a byte vector or string, if possible
644 pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
645 GenericPath::new_opt(path)
648 /// Returns an iterator that yields each component of the path in turn as a Option<&str>.
649 /// Every component is guaranteed to be Some.
650 /// Does not yield the path prefix (including server/share components in UNC paths).
651 /// Does not distinguish between volume-relative and relative paths, e.g.
652 /// \a\b\c and a\b\c.
653 /// Does not distinguish between absolute and cwd-relative paths, e.g.
654 /// C:\foo and C:foo.
655 pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
656 let repr = self.repr.as_slice();
657 let s = match self.prefix {
659 let plen = self.prefix_len();
660 if repr.len() > plen && repr.as_bytes()[plen] == SEP_BYTE {
661 repr.slice_from(plen+1)
662 } else { repr.slice_from(plen) }
664 None if repr.as_bytes()[0] == SEP_BYTE => repr.slice_from(1),
667 let ret = s.split_terminator(SEP).map(Some);
671 /// Returns an iterator that yields each component of the path in turn as a &[u8].
672 /// See str_components() for details.
673 pub fn components<'a>(&'a self) -> Components<'a> {
674 fn convert<'a>(x: Option<&'a str>) -> &'a [u8] {
676 x.unwrap().as_bytes()
678 self.str_components().map(convert)
681 fn equiv_prefix(&self, other: &Path) -> bool {
682 let s_repr = self.repr.as_slice();
683 let o_repr = other.repr.as_slice();
684 match (self.prefix, other.prefix) {
685 (Some(DiskPrefix), Some(VerbatimDiskPrefix)) => {
686 self.is_absolute() &&
687 s_repr.as_bytes()[0].to_ascii().eq_ignore_case(o_repr.as_bytes()[4].to_ascii())
689 (Some(VerbatimDiskPrefix), Some(DiskPrefix)) => {
690 other.is_absolute() &&
691 s_repr.as_bytes()[4].to_ascii().eq_ignore_case(o_repr.as_bytes()[0].to_ascii())
693 (Some(VerbatimDiskPrefix), Some(VerbatimDiskPrefix)) => {
694 s_repr.as_bytes()[4].to_ascii().eq_ignore_case(o_repr.as_bytes()[4].to_ascii())
696 (Some(UNCPrefix(_,_)), Some(VerbatimUNCPrefix(_,_))) => {
697 s_repr.slice(2, self.prefix_len()) == o_repr.slice(8, other.prefix_len())
699 (Some(VerbatimUNCPrefix(_,_)), Some(UNCPrefix(_,_))) => {
700 s_repr.slice(8, self.prefix_len()) == o_repr.slice(2, other.prefix_len())
702 (None, None) => true,
703 (a, b) if a == b => {
704 s_repr.slice_to(self.prefix_len()) == o_repr.slice_to(other.prefix_len())
710 fn normalize_<S: StrAllocating>(s: S) -> (Option<PathPrefix>, String) {
711 // make borrowck happy
712 let (prefix, val) = {
713 let prefix = parse_prefix(s.as_slice());
714 let path = Path::normalize__(s.as_slice(), prefix);
718 None => s.into_string(),
723 fn normalize__(s: &str, prefix: Option<PathPrefix>) -> Option<String> {
724 if prefix_is_verbatim(prefix) {
725 // don't do any normalization
727 Some(VerbatimUNCPrefix(x, 0)) if s.len() == 8 + x => {
728 // the server component has no trailing '\'
729 let mut s = String::from_str(s);
736 let (is_abs, comps) = normalize_helper(s, prefix);
737 let mut comps = comps;
738 match (comps.is_some(),prefix) {
739 (false, Some(DiskPrefix)) => {
740 if s.as_bytes()[0] >= b'a' && s.as_bytes()[0] <= b'z' {
741 comps = Some(vec![]);
744 (false, Some(VerbatimDiskPrefix)) => {
745 if s.as_bytes()[4] >= b'a' && s.as_bytes()[0] <= b'z' {
746 comps = Some(vec![]);
754 if prefix.is_some() && comps.is_empty() {
755 match prefix.unwrap() {
757 let len = prefix_len(prefix) + is_abs as uint;
758 let mut s = String::from_str(s.slice_to(len));
760 let v = s.as_mut_vec();
761 *v.get_mut(0) = v.get(0)
767 // normalize C:/ to C:\
769 *s.as_mut_vec().get_mut(2) = SEP_BYTE;
774 VerbatimDiskPrefix => {
775 let len = prefix_len(prefix) + is_abs as uint;
776 let mut s = String::from_str(s.slice_to(len));
778 let v = s.as_mut_vec();
779 *v.get_mut(4) = v.get(4).to_ascii().to_upper().to_byte();
784 let plen = prefix_len(prefix);
786 Some(String::from_str(s.slice_to(plen)))
790 } else if is_abs && comps.is_empty() {
791 Some(String::from_char(1, SEP))
793 let prefix_ = s.slice_to(prefix_len(prefix));
794 let n = prefix_.len() +
795 if is_abs { comps.len() } else { comps.len() - 1} +
796 comps.iter().map(|v| v.len()).sum();
797 let mut s = String::with_capacity(n);
799 Some(DiskPrefix) => {
800 s.push_char(prefix_.as_bytes()[0].to_ascii().to_upper().to_char());
803 Some(VerbatimDiskPrefix) => {
804 s.push_str(prefix_.slice_to(4));
805 s.push_char(prefix_.as_bytes()[4].to_ascii().to_upper().to_char());
806 s.push_str(prefix_.slice_from(5));
808 Some(UNCPrefix(a,b)) => {
810 s.push_str(prefix_.slice(2, a+2));
812 s.push_str(prefix_.slice(3+a, 3+a+b));
814 Some(_) => s.push_str(prefix_),
817 let mut it = comps.move_iter();
821 Some(comp) => s.push_str(comp)
835 fn update_sepidx(&mut self) {
836 let s = if self.has_nonsemantic_trailing_slash() {
837 self.repr.as_slice().slice_to(self.repr.len()-1)
838 } else { self.repr.as_slice() };
839 let idx = s.rfind(if !prefix_is_verbatim(self.prefix) { is_sep }
840 else { is_sep_verbatim });
841 let prefixlen = self.prefix_len();
842 self.sepidx = idx.and_then(|x| if x < prefixlen { None } else { Some(x) });
845 fn prefix_len(&self) -> uint {
846 prefix_len(self.prefix)
849 // Returns a tuple (before, after, end) where before is the index of the separator
850 // and after is the index just after the separator.
851 // end is the length of the string, normally, or the index of the final character if it is
852 // a non-semantic trailing separator in a verbatim string.
853 // If the prefix is considered the separator, before and after are the same.
854 fn sepidx_or_prefix_len(&self) -> Option<(uint,uint,uint)> {
856 None => match self.prefix_len() { 0 => None, x => Some((x,x,self.repr.len())) },
858 if self.has_nonsemantic_trailing_slash() {
859 Some((x,x+1,self.repr.len()-1))
860 } else { Some((x,x+1,self.repr.len())) }
865 fn has_nonsemantic_trailing_slash(&self) -> bool {
866 is_verbatim(self) && self.repr.len() > self.prefix_len()+1 &&
867 self.repr.as_bytes()[self.repr.len()-1] == SEP_BYTE
870 fn update_normalized<S: Str>(&mut self, s: S) {
871 let (prefix, path) = Path::normalize_(s.as_slice());
873 self.prefix = prefix;
874 self.update_sepidx();
878 /// Returns whether the path is considered "volume-relative", which means a path
879 /// that looks like "\foo". Paths of this form are relative to the current volume,
880 /// but absolute within that volume.
882 pub fn is_vol_relative(path: &Path) -> bool {
883 path.prefix.is_none() && is_sep_byte(&path.repr.as_bytes()[0])
886 /// Returns whether the path is considered "cwd-relative", which means a path
887 /// with a volume prefix that is not absolute. This look like "C:foo.txt". Paths
888 /// of this form are relative to the cwd on the given volume.
890 pub fn is_cwd_relative(path: &Path) -> bool {
891 path.prefix == Some(DiskPrefix) && !path.is_absolute()
894 /// Returns the PathPrefix for this Path
896 pub fn prefix(path: &Path) -> Option<PathPrefix> {
900 /// Returns whether the Path's prefix is a verbatim prefix, i.e. `\\?\`
902 pub fn is_verbatim(path: &Path) -> bool {
903 prefix_is_verbatim(path.prefix)
906 /// Returns the non-verbatim equivalent of the input path, if possible.
907 /// If the input path is a device namespace path, None is returned.
908 /// If the input path is not verbatim, it is returned as-is.
909 /// If the input path is verbatim, but the same path can be expressed as
910 /// non-verbatim, the non-verbatim version is returned.
911 /// Otherwise, None is returned.
912 pub fn make_non_verbatim(path: &Path) -> Option<Path> {
913 let repr = path.repr.as_slice();
914 let new_path = match path.prefix {
915 Some(VerbatimPrefix(_)) | Some(DeviceNSPrefix(_)) => return None,
916 Some(UNCPrefix(_,_)) | Some(DiskPrefix) | None => return Some(path.clone()),
917 Some(VerbatimDiskPrefix) => {
919 Path::new(repr.slice_from(4))
921 Some(VerbatimUNCPrefix(_,_)) => {
922 // \\?\UNC\server\share
923 Path::new(format!(r"\{}", repr.slice_from(7)))
926 if new_path.prefix.is_none() {
927 // \\?\UNC\server is a VerbatimUNCPrefix
928 // but \\server is nothing
931 // now ensure normalization didn't change anything
932 if repr.slice_from(path.prefix_len()) ==
933 new_path.repr.as_slice().slice_from(new_path.prefix_len()) {
940 /// The standard path separator character
941 pub static SEP: char = '\\';
942 /// The standard path separator byte
943 pub static SEP_BYTE: u8 = SEP as u8;
945 /// The alternative path separator character
946 pub static SEP2: char = '/';
947 /// The alternative path separator character
948 pub static SEP2_BYTE: u8 = SEP2 as u8;
950 /// Returns whether the given char is a path separator.
951 /// Allows both the primary separator '\' and the alternative separator '/'.
953 pub fn is_sep(c: char) -> bool {
954 c == SEP || c == SEP2
957 /// Returns whether the given char is a path separator.
958 /// Only allows the primary separator '\'; use is_sep to allow '/'.
960 pub fn is_sep_verbatim(c: char) -> bool {
964 /// Returns whether the given byte is a path separator.
965 /// Allows both the primary separator '\' and the alternative separator '/'.
967 pub fn is_sep_byte(u: &u8) -> bool {
968 *u == SEP_BYTE || *u == SEP2_BYTE
971 /// Returns whether the given byte is a path separator.
972 /// Only allows the primary separator '\'; use is_sep_byte to allow '/'.
974 pub fn is_sep_byte_verbatim(u: &u8) -> bool {
978 /// Prefix types for Path
979 #[deriving(PartialEq, Clone)]
980 pub enum PathPrefix {
981 /// Prefix `\\?\`, uint is the length of the following component
982 VerbatimPrefix(uint),
983 /// Prefix `\\?\UNC\`, uints are the lengths of the UNC components
984 VerbatimUNCPrefix(uint, uint),
985 /// Prefix `\\?\C:\` (for any alphabetic character)
987 /// Prefix `\\.\`, uint is the length of the following component
988 DeviceNSPrefix(uint),
989 /// UNC prefix `\\server\share`, uints are the lengths of the server/share
990 UNCPrefix(uint, uint),
991 /// Prefix `C:` for any alphabetic character
995 fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> {
996 if path.starts_with("\\\\") {
998 path = path.slice_from(2);
999 if path.starts_with("?\\") {
1001 path = path.slice_from(2);
1002 if path.starts_with("UNC\\") {
1003 // \\?\UNC\server\share
1004 path = path.slice_from(4);
1005 let (idx_a, idx_b) = match parse_two_comps(path, is_sep_verbatim) {
1007 None => (path.len(), 0)
1009 return Some(VerbatimUNCPrefix(idx_a, idx_b));
1012 let idx = path.find('\\');
1013 if idx == Some(2) && path.as_bytes()[1] == b':' {
1014 let c = path.as_bytes()[0];
1015 if c.is_ascii() && (c as char).is_alphabetic() {
1017 return Some(VerbatimDiskPrefix);
1020 let idx = idx.unwrap_or(path.len());
1021 return Some(VerbatimPrefix(idx));
1023 } else if path.starts_with(".\\") {
1025 path = path.slice_from(2);
1026 let idx = path.find('\\').unwrap_or(path.len());
1027 return Some(DeviceNSPrefix(idx));
1029 match parse_two_comps(path, is_sep) {
1030 Some((idx_a, idx_b)) if idx_a > 0 && idx_b > 0 => {
1032 return Some(UNCPrefix(idx_a, idx_b));
1036 } else if path.len() > 1 && path.as_bytes()[1] == b':' {
1038 let c = path.as_bytes()[0];
1039 if c.is_ascii() && (c as char).is_alphabetic() {
1040 return Some(DiskPrefix);
1045 fn parse_two_comps<'a>(mut path: &'a str, f: |char| -> bool)
1046 -> Option<(uint, uint)> {
1047 let idx_a = match path.find(|x| f(x)) {
1048 None => return None,
1051 path = path.slice_from(idx_a+1);
1052 let idx_b = path.find(f).unwrap_or(path.len());
1053 Some((idx_a, idx_b))
1057 // None result means the string didn't need normalizing
1058 fn normalize_helper<'a>(s: &'a str, prefix: Option<PathPrefix>) -> (bool, Option<Vec<&'a str>>) {
1059 let f = if !prefix_is_verbatim(prefix) { is_sep } else { is_sep_verbatim };
1060 let is_abs = s.len() > prefix_len(prefix) && f(s.char_at(prefix_len(prefix)));
1061 let s_ = s.slice_from(prefix_len(prefix));
1062 let s_ = if is_abs { s_.slice_from(1) } else { s_ };
1064 if is_abs && s_.is_empty() {
1065 return (is_abs, match prefix {
1066 Some(DiskPrefix) | None => (if is_sep_verbatim(s.char_at(prefix_len(prefix))) { None }
1067 else { Some(vec![]) }),
1068 Some(_) => Some(vec![]), // need to trim the trailing separator
1071 let mut comps: Vec<&'a str> = vec![];
1073 let mut changed = false;
1074 for comp in s_.split(f) {
1075 if comp.is_empty() { changed = true }
1076 else if comp == "." { changed = true }
1077 else if comp == ".." {
1078 let has_abs_prefix = match prefix {
1079 Some(DiskPrefix) => false,
1083 if (is_abs || has_abs_prefix) && comps.is_empty() { changed = true }
1084 else if comps.len() == n_up { comps.push(".."); n_up += 1 }
1085 else { comps.pop().unwrap(); changed = true }
1086 } else { comps.push(comp) }
1088 if !changed && !prefix_is_verbatim(prefix) {
1089 changed = s.find(is_sep).is_some();
1092 if comps.is_empty() && !is_abs && prefix.is_none() {
1094 return (is_abs, None);
1098 (is_abs, Some(comps))
1104 fn prefix_is_verbatim(p: Option<PathPrefix>) -> bool {
1106 Some(VerbatimPrefix(_)) | Some(VerbatimUNCPrefix(_,_)) | Some(VerbatimDiskPrefix) => true,
1107 Some(DeviceNSPrefix(_)) => true, // not really sure, but I think so
1112 fn prefix_len(p: Option<PathPrefix>) -> uint {
1115 Some(VerbatimPrefix(x)) => 4 + x,
1116 Some(VerbatimUNCPrefix(x,y)) => 8 + x + 1 + y,
1117 Some(VerbatimDiskPrefix) => 6,
1118 Some(UNCPrefix(x,y)) => 2 + x + 1 + y,
1119 Some(DeviceNSPrefix(x)) => 4 + x,
1120 Some(DiskPrefix) => 2
1128 use super::parse_prefix;
1131 (s: $path:expr, $exp:expr) => (
1134 assert!(path.as_str() == Some($exp));
1137 (v: $path:expr, $exp:expr) => (
1140 assert!(path.as_vec() == $exp);
1146 fn test_parse_prefix() {
1148 ($path:expr, $exp:expr) => (
1152 let res = parse_prefix(path);
1154 "parse_prefix(\"{}\"): expected {:?}, found {:?}", path, exp, res);
1159 t!("\\\\SERVER\\share\\foo", Some(UNCPrefix(6,5)));
1161 t!("\\\\SERVER", None);
1162 t!("\\\\SERVER\\", None);
1163 t!("\\\\SERVER\\\\", None);
1164 t!("\\\\SERVER\\\\foo", None);
1165 t!("\\\\SERVER\\share", Some(UNCPrefix(6,5)));
1166 t!("\\\\SERVER/share/foo", Some(UNCPrefix(6,5)));
1167 t!("\\\\SERVER\\share/foo", Some(UNCPrefix(6,5)));
1168 t!("//SERVER/share/foo", None);
1169 t!("\\\\\\a\\b\\c", None);
1170 t!("\\\\?\\a\\b\\c", Some(VerbatimPrefix(1)));
1171 t!("\\\\?\\a/b/c", Some(VerbatimPrefix(5)));
1172 t!("//?/a/b/c", None);
1173 t!("\\\\.\\a\\b", Some(DeviceNSPrefix(1)));
1174 t!("\\\\.\\a/b", Some(DeviceNSPrefix(3)));
1175 t!("//./a/b", None);
1176 t!("\\\\?\\UNC\\server\\share\\foo", Some(VerbatimUNCPrefix(6,5)));
1177 t!("\\\\?\\UNC\\\\share\\foo", Some(VerbatimUNCPrefix(0,5)));
1178 t!("\\\\?\\UNC\\", Some(VerbatimUNCPrefix(0,0)));
1179 t!("\\\\?\\UNC\\server/share/foo", Some(VerbatimUNCPrefix(16,0)));
1180 t!("\\\\?\\UNC\\server", Some(VerbatimUNCPrefix(6,0)));
1181 t!("\\\\?\\UNC\\server\\", Some(VerbatimUNCPrefix(6,0)));
1182 t!("\\\\?\\UNC/server/share", Some(VerbatimPrefix(16)));
1183 t!("\\\\?\\UNC", Some(VerbatimPrefix(3)));
1184 t!("\\\\?\\C:\\a\\b.txt", Some(VerbatimDiskPrefix));
1185 t!("\\\\?\\z:\\", Some(VerbatimDiskPrefix));
1186 t!("\\\\?\\C:", Some(VerbatimPrefix(2)));
1187 t!("\\\\?\\C:a.txt", Some(VerbatimPrefix(7)));
1188 t!("\\\\?\\C:a\\b.txt", Some(VerbatimPrefix(3)));
1189 t!("\\\\?\\C:/a", Some(VerbatimPrefix(4)));
1190 t!("C:\\foo", Some(DiskPrefix));
1191 t!("z:/foo", Some(DiskPrefix));
1192 t!("d:", Some(DiskPrefix));
1194 t!("ü:\\foo", None);
1195 t!("3:\\foo", None);
1196 t!(" :\\foo", None);
1197 t!("::\\foo", None);
1198 t!("\\\\?\\C:", Some(VerbatimPrefix(2)));
1199 t!("\\\\?\\z:\\", Some(VerbatimDiskPrefix));
1200 t!("\\\\?\\ab:\\", Some(VerbatimPrefix(3)));
1201 t!("\\\\?\\C:\\a", Some(VerbatimDiskPrefix));
1202 t!("\\\\?\\C:/a", Some(VerbatimPrefix(4)));
1203 t!("\\\\?\\C:\\a/b", Some(VerbatimDiskPrefix));
1208 let empty: &[u8] = [];
1209 t!(v: Path::new(empty), b".");
1210 t!(v: Path::new(b"\\"), b"\\");
1211 t!(v: Path::new(b"a\\b\\c"), b"a\\b\\c");
1213 t!(s: Path::new(""), ".");
1214 t!(s: Path::new("\\"), "\\");
1215 t!(s: Path::new("hi"), "hi");
1216 t!(s: Path::new("hi\\"), "hi");
1217 t!(s: Path::new("\\lib"), "\\lib");
1218 t!(s: Path::new("\\lib\\"), "\\lib");
1219 t!(s: Path::new("hi\\there"), "hi\\there");
1220 t!(s: Path::new("hi\\there.txt"), "hi\\there.txt");
1221 t!(s: Path::new("/"), "\\");
1222 t!(s: Path::new("hi/"), "hi");
1223 t!(s: Path::new("/lib"), "\\lib");
1224 t!(s: Path::new("/lib/"), "\\lib");
1225 t!(s: Path::new("hi/there"), "hi\\there");
1227 t!(s: Path::new("hi\\there\\"), "hi\\there");
1228 t!(s: Path::new("hi\\..\\there"), "there");
1229 t!(s: Path::new("hi/../there"), "there");
1230 t!(s: Path::new("..\\hi\\there"), "..\\hi\\there");
1231 t!(s: Path::new("\\..\\hi\\there"), "\\hi\\there");
1232 t!(s: Path::new("/../hi/there"), "\\hi\\there");
1233 t!(s: Path::new("foo\\.."), ".");
1234 t!(s: Path::new("\\foo\\.."), "\\");
1235 t!(s: Path::new("\\foo\\..\\.."), "\\");
1236 t!(s: Path::new("\\foo\\..\\..\\bar"), "\\bar");
1237 t!(s: Path::new("\\.\\hi\\.\\there\\."), "\\hi\\there");
1238 t!(s: Path::new("\\.\\hi\\.\\there\\.\\.."), "\\hi");
1239 t!(s: Path::new("foo\\..\\.."), "..");
1240 t!(s: Path::new("foo\\..\\..\\.."), "..\\..");
1241 t!(s: Path::new("foo\\..\\..\\bar"), "..\\bar");
1243 assert_eq!(Path::new(b"foo\\bar").into_vec().as_slice(), b"foo\\bar");
1244 assert_eq!(Path::new(b"\\foo\\..\\..\\bar").into_vec().as_slice(), b"\\bar");
1246 t!(s: Path::new("\\\\a"), "\\a");
1247 t!(s: Path::new("\\\\a\\"), "\\a");
1248 t!(s: Path::new("\\\\a\\b"), "\\\\a\\b");
1249 t!(s: Path::new("\\\\a\\b\\"), "\\\\a\\b");
1250 t!(s: Path::new("\\\\a\\b/"), "\\\\a\\b");
1251 t!(s: Path::new("\\\\\\b"), "\\b");
1252 t!(s: Path::new("\\\\a\\\\b"), "\\a\\b");
1253 t!(s: Path::new("\\\\a\\b\\c"), "\\\\a\\b\\c");
1254 t!(s: Path::new("\\\\server\\share/path"), "\\\\server\\share\\path");
1255 t!(s: Path::new("\\\\server/share/path"), "\\\\server\\share\\path");
1256 t!(s: Path::new("C:a\\b.txt"), "C:a\\b.txt");
1257 t!(s: Path::new("C:a/b.txt"), "C:a\\b.txt");
1258 t!(s: Path::new("z:\\a\\b.txt"), "Z:\\a\\b.txt");
1259 t!(s: Path::new("z:/a/b.txt"), "Z:\\a\\b.txt");
1260 t!(s: Path::new("ab:/a/b.txt"), "ab:\\a\\b.txt");
1261 t!(s: Path::new("C:\\"), "C:\\");
1262 t!(s: Path::new("C:"), "C:");
1263 t!(s: Path::new("q:"), "Q:");
1264 t!(s: Path::new("C:/"), "C:\\");
1265 t!(s: Path::new("C:\\foo\\.."), "C:\\");
1266 t!(s: Path::new("C:foo\\.."), "C:");
1267 t!(s: Path::new("C:\\a\\"), "C:\\a");
1268 t!(s: Path::new("C:\\a/"), "C:\\a");
1269 t!(s: Path::new("C:\\a\\b\\"), "C:\\a\\b");
1270 t!(s: Path::new("C:\\a\\b/"), "C:\\a\\b");
1271 t!(s: Path::new("C:a\\"), "C:a");
1272 t!(s: Path::new("C:a/"), "C:a");
1273 t!(s: Path::new("C:a\\b\\"), "C:a\\b");
1274 t!(s: Path::new("C:a\\b/"), "C:a\\b");
1275 t!(s: Path::new("\\\\?\\z:\\a\\b.txt"), "\\\\?\\z:\\a\\b.txt");
1276 t!(s: Path::new("\\\\?\\C:/a/b.txt"), "\\\\?\\C:/a/b.txt");
1277 t!(s: Path::new("\\\\?\\C:\\a/b.txt"), "\\\\?\\C:\\a/b.txt");
1278 t!(s: Path::new("\\\\?\\test\\a\\b.txt"), "\\\\?\\test\\a\\b.txt");
1279 t!(s: Path::new("\\\\?\\foo\\bar\\"), "\\\\?\\foo\\bar\\");
1280 t!(s: Path::new("\\\\.\\foo\\bar"), "\\\\.\\foo\\bar");
1281 t!(s: Path::new("\\\\.\\"), "\\\\.\\");
1282 t!(s: Path::new("\\\\?\\UNC\\server\\share\\foo"), "\\\\?\\UNC\\server\\share\\foo");
1283 t!(s: Path::new("\\\\?\\UNC\\server/share"), "\\\\?\\UNC\\server/share\\");
1284 t!(s: Path::new("\\\\?\\UNC\\server"), "\\\\?\\UNC\\server\\");
1285 t!(s: Path::new("\\\\?\\UNC\\"), "\\\\?\\UNC\\\\");
1286 t!(s: Path::new("\\\\?\\UNC"), "\\\\?\\UNC");
1288 // I'm not sure whether \\.\foo/bar should normalize to \\.\foo\bar
1289 // as information is sparse and this isn't really googleable.
1290 // I'm going to err on the side of not normalizing it, as this skips the filesystem
1291 t!(s: Path::new("\\\\.\\foo/bar"), "\\\\.\\foo/bar");
1292 t!(s: Path::new("\\\\.\\foo\\bar"), "\\\\.\\foo\\bar");
1296 fn test_opt_paths() {
1297 assert!(Path::new_opt(b"foo\\bar\0") == None);
1298 assert!(Path::new_opt(b"foo\\bar\x80") == None);
1299 t!(v: Path::new_opt(b"foo\\bar").unwrap(), b"foo\\bar");
1300 assert!(Path::new_opt("foo\\bar\0") == None);
1301 t!(s: Path::new_opt("foo\\bar").unwrap(), "foo\\bar");
1305 fn test_null_byte() {
1307 let result = task::try(proc() {
1308 Path::new(b"foo/bar\0")
1310 assert!(result.is_err());
1312 let result = task::try(proc() {
1313 Path::new("test").set_filename(b"f\0o")
1315 assert!(result.is_err());
1317 let result = task::try(proc() {
1318 Path::new("test").push(b"f\0o");
1320 assert!(result.is_err());
1325 fn test_not_utf8_fail() {
1326 Path::new(b"hello\x80.txt");
1330 fn test_display_str() {
1331 let path = Path::new("foo");
1332 assert_eq!(path.display().to_string(), "foo".to_string());
1333 let path = Path::new(b"\\");
1334 assert_eq!(path.filename_display().to_string(), "".to_string());
1336 let path = Path::new("foo");
1337 let mo = path.display().as_maybe_owned();
1338 assert_eq!(mo.as_slice(), "foo");
1339 let path = Path::new(b"\\");
1340 let mo = path.filename_display().as_maybe_owned();
1341 assert_eq!(mo.as_slice(), "");
1347 ($path:expr, $exp:expr, $expf:expr) => (
1349 let path = Path::new($path);
1350 let f = format!("{}", path.display());
1351 assert_eq!(f.as_slice(), $exp);
1352 let f = format!("{}", path.filename_display());
1353 assert_eq!(f.as_slice(), $expf);
1358 t!("foo", "foo", "foo");
1359 t!("foo\\bar", "foo\\bar", "bar");
1364 fn test_components() {
1366 (s: $path:expr, $op:ident, $exp:expr) => (
1369 let path = Path::new(path);
1370 assert!(path.$op() == Some($exp));
1373 (s: $path:expr, $op:ident, $exp:expr, opt) => (
1376 let path = Path::new(path);
1377 let left = path.$op();
1378 assert!(left == $exp);
1381 (v: $path:expr, $op:ident, $exp:expr) => (
1384 let path = Path::new(path);
1385 assert!(path.$op() == $exp);
1390 t!(v: b"a\\b\\c", filename, Some(b"c"));
1391 t!(s: "a\\b\\c", filename_str, "c");
1392 t!(s: "\\a\\b\\c", filename_str, "c");
1393 t!(s: "a", filename_str, "a");
1394 t!(s: "\\a", filename_str, "a");
1395 t!(s: ".", filename_str, None, opt);
1396 t!(s: "\\", filename_str, None, opt);
1397 t!(s: "..", filename_str, None, opt);
1398 t!(s: "..\\..", filename_str, None, opt);
1399 t!(s: "c:\\foo.txt", filename_str, "foo.txt");
1400 t!(s: "C:\\", filename_str, None, opt);
1401 t!(s: "C:", filename_str, None, opt);
1402 t!(s: "\\\\server\\share\\foo.txt", filename_str, "foo.txt");
1403 t!(s: "\\\\server\\share", filename_str, None, opt);
1404 t!(s: "\\\\server", filename_str, "server");
1405 t!(s: "\\\\?\\bar\\foo.txt", filename_str, "foo.txt");
1406 t!(s: "\\\\?\\bar", filename_str, None, opt);
1407 t!(s: "\\\\?\\", filename_str, None, opt);
1408 t!(s: "\\\\?\\UNC\\server\\share\\foo.txt", filename_str, "foo.txt");
1409 t!(s: "\\\\?\\UNC\\server", filename_str, None, opt);
1410 t!(s: "\\\\?\\UNC\\", filename_str, None, opt);
1411 t!(s: "\\\\?\\C:\\foo.txt", filename_str, "foo.txt");
1412 t!(s: "\\\\?\\C:\\", filename_str, None, opt);
1413 t!(s: "\\\\?\\C:", filename_str, None, opt);
1414 t!(s: "\\\\?\\foo/bar", filename_str, None, opt);
1415 t!(s: "\\\\?\\C:/foo", filename_str, None, opt);
1416 t!(s: "\\\\.\\foo\\bar", filename_str, "bar");
1417 t!(s: "\\\\.\\foo", filename_str, None, opt);
1418 t!(s: "\\\\.\\foo/bar", filename_str, None, opt);
1419 t!(s: "\\\\.\\foo\\bar/baz", filename_str, "bar/baz");
1420 t!(s: "\\\\.\\", filename_str, None, opt);
1421 t!(s: "\\\\?\\a\\b\\", filename_str, "b");
1423 t!(v: b"a\\b\\c", dirname, b"a\\b");
1424 t!(s: "a\\b\\c", dirname_str, "a\\b");
1425 t!(s: "\\a\\b\\c", dirname_str, "\\a\\b");
1426 t!(s: "a", dirname_str, ".");
1427 t!(s: "\\a", dirname_str, "\\");
1428 t!(s: ".", dirname_str, ".");
1429 t!(s: "\\", dirname_str, "\\");
1430 t!(s: "..", dirname_str, "..");
1431 t!(s: "..\\..", dirname_str, "..\\..");
1432 t!(s: "c:\\foo.txt", dirname_str, "C:\\");
1433 t!(s: "C:\\", dirname_str, "C:\\");
1434 t!(s: "C:", dirname_str, "C:");
1435 t!(s: "C:foo.txt", dirname_str, "C:");
1436 t!(s: "\\\\server\\share\\foo.txt", dirname_str, "\\\\server\\share");
1437 t!(s: "\\\\server\\share", dirname_str, "\\\\server\\share");
1438 t!(s: "\\\\server", dirname_str, "\\");
1439 t!(s: "\\\\?\\bar\\foo.txt", dirname_str, "\\\\?\\bar");
1440 t!(s: "\\\\?\\bar", dirname_str, "\\\\?\\bar");
1441 t!(s: "\\\\?\\", dirname_str, "\\\\?\\");
1442 t!(s: "\\\\?\\UNC\\server\\share\\foo.txt", dirname_str, "\\\\?\\UNC\\server\\share");
1443 t!(s: "\\\\?\\UNC\\server", dirname_str, "\\\\?\\UNC\\server\\");
1444 t!(s: "\\\\?\\UNC\\", dirname_str, "\\\\?\\UNC\\\\");
1445 t!(s: "\\\\?\\C:\\foo.txt", dirname_str, "\\\\?\\C:\\");
1446 t!(s: "\\\\?\\C:\\", dirname_str, "\\\\?\\C:\\");
1447 t!(s: "\\\\?\\C:", dirname_str, "\\\\?\\C:");
1448 t!(s: "\\\\?\\C:/foo/bar", dirname_str, "\\\\?\\C:/foo/bar");
1449 t!(s: "\\\\?\\foo/bar", dirname_str, "\\\\?\\foo/bar");
1450 t!(s: "\\\\.\\foo\\bar", dirname_str, "\\\\.\\foo");
1451 t!(s: "\\\\.\\foo", dirname_str, "\\\\.\\foo");
1452 t!(s: "\\\\?\\a\\b\\", dirname_str, "\\\\?\\a");
1454 t!(v: b"hi\\there.txt", filestem, Some(b"there"));
1455 t!(s: "hi\\there.txt", filestem_str, "there");
1456 t!(s: "hi\\there", filestem_str, "there");
1457 t!(s: "there.txt", filestem_str, "there");
1458 t!(s: "there", filestem_str, "there");
1459 t!(s: ".", filestem_str, None, opt);
1460 t!(s: "\\", filestem_str, None, opt);
1461 t!(s: "foo\\.bar", filestem_str, ".bar");
1462 t!(s: ".bar", filestem_str, ".bar");
1463 t!(s: "..bar", filestem_str, ".");
1464 t!(s: "hi\\there..txt", filestem_str, "there.");
1465 t!(s: "..", filestem_str, None, opt);
1466 t!(s: "..\\..", filestem_str, None, opt);
1467 // filestem is based on filename, so we don't need the full set of prefix tests
1469 t!(v: b"hi\\there.txt", extension, Some(b"txt"));
1470 t!(v: b"hi\\there", extension, None);
1471 t!(s: "hi\\there.txt", extension_str, Some("txt"), opt);
1472 t!(s: "hi\\there", extension_str, None, opt);
1473 t!(s: "there.txt", extension_str, Some("txt"), opt);
1474 t!(s: "there", extension_str, None, opt);
1475 t!(s: ".", extension_str, None, opt);
1476 t!(s: "\\", extension_str, None, opt);
1477 t!(s: "foo\\.bar", extension_str, None, opt);
1478 t!(s: ".bar", extension_str, None, opt);
1479 t!(s: "..bar", extension_str, Some("bar"), opt);
1480 t!(s: "hi\\there..txt", extension_str, Some("txt"), opt);
1481 t!(s: "..", extension_str, None, opt);
1482 t!(s: "..\\..", extension_str, None, opt);
1483 // extension is based on filename, so we don't need the full set of prefix tests
1489 (s: $path:expr, $join:expr) => (
1493 let mut p1 = Path::new(path);
1494 let p2 = p1.clone();
1496 assert!(p1 == p2.join(join));
1501 t!(s: "a\\b\\c", "..");
1502 t!(s: "\\a\\b\\c", "d");
1503 t!(s: "a\\b", "c\\d");
1504 t!(s: "a\\b", "\\c\\d");
1505 // this is just a sanity-check test. push and join share an implementation,
1506 // so there's no need for the full set of prefix tests
1508 // we do want to check one odd case though to ensure the prefix is re-parsed
1509 let mut p = Path::new("\\\\?\\C:");
1510 assert!(prefix(&p) == Some(VerbatimPrefix(2)));
1512 assert!(prefix(&p) == Some(VerbatimDiskPrefix));
1513 assert_eq!(p.as_str(), Some("\\\\?\\C:\\foo"));
1515 // and another with verbatim non-normalized paths
1516 let mut p = Path::new("\\\\?\\C:\\a\\");
1518 assert_eq!(p.as_str(), Some("\\\\?\\C:\\a\\foo"));
1522 fn test_push_path() {
1524 (s: $path:expr, $push:expr, $exp:expr) => (
1526 let mut p = Path::new($path);
1527 let push = Path::new($push);
1529 assert_eq!(p.as_str(), Some($exp));
1534 t!(s: "a\\b\\c", "d", "a\\b\\c\\d");
1535 t!(s: "\\a\\b\\c", "d", "\\a\\b\\c\\d");
1536 t!(s: "a\\b", "c\\d", "a\\b\\c\\d");
1537 t!(s: "a\\b", "\\c\\d", "\\c\\d");
1538 t!(s: "a\\b", ".", "a\\b");
1539 t!(s: "a\\b", "..\\c", "a\\c");
1540 t!(s: "a\\b", "C:a.txt", "C:a.txt");
1541 t!(s: "a\\b", "..\\..\\..\\c", "..\\c");
1542 t!(s: "a\\b", "C:\\a.txt", "C:\\a.txt");
1543 t!(s: "C:\\a", "C:\\b.txt", "C:\\b.txt");
1544 t!(s: "C:\\a\\b\\c", "C:d", "C:\\a\\b\\c\\d");
1545 t!(s: "C:a\\b\\c", "C:d", "C:a\\b\\c\\d");
1546 t!(s: "C:a\\b", "..\\..\\..\\c", "C:..\\c");
1547 t!(s: "C:\\a\\b", "..\\..\\..\\c", "C:\\c");
1548 t!(s: "C:", r"a\b\c", r"C:a\b\c");
1549 t!(s: "C:", r"..\a", r"C:..\a");
1550 t!(s: "\\\\server\\share\\foo", "bar", "\\\\server\\share\\foo\\bar");
1551 t!(s: "\\\\server\\share\\foo", "..\\..\\bar", "\\\\server\\share\\bar");
1552 t!(s: "\\\\server\\share\\foo", "C:baz", "C:baz");
1553 t!(s: "\\\\?\\C:\\a\\b", "C:c\\d", "\\\\?\\C:\\a\\b\\c\\d");
1554 t!(s: "\\\\?\\C:a\\b", "C:c\\d", "C:c\\d");
1555 t!(s: "\\\\?\\C:\\a\\b", "C:\\c\\d", "C:\\c\\d");
1556 t!(s: "\\\\?\\foo\\bar", "baz", "\\\\?\\foo\\bar\\baz");
1557 t!(s: "\\\\?\\C:\\a\\b", "..\\..\\..\\c", "\\\\?\\C:\\a\\b\\..\\..\\..\\c");
1558 t!(s: "\\\\?\\foo\\bar", "..\\..\\c", "\\\\?\\foo\\bar\\..\\..\\c");
1559 t!(s: "\\\\?\\", "foo", "\\\\?\\\\foo");
1560 t!(s: "\\\\?\\UNC\\server\\share\\foo", "bar", "\\\\?\\UNC\\server\\share\\foo\\bar");
1561 t!(s: "\\\\?\\UNC\\server\\share", "C:\\a", "C:\\a");
1562 t!(s: "\\\\?\\UNC\\server\\share", "C:a", "C:a");
1563 t!(s: "\\\\?\\UNC\\server", "foo", "\\\\?\\UNC\\server\\\\foo");
1564 t!(s: "C:\\a", "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share");
1565 t!(s: "\\\\.\\foo\\bar", "baz", "\\\\.\\foo\\bar\\baz");
1566 t!(s: "\\\\.\\foo\\bar", "C:a", "C:a");
1567 // again, not sure about the following, but I'm assuming \\.\ should be verbatim
1568 t!(s: "\\\\.\\foo", "..\\bar", "\\\\.\\foo\\..\\bar");
1570 t!(s: "\\\\?\\C:", "foo", "\\\\?\\C:\\foo"); // this is a weird one
1574 fn test_push_many() {
1576 (s: $path:expr, $push:expr, $exp:expr) => (
1578 let mut p = Path::new($path);
1580 assert_eq!(p.as_str(), Some($exp));
1583 (v: $path:expr, $push:expr, $exp:expr) => (
1585 let mut p = Path::new($path);
1587 assert_eq!(p.as_vec(), $exp);
1592 t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e");
1593 t!(s: "a\\b\\c", ["d", "\\e"], "\\e");
1594 t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
1595 t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "a\\b\\c\\d\\e");
1596 t!(v: b"a\\b\\c", [b"d", b"e"], b"a\\b\\c\\d\\e");
1597 t!(v: b"a\\b\\c", [b"d", b"\\e", b"f"], b"\\e\\f");
1598 t!(v: b"a\\b\\c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")],
1605 (s: $path:expr, $left:expr, $right:expr) => (
1608 let mut p = Path::new(pstr);
1609 let result = p.pop();
1611 assert!(p.as_str() == Some(left),
1612 "`{}`.pop() failed; expected remainder `{}`, found `{}`",
1613 pstr, left, p.as_str().unwrap());
1614 assert!(result == $right);
1617 (b: $path:expr, $left:expr, $right:expr) => (
1619 let mut p = Path::new($path);
1620 let result = p.pop();
1621 assert_eq!(p.as_vec(), $left);
1622 assert!(result == $right);
1627 t!(s: "a\\b\\c", "a\\b", true);
1628 t!(s: "a", ".", true);
1629 t!(s: ".", ".", false);
1630 t!(s: "\\a", "\\", true);
1631 t!(s: "\\", "\\", false);
1632 t!(b: b"a\\b\\c", b"a\\b", true);
1633 t!(b: b"a", b".", true);
1634 t!(b: b".", b".", false);
1635 t!(b: b"\\a", b"\\", true);
1636 t!(b: b"\\", b"\\", false);
1638 t!(s: "C:\\a\\b", "C:\\a", true);
1639 t!(s: "C:\\a", "C:\\", true);
1640 t!(s: "C:\\", "C:\\", false);
1641 t!(s: "C:a\\b", "C:a", true);
1642 t!(s: "C:a", "C:", true);
1643 t!(s: "C:", "C:", false);
1644 t!(s: "\\\\server\\share\\a\\b", "\\\\server\\share\\a", true);
1645 t!(s: "\\\\server\\share\\a", "\\\\server\\share", true);
1646 t!(s: "\\\\server\\share", "\\\\server\\share", false);
1647 t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b", true);
1648 t!(s: "\\\\?\\a\\b", "\\\\?\\a", true);
1649 t!(s: "\\\\?\\a", "\\\\?\\a", false);
1650 t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", true);
1651 t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\", true);
1652 t!(s: "\\\\?\\C:\\", "\\\\?\\C:\\", false);
1653 t!(s: "\\\\?\\UNC\\server\\share\\a\\b", "\\\\?\\UNC\\server\\share\\a", true);
1654 t!(s: "\\\\?\\UNC\\server\\share\\a", "\\\\?\\UNC\\server\\share", true);
1655 t!(s: "\\\\?\\UNC\\server\\share", "\\\\?\\UNC\\server\\share", false);
1656 t!(s: "\\\\.\\a\\b\\c", "\\\\.\\a\\b", true);
1657 t!(s: "\\\\.\\a\\b", "\\\\.\\a", true);
1658 t!(s: "\\\\.\\a", "\\\\.\\a", false);
1660 t!(s: "\\\\?\\a\\b\\", "\\\\?\\a", true);
1664 fn test_root_path() {
1665 assert!(Path::new("a\\b\\c").root_path() == None);
1666 assert!(Path::new("\\a\\b\\c").root_path() == Some(Path::new("\\")));
1667 assert!(Path::new("C:a").root_path() == Some(Path::new("C:")));
1668 assert!(Path::new("C:\\a").root_path() == Some(Path::new("C:\\")));
1669 assert!(Path::new("\\\\a\\b\\c").root_path() == Some(Path::new("\\\\a\\b")));
1670 assert!(Path::new("\\\\?\\a\\b").root_path() == Some(Path::new("\\\\?\\a")));
1671 assert!(Path::new("\\\\?\\C:\\a").root_path() == Some(Path::new("\\\\?\\C:\\")));
1672 assert!(Path::new("\\\\?\\UNC\\a\\b\\c").root_path() ==
1673 Some(Path::new("\\\\?\\UNC\\a\\b")));
1674 assert!(Path::new("\\\\.\\a\\b").root_path() == Some(Path::new("\\\\.\\a")));
1679 t!(s: Path::new("a\\b\\c").join(".."), "a\\b");
1680 t!(s: Path::new("\\a\\b\\c").join("d"), "\\a\\b\\c\\d");
1681 t!(s: Path::new("a\\b").join("c\\d"), "a\\b\\c\\d");
1682 t!(s: Path::new("a\\b").join("\\c\\d"), "\\c\\d");
1683 t!(s: Path::new(".").join("a\\b"), "a\\b");
1684 t!(s: Path::new("\\").join("a\\b"), "\\a\\b");
1685 t!(v: Path::new(b"a\\b\\c").join(b".."), b"a\\b");
1686 t!(v: Path::new(b"\\a\\b\\c").join(b"d"), b"\\a\\b\\c\\d");
1687 // full join testing is covered under test_push_path, so no need for
1688 // the full set of prefix tests
1692 fn test_join_path() {
1694 (s: $path:expr, $join:expr, $exp:expr) => (
1696 let path = Path::new($path);
1697 let join = Path::new($join);
1698 let res = path.join(&join);
1699 assert_eq!(res.as_str(), Some($exp));
1704 t!(s: "a\\b\\c", "..", "a\\b");
1705 t!(s: "\\a\\b\\c", "d", "\\a\\b\\c\\d");
1706 t!(s: "a\\b", "c\\d", "a\\b\\c\\d");
1707 t!(s: "a\\b", "\\c\\d", "\\c\\d");
1708 t!(s: ".", "a\\b", "a\\b");
1709 t!(s: "\\", "a\\b", "\\a\\b");
1710 // join is implemented using push, so there's no need for
1711 // the full set of prefix tests
1715 fn test_join_many() {
1717 (s: $path:expr, $join:expr, $exp:expr) => (
1719 let path = Path::new($path);
1720 let res = path.join_many($join);
1721 assert_eq!(res.as_str(), Some($exp));
1724 (v: $path:expr, $join:expr, $exp:expr) => (
1726 let path = Path::new($path);
1727 let res = path.join_many($join);
1728 assert_eq!(res.as_vec(), $exp);
1733 t!(s: "a\\b\\c", ["d", "e"], "a\\b\\c\\d\\e");
1734 t!(s: "a\\b\\c", ["..", "d"], "a\\b\\d");
1735 t!(s: "a\\b\\c", ["d", "\\e", "f"], "\\e\\f");
1736 t!(s: "a\\b\\c", ["d".to_string(), "e".to_string()], "a\\b\\c\\d\\e");
1737 t!(v: b"a\\b\\c", [b"d", b"e"], b"a\\b\\c\\d\\e");
1738 t!(v: b"a\\b\\c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")],
1743 fn test_with_helpers() {
1745 (s: $path:expr, $op:ident, $arg:expr, $res:expr) => (
1748 let path = Path::new(pstr);
1750 let res = path.$op(arg);
1752 assert!(res.as_str() == Some(exp),
1753 "`{}`.{}(\"{}\"): Expected `{}`, found `{}`",
1754 pstr, stringify!($op), arg, exp, res.as_str().unwrap());
1759 t!(s: "a\\b\\c", with_filename, "d", "a\\b\\d");
1760 t!(s: ".", with_filename, "foo", "foo");
1761 t!(s: "\\a\\b\\c", with_filename, "d", "\\a\\b\\d");
1762 t!(s: "\\", with_filename, "foo", "\\foo");
1763 t!(s: "\\a", with_filename, "foo", "\\foo");
1764 t!(s: "foo", with_filename, "bar", "bar");
1765 t!(s: "\\", with_filename, "foo\\", "\\foo");
1766 t!(s: "\\a", with_filename, "foo\\", "\\foo");
1767 t!(s: "a\\b\\c", with_filename, "", "a\\b");
1768 t!(s: "a\\b\\c", with_filename, ".", "a\\b");
1769 t!(s: "a\\b\\c", with_filename, "..", "a");
1770 t!(s: "\\a", with_filename, "", "\\");
1771 t!(s: "foo", with_filename, "", ".");
1772 t!(s: "a\\b\\c", with_filename, "d\\e", "a\\b\\d\\e");
1773 t!(s: "a\\b\\c", with_filename, "\\d", "a\\b\\d");
1774 t!(s: "..", with_filename, "foo", "..\\foo");
1775 t!(s: "..\\..", with_filename, "foo", "..\\..\\foo");
1776 t!(s: "..", with_filename, "", "..");
1777 t!(s: "..\\..", with_filename, "", "..\\..");
1778 t!(s: "C:\\foo\\bar", with_filename, "baz", "C:\\foo\\baz");
1779 t!(s: "C:\\foo", with_filename, "bar", "C:\\bar");
1780 t!(s: "C:\\", with_filename, "foo", "C:\\foo");
1781 t!(s: "C:foo\\bar", with_filename, "baz", "C:foo\\baz");
1782 t!(s: "C:foo", with_filename, "bar", "C:bar");
1783 t!(s: "C:", with_filename, "foo", "C:foo");
1784 t!(s: "C:\\foo", with_filename, "", "C:\\");
1785 t!(s: "C:foo", with_filename, "", "C:");
1786 t!(s: "C:\\foo\\bar", with_filename, "..", "C:\\");
1787 t!(s: "C:\\foo", with_filename, "..", "C:\\");
1788 t!(s: "C:\\", with_filename, "..", "C:\\");
1789 t!(s: "C:foo\\bar", with_filename, "..", "C:");
1790 t!(s: "C:foo", with_filename, "..", "C:..");
1791 t!(s: "C:", with_filename, "..", "C:..");
1792 t!(s: "\\\\server\\share\\foo", with_filename, "bar", "\\\\server\\share\\bar");
1793 t!(s: "\\\\server\\share", with_filename, "foo", "\\\\server\\share\\foo");
1794 t!(s: "\\\\server\\share\\foo", with_filename, "", "\\\\server\\share");
1795 t!(s: "\\\\server\\share", with_filename, "", "\\\\server\\share");
1796 t!(s: "\\\\server\\share\\foo", with_filename, "..", "\\\\server\\share");
1797 t!(s: "\\\\server\\share", with_filename, "..", "\\\\server\\share");
1798 t!(s: "\\\\?\\C:\\foo\\bar", with_filename, "baz", "\\\\?\\C:\\foo\\baz");
1799 t!(s: "\\\\?\\C:\\foo", with_filename, "bar", "\\\\?\\C:\\bar");
1800 t!(s: "\\\\?\\C:\\", with_filename, "foo", "\\\\?\\C:\\foo");
1801 t!(s: "\\\\?\\C:\\foo", with_filename, "..", "\\\\?\\C:\\..");
1802 t!(s: "\\\\?\\foo\\bar", with_filename, "baz", "\\\\?\\foo\\baz");
1803 t!(s: "\\\\?\\foo", with_filename, "bar", "\\\\?\\foo\\bar");
1804 t!(s: "\\\\?\\", with_filename, "foo", "\\\\?\\\\foo");
1805 t!(s: "\\\\?\\foo\\bar", with_filename, "..", "\\\\?\\foo\\..");
1806 t!(s: "\\\\.\\foo\\bar", with_filename, "baz", "\\\\.\\foo\\baz");
1807 t!(s: "\\\\.\\foo", with_filename, "bar", "\\\\.\\foo\\bar");
1808 t!(s: "\\\\.\\foo\\bar", with_filename, "..", "\\\\.\\foo\\..");
1810 t!(s: "hi\\there.txt", with_extension, "exe", "hi\\there.exe");
1811 t!(s: "hi\\there.txt", with_extension, "", "hi\\there");
1812 t!(s: "hi\\there.txt", with_extension, ".", "hi\\there..");
1813 t!(s: "hi\\there.txt", with_extension, "..", "hi\\there...");
1814 t!(s: "hi\\there", with_extension, "txt", "hi\\there.txt");
1815 t!(s: "hi\\there", with_extension, ".", "hi\\there..");
1816 t!(s: "hi\\there", with_extension, "..", "hi\\there...");
1817 t!(s: "hi\\there.", with_extension, "txt", "hi\\there.txt");
1818 t!(s: "hi\\.foo", with_extension, "txt", "hi\\.foo.txt");
1819 t!(s: "hi\\there.txt", with_extension, ".foo", "hi\\there..foo");
1820 t!(s: "\\", with_extension, "txt", "\\");
1821 t!(s: "\\", with_extension, ".", "\\");
1822 t!(s: "\\", with_extension, "..", "\\");
1823 t!(s: ".", with_extension, "txt", ".");
1824 // extension setter calls filename setter internally, no need for extended tests
1830 (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
1834 let mut p1 = Path::new(path);
1836 let p2 = Path::new(path);
1837 assert!(p1 == p2.$with(arg));
1840 (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
1844 let mut p1 = Path::new(path);
1846 let p2 = Path::new(path);
1847 assert!(p1 == p2.$with(arg));
1852 t!(v: b"a\\b\\c", set_filename, with_filename, b"d");
1853 t!(v: b"\\", set_filename, with_filename, b"foo");
1854 t!(s: "a\\b\\c", set_filename, with_filename, "d");
1855 t!(s: "\\", set_filename, with_filename, "foo");
1856 t!(s: ".", set_filename, with_filename, "foo");
1857 t!(s: "a\\b", set_filename, with_filename, "");
1858 t!(s: "a", set_filename, with_filename, "");
1860 t!(v: b"hi\\there.txt", set_extension, with_extension, b"exe");
1861 t!(s: "hi\\there.txt", set_extension, with_extension, "exe");
1862 t!(s: "hi\\there.", set_extension, with_extension, "txt");
1863 t!(s: "hi\\there", set_extension, with_extension, "txt");
1864 t!(s: "hi\\there.txt", set_extension, with_extension, "");
1865 t!(s: "hi\\there", set_extension, with_extension, "");
1866 t!(s: ".", set_extension, with_extension, "txt");
1868 // with_ helpers use the setter internally, so the tests for the with_ helpers
1869 // will suffice. No need for the full set of prefix tests.
1875 (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
1878 let filename = $filename;
1879 assert!(path.filename_str() == filename,
1880 "`{}`.filename_str(): Expected `{:?}`, found `{:?}`",
1881 path.as_str().unwrap(), filename, path.filename_str());
1882 let dirname = $dirname;
1883 assert!(path.dirname_str() == dirname,
1884 "`{}`.dirname_str(): Expected `{:?}`, found `{:?}`",
1885 path.as_str().unwrap(), dirname, path.dirname_str());
1886 let filestem = $filestem;
1887 assert!(path.filestem_str() == filestem,
1888 "`{}`.filestem_str(): Expected `{:?}`, found `{:?}`",
1889 path.as_str().unwrap(), filestem, path.filestem_str());
1891 assert!(path.extension_str() == ext,
1892 "`{}`.extension_str(): Expected `{:?}`, found `{:?}`",
1893 path.as_str().unwrap(), ext, path.extension_str());
1896 (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
1899 assert!(path.filename() == $filename);
1900 assert!(path.dirname() == $dirname);
1901 assert!(path.filestem() == $filestem);
1902 assert!(path.extension() == $ext);
1907 t!(v: Path::new(b"a\\b\\c"), Some(b"c"), b"a\\b", Some(b"c"), None);
1908 t!(s: Path::new("a\\b\\c"), Some("c"), Some("a\\b"), Some("c"), None);
1909 t!(s: Path::new("."), None, Some("."), None, None);
1910 t!(s: Path::new("\\"), None, Some("\\"), None, None);
1911 t!(s: Path::new(".."), None, Some(".."), None, None);
1912 t!(s: Path::new("..\\.."), None, Some("..\\.."), None, None);
1913 t!(s: Path::new("hi\\there.txt"), Some("there.txt"), Some("hi"),
1914 Some("there"), Some("txt"));
1915 t!(s: Path::new("hi\\there"), Some("there"), Some("hi"), Some("there"), None);
1916 t!(s: Path::new("hi\\there."), Some("there."), Some("hi"),
1917 Some("there"), Some(""));
1918 t!(s: Path::new("hi\\.there"), Some(".there"), Some("hi"), Some(".there"), None);
1919 t!(s: Path::new("hi\\..there"), Some("..there"), Some("hi"),
1920 Some("."), Some("there"));
1922 // these are already tested in test_components, so no need for extended tests
1926 fn test_dir_path() {
1927 t!(s: Path::new("hi\\there").dir_path(), "hi");
1928 t!(s: Path::new("hi").dir_path(), ".");
1929 t!(s: Path::new("\\hi").dir_path(), "\\");
1930 t!(s: Path::new("\\").dir_path(), "\\");
1931 t!(s: Path::new("..").dir_path(), "..");
1932 t!(s: Path::new("..\\..").dir_path(), "..\\..");
1934 // dir_path is just dirname interpreted as a path.
1935 // No need for extended tests
1939 fn test_is_absolute() {
1941 ($path:expr, $abs:expr, $vol:expr, $cwd:expr, $rel:expr) => (
1943 let path = Path::new($path);
1944 let (abs, vol, cwd, rel) = ($abs, $vol, $cwd, $rel);
1945 let b = path.is_absolute();
1946 assert!(b == abs, "Path '{}'.is_absolute(): expected {:?}, found {:?}",
1947 path.as_str().unwrap(), abs, b);
1948 let b = is_vol_relative(&path);
1949 assert!(b == vol, "is_vol_relative('{}'): expected {:?}, found {:?}",
1950 path.as_str().unwrap(), vol, b);
1951 let b = is_cwd_relative(&path);
1952 assert!(b == cwd, "is_cwd_relative('{}'): expected {:?}, found {:?}",
1953 path.as_str().unwrap(), cwd, b);
1954 let b = path.is_relative();
1955 assert!(b == rel, "Path '{}'.is_relativf(): expected {:?}, found {:?}",
1956 path.as_str().unwrap(), rel, b);
1960 t!("a\\b\\c", false, false, false, true);
1961 t!("\\a\\b\\c", false, true, false, false);
1962 t!("a", false, false, false, true);
1963 t!("\\a", false, true, false, false);
1964 t!(".", false, false, false, true);
1965 t!("\\", false, true, false, false);
1966 t!("..", false, false, false, true);
1967 t!("..\\..", false, false, false, true);
1968 t!("C:a\\b.txt", false, false, true, false);
1969 t!("C:\\a\\b.txt", true, false, false, false);
1970 t!("\\\\server\\share\\a\\b.txt", true, false, false, false);
1971 t!("\\\\?\\a\\b\\c.txt", true, false, false, false);
1972 t!("\\\\?\\C:\\a\\b.txt", true, false, false, false);
1973 t!("\\\\?\\C:a\\b.txt", true, false, false, false); // NB: not equivalent to C:a\b.txt
1974 t!("\\\\?\\UNC\\server\\share\\a\\b.txt", true, false, false, false);
1975 t!("\\\\.\\a\\b", true, false, false, false);
1979 fn test_is_ancestor_of() {
1981 (s: $path:expr, $dest:expr, $exp:expr) => (
1983 let path = Path::new($path);
1984 let dest = Path::new($dest);
1986 let res = path.is_ancestor_of(&dest);
1988 "`{}`.is_ancestor_of(`{}`): Expected {:?}, found {:?}",
1989 path.as_str().unwrap(), dest.as_str().unwrap(), exp, res);
1994 t!(s: "a\\b\\c", "a\\b\\c\\d", true);
1995 t!(s: "a\\b\\c", "a\\b\\c", true);
1996 t!(s: "a\\b\\c", "a\\b", false);
1997 t!(s: "\\a\\b\\c", "\\a\\b\\c", true);
1998 t!(s: "\\a\\b", "\\a\\b\\c", true);
1999 t!(s: "\\a\\b\\c\\d", "\\a\\b\\c", false);
2000 t!(s: "\\a\\b", "a\\b\\c", false);
2001 t!(s: "a\\b", "\\a\\b\\c", false);
2002 t!(s: "a\\b\\c", "a\\b\\d", false);
2003 t!(s: "..\\a\\b\\c", "a\\b\\c", false);
2004 t!(s: "a\\b\\c", "..\\a\\b\\c", false);
2005 t!(s: "a\\b\\c", "a\\b\\cd", false);
2006 t!(s: "a\\b\\cd", "a\\b\\c", false);
2007 t!(s: "..\\a\\b", "..\\a\\b\\c", true);
2008 t!(s: ".", "a\\b", true);
2009 t!(s: ".", ".", true);
2010 t!(s: "\\", "\\", true);
2011 t!(s: "\\", "\\a\\b", true);
2012 t!(s: "..", "a\\b", true);
2013 t!(s: "..\\..", "a\\b", true);
2014 t!(s: "foo\\bar", "foobar", false);
2015 t!(s: "foobar", "foo\\bar", false);
2017 t!(s: "foo", "C:foo", false);
2018 t!(s: "C:foo", "foo", false);
2019 t!(s: "C:foo", "C:foo\\bar", true);
2020 t!(s: "C:foo\\bar", "C:foo", false);
2021 t!(s: "C:\\foo", "C:\\foo\\bar", true);
2022 t!(s: "C:", "C:", true);
2023 t!(s: "C:", "C:\\", false);
2024 t!(s: "C:\\", "C:", false);
2025 t!(s: "C:\\", "C:\\", true);
2026 t!(s: "C:\\foo\\bar", "C:\\foo", false);
2027 t!(s: "C:foo\\bar", "C:foo", false);
2028 t!(s: "C:\\foo", "\\foo", false);
2029 t!(s: "\\foo", "C:\\foo", false);
2030 t!(s: "\\\\server\\share\\foo", "\\\\server\\share\\foo\\bar", true);
2031 t!(s: "\\\\server\\share", "\\\\server\\share\\foo", true);
2032 t!(s: "\\\\server\\share\\foo", "\\\\server\\share", false);
2033 t!(s: "C:\\foo", "\\\\server\\share\\foo", false);
2034 t!(s: "\\\\server\\share\\foo", "C:\\foo", false);
2035 t!(s: "\\\\?\\foo\\bar", "\\\\?\\foo\\bar\\baz", true);
2036 t!(s: "\\\\?\\foo\\bar\\baz", "\\\\?\\foo\\bar", false);
2037 t!(s: "\\\\?\\foo\\bar", "\\foo\\bar\\baz", false);
2038 t!(s: "\\foo\\bar", "\\\\?\\foo\\bar\\baz", false);
2039 t!(s: "\\\\?\\C:\\foo\\bar", "\\\\?\\C:\\foo\\bar\\baz", true);
2040 t!(s: "\\\\?\\C:\\foo\\bar\\baz", "\\\\?\\C:\\foo\\bar", false);
2041 t!(s: "\\\\?\\C:\\", "\\\\?\\C:\\foo", true);
2042 t!(s: "\\\\?\\C:", "\\\\?\\C:\\", false); // this is a weird one
2043 t!(s: "\\\\?\\C:\\", "\\\\?\\C:", false);
2044 t!(s: "\\\\?\\C:\\a", "\\\\?\\c:\\a\\b", true);
2045 t!(s: "\\\\?\\c:\\a", "\\\\?\\C:\\a\\b", true);
2046 t!(s: "\\\\?\\C:\\a", "\\\\?\\D:\\a\\b", false);
2047 t!(s: "\\\\?\\foo", "\\\\?\\foobar", false);
2048 t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\c", true);
2049 t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\", true);
2050 t!(s: "\\\\?\\a\\b\\", "\\\\?\\a\\b", true);
2051 t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b", false);
2052 t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b\\", false);
2053 t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\b\\c\\d", true);
2054 t!(s: "\\\\?\\UNC\\a\\b\\c\\d", "\\\\?\\UNC\\a\\b\\c", false);
2055 t!(s: "\\\\?\\UNC\\a\\b", "\\\\?\\UNC\\a\\b\\c", true);
2056 t!(s: "\\\\.\\foo\\bar", "\\\\.\\foo\\bar\\baz", true);
2057 t!(s: "\\\\.\\foo\\bar\\baz", "\\\\.\\foo\\bar", false);
2058 t!(s: "\\\\.\\foo", "\\\\.\\foo\\bar", true);
2059 t!(s: "\\\\.\\foo", "\\\\.\\foobar", false);
2061 t!(s: "\\a\\b", "\\\\?\\a\\b", false);
2062 t!(s: "\\\\?\\a\\b", "\\a\\b", false);
2063 t!(s: "\\a\\b", "\\\\?\\C:\\a\\b", false);
2064 t!(s: "\\\\?\\C:\\a\\b", "\\a\\b", false);
2065 t!(s: "Z:\\a\\b", "\\\\?\\z:\\a\\b", true);
2066 t!(s: "C:\\a\\b", "\\\\?\\D:\\a\\b", false);
2067 t!(s: "a\\b", "\\\\?\\a\\b", false);
2068 t!(s: "\\\\?\\a\\b", "a\\b", false);
2069 t!(s: "C:\\a\\b", "\\\\?\\C:\\a\\b", true);
2070 t!(s: "\\\\?\\C:\\a\\b", "C:\\a\\b", true);
2071 t!(s: "C:a\\b", "\\\\?\\C:\\a\\b", false);
2072 t!(s: "C:a\\b", "\\\\?\\C:a\\b", false);
2073 t!(s: "\\\\?\\C:\\a\\b", "C:a\\b", false);
2074 t!(s: "\\\\?\\C:a\\b", "C:a\\b", false);
2075 t!(s: "C:\\a\\b", "\\\\?\\C:\\a\\b\\", true);
2076 t!(s: "\\\\?\\C:\\a\\b\\", "C:\\a\\b", true);
2077 t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\b\\c", true);
2078 t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\b\\c", true);
2082 fn test_ends_with_path() {
2084 (s: $path:expr, $child:expr, $exp:expr) => (
2086 let path = Path::new($path);
2087 let child = Path::new($child);
2088 assert_eq!(path.ends_with_path(&child), $exp);
2093 t!(s: "a\\b\\c", "c", true);
2094 t!(s: "a\\b\\c", "d", false);
2095 t!(s: "foo\\bar\\quux", "bar", false);
2096 t!(s: "foo\\bar\\quux", "barquux", false);
2097 t!(s: "a\\b\\c", "b\\c", true);
2098 t!(s: "a\\b\\c", "a\\b\\c", true);
2099 t!(s: "a\\b\\c", "foo\\a\\b\\c", false);
2100 t!(s: "\\a\\b\\c", "a\\b\\c", true);
2101 t!(s: "\\a\\b\\c", "\\a\\b\\c", false); // child must be relative
2102 t!(s: "\\a\\b\\c", "foo\\a\\b\\c", false);
2103 t!(s: "a\\b\\c", "", false);
2104 t!(s: "", "", true);
2105 t!(s: "\\a\\b\\c", "d\\e\\f", false);
2106 t!(s: "a\\b\\c", "a\\b", false);
2107 t!(s: "a\\b\\c", "b", false);
2108 t!(s: "C:\\a\\b", "b", true);
2109 t!(s: "C:\\a\\b", "C:b", false);
2110 t!(s: "C:\\a\\b", "C:a\\b", false);
2114 fn test_path_relative_from() {
2116 (s: $path:expr, $other:expr, $exp:expr) => (
2118 let path = Path::new($path);
2119 let other = Path::new($other);
2120 let res = path.path_relative_from(&other);
2122 assert!(res.as_ref().and_then(|x| x.as_str()) == exp,
2123 "`{}`.path_relative_from(`{}`): Expected {:?}, got {:?}",
2124 path.as_str().unwrap(), other.as_str().unwrap(), exp,
2125 res.as_ref().and_then(|x| x.as_str()));
2130 t!(s: "a\\b\\c", "a\\b", Some("c"));
2131 t!(s: "a\\b\\c", "a\\b\\d", Some("..\\c"));
2132 t!(s: "a\\b\\c", "a\\b\\c\\d", Some(".."));
2133 t!(s: "a\\b\\c", "a\\b\\c", Some("."));
2134 t!(s: "a\\b\\c", "a\\b\\c\\d\\e", Some("..\\.."));
2135 t!(s: "a\\b\\c", "a\\d\\e", Some("..\\..\\b\\c"));
2136 t!(s: "a\\b\\c", "d\\e\\f", Some("..\\..\\..\\a\\b\\c"));
2137 t!(s: "a\\b\\c", "\\a\\b\\c", None);
2138 t!(s: "\\a\\b\\c", "a\\b\\c", Some("\\a\\b\\c"));
2139 t!(s: "\\a\\b\\c", "\\a\\b\\c\\d", Some(".."));
2140 t!(s: "\\a\\b\\c", "\\a\\b", Some("c"));
2141 t!(s: "\\a\\b\\c", "\\a\\b\\c\\d\\e", Some("..\\.."));
2142 t!(s: "\\a\\b\\c", "\\a\\d\\e", Some("..\\..\\b\\c"));
2143 t!(s: "\\a\\b\\c", "\\d\\e\\f", Some("..\\..\\..\\a\\b\\c"));
2144 t!(s: "hi\\there.txt", "hi\\there", Some("..\\there.txt"));
2145 t!(s: ".", "a", Some(".."));
2146 t!(s: ".", "a\\b", Some("..\\.."));
2147 t!(s: ".", ".", Some("."));
2148 t!(s: "a", ".", Some("a"));
2149 t!(s: "a\\b", ".", Some("a\\b"));
2150 t!(s: "..", ".", Some(".."));
2151 t!(s: "a\\b\\c", "a\\b\\c", Some("."));
2152 t!(s: "\\a\\b\\c", "\\a\\b\\c", Some("."));
2153 t!(s: "\\", "\\", Some("."));
2154 t!(s: "\\", ".", Some("\\"));
2155 t!(s: "..\\..\\a", "b", Some("..\\..\\..\\a"));
2156 t!(s: "a", "..\\..\\b", None);
2157 t!(s: "..\\..\\a", "..\\..\\b", Some("..\\a"));
2158 t!(s: "..\\..\\a", "..\\..\\a\\b", Some(".."));
2159 t!(s: "..\\..\\a\\b", "..\\..\\a", Some("b"));
2161 t!(s: "C:a\\b\\c", "C:a\\b", Some("c"));
2162 t!(s: "C:a\\b", "C:a\\b\\c", Some(".."));
2163 t!(s: "C:" ,"C:a\\b", Some("..\\.."));
2164 t!(s: "C:a\\b", "C:c\\d", Some("..\\..\\a\\b"));
2165 t!(s: "C:a\\b", "D:c\\d", Some("C:a\\b"));
2166 t!(s: "C:a\\b", "C:..\\c", None);
2167 t!(s: "C:..\\a", "C:b\\c", Some("..\\..\\..\\a"));
2168 t!(s: "C:\\a\\b\\c", "C:\\a\\b", Some("c"));
2169 t!(s: "C:\\a\\b", "C:\\a\\b\\c", Some(".."));
2170 t!(s: "C:\\", "C:\\a\\b", Some("..\\.."));
2171 t!(s: "C:\\a\\b", "C:\\c\\d", Some("..\\..\\a\\b"));
2172 t!(s: "C:\\a\\b", "C:a\\b", Some("C:\\a\\b"));
2173 t!(s: "C:a\\b", "C:\\a\\b", None);
2174 t!(s: "\\a\\b", "C:\\a\\b", None);
2175 t!(s: "\\a\\b", "C:a\\b", None);
2176 t!(s: "a\\b", "C:\\a\\b", None);
2177 t!(s: "a\\b", "C:a\\b", None);
2179 t!(s: "\\\\a\\b\\c", "\\\\a\\b", Some("c"));
2180 t!(s: "\\\\a\\b", "\\\\a\\b\\c", Some(".."));
2181 t!(s: "\\\\a\\b\\c\\e", "\\\\a\\b\\c\\d", Some("..\\e"));
2182 t!(s: "\\\\a\\c\\d", "\\\\a\\b\\d", Some("\\\\a\\c\\d"));
2183 t!(s: "\\\\b\\c\\d", "\\\\a\\c\\d", Some("\\\\b\\c\\d"));
2184 t!(s: "\\\\a\\b\\c", "\\d\\e", Some("\\\\a\\b\\c"));
2185 t!(s: "\\d\\e", "\\\\a\\b\\c", None);
2186 t!(s: "d\\e", "\\\\a\\b\\c", None);
2187 t!(s: "C:\\a\\b\\c", "\\\\a\\b\\c", Some("C:\\a\\b\\c"));
2188 t!(s: "C:\\c", "\\\\a\\b\\c", Some("C:\\c"));
2190 t!(s: "\\\\?\\a\\b", "\\a\\b", Some("\\\\?\\a\\b"));
2191 t!(s: "\\\\?\\a\\b", "a\\b", Some("\\\\?\\a\\b"));
2192 t!(s: "\\\\?\\a\\b", "\\b", Some("\\\\?\\a\\b"));
2193 t!(s: "\\\\?\\a\\b", "b", Some("\\\\?\\a\\b"));
2194 t!(s: "\\\\?\\a\\b", "\\\\?\\a\\b\\c", Some(".."));
2195 t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\b", Some("c"));
2196 t!(s: "\\\\?\\a\\b", "\\\\?\\c\\d", Some("\\\\?\\a\\b"));
2197 t!(s: "\\\\?\\a", "\\\\?\\b", Some("\\\\?\\a"));
2199 t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\C:\\a", Some("b"));
2200 t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\a\\b", Some(".."));
2201 t!(s: "\\\\?\\C:\\a", "\\\\?\\C:\\b", Some("..\\a"));
2202 t!(s: "\\\\?\\C:\\a", "\\\\?\\D:\\a", Some("\\\\?\\C:\\a"));
2203 t!(s: "\\\\?\\C:\\a\\b", "\\\\?\\c:\\a", Some("b"));
2204 t!(s: "\\\\?\\C:\\a\\b", "C:\\a", Some("b"));
2205 t!(s: "\\\\?\\C:\\a", "C:\\a\\b", Some(".."));
2206 t!(s: "C:\\a\\b", "\\\\?\\C:\\a", Some("b"));
2207 t!(s: "C:\\a", "\\\\?\\C:\\a\\b", Some(".."));
2208 t!(s: "\\\\?\\C:\\a", "D:\\a", Some("\\\\?\\C:\\a"));
2209 t!(s: "\\\\?\\c:\\a\\b", "C:\\a", Some("b"));
2210 t!(s: "\\\\?\\C:\\a\\b", "C:a\\b", Some("\\\\?\\C:\\a\\b"));
2211 t!(s: "\\\\?\\C:\\a\\.\\b", "C:\\a", Some("\\\\?\\C:\\a\\.\\b"));
2212 t!(s: "\\\\?\\C:\\a\\b/c", "C:\\a", Some("\\\\?\\C:\\a\\b/c"));
2213 t!(s: "\\\\?\\C:\\a\\..\\b", "C:\\a", Some("\\\\?\\C:\\a\\..\\b"));
2214 t!(s: "C:a\\b", "\\\\?\\C:\\a\\b", None);
2215 t!(s: "\\\\?\\C:\\a\\.\\b", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\.\\b"));
2216 t!(s: "\\\\?\\C:\\a\\b/c", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\b/c"));
2217 t!(s: "\\\\?\\C:\\a\\..\\b", "\\\\?\\C:\\a", Some("\\\\?\\C:\\a\\..\\b"));
2218 t!(s: "\\\\?\\C:\\a\\b\\", "\\\\?\\C:\\a", Some("b"));
2219 t!(s: "\\\\?\\C:\\.\\b", "\\\\?\\C:\\.", Some("b"));
2220 t!(s: "C:\\b", "\\\\?\\C:\\.", Some("..\\b"));
2221 t!(s: "\\\\?\\a\\.\\b\\c", "\\\\?\\a\\.\\b", Some("c"));
2222 t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\.\\d", Some("..\\..\\b\\c"));
2223 t!(s: "\\\\?\\a\\..\\b", "\\\\?\\a\\..", Some("b"));
2224 t!(s: "\\\\?\\a\\b\\..", "\\\\?\\a\\b", Some("\\\\?\\a\\b\\.."));
2225 t!(s: "\\\\?\\a\\b\\c", "\\\\?\\a\\..\\b", Some("..\\..\\b\\c"));
2227 t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\b", Some("c"));
2228 t!(s: "\\\\?\\UNC\\a\\b", "\\\\?\\UNC\\a\\b\\c", Some(".."));
2229 t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\UNC\\a\\c\\d", Some("\\\\?\\UNC\\a\\b\\c"));
2230 t!(s: "\\\\?\\UNC\\b\\c\\d", "\\\\?\\UNC\\a\\c\\d", Some("\\\\?\\UNC\\b\\c\\d"));
2231 t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\a\\b\\c", Some("\\\\?\\UNC\\a\\b\\c"));
2232 t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\?\\C:\\a\\b\\c", Some("\\\\?\\UNC\\a\\b\\c"));
2233 t!(s: "\\\\?\\UNC\\a\\b\\c/d", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\c/d"));
2234 t!(s: "\\\\?\\UNC\\a\\b\\.", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\."));
2235 t!(s: "\\\\?\\UNC\\a\\b\\..", "\\\\?\\UNC\\a\\b", Some("\\\\?\\UNC\\a\\b\\.."));
2236 t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\b", Some("c"));
2237 t!(s: "\\\\?\\UNC\\a\\b", "\\\\a\\b\\c", Some(".."));
2238 t!(s: "\\\\?\\UNC\\a\\b\\c", "\\\\a\\c\\d", Some("\\\\?\\UNC\\a\\b\\c"));
2239 t!(s: "\\\\?\\UNC\\b\\c\\d", "\\\\a\\c\\d", Some("\\\\?\\UNC\\b\\c\\d"));
2240 t!(s: "\\\\?\\UNC\\a\\b\\.", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\."));
2241 t!(s: "\\\\?\\UNC\\a\\b\\c/d", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\c/d"));
2242 t!(s: "\\\\?\\UNC\\a\\b\\..", "\\\\a\\b", Some("\\\\?\\UNC\\a\\b\\.."));
2243 t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\b", Some("c"));
2244 t!(s: "\\\\a\\b\\c", "\\\\?\\UNC\\a\\c\\d", Some("\\\\a\\b\\c"));
2248 fn test_str_components() {
2250 (s: $path:expr, $exp:expr) => (
2252 let path = Path::new($path);
2253 let comps = path.str_components().map(|x|x.unwrap())
2254 .collect::<Vec<&str>>();
2255 let exp: &[&str] = $exp;
2256 assert_eq!(comps.as_slice(), exp);
2257 let comps = path.str_components().rev().map(|x|x.unwrap())
2258 .collect::<Vec<&str>>();
2259 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&str>>();
2260 assert_eq!(comps, exp);
2265 t!(s: b"a\\b\\c", ["a", "b", "c"]);
2266 t!(s: "a\\b\\c", ["a", "b", "c"]);
2267 t!(s: "a\\b\\d", ["a", "b", "d"]);
2268 t!(s: "a\\b\\cd", ["a", "b", "cd"]);
2269 t!(s: "\\a\\b\\c", ["a", "b", "c"]);
2271 t!(s: "\\a", ["a"]);
2274 t!(s: "..", [".."]);
2275 t!(s: "..\\..", ["..", ".."]);
2276 t!(s: "..\\..\\foo", ["..", "..", "foo"]);
2277 t!(s: "C:foo\\bar", ["foo", "bar"]);
2278 t!(s: "C:foo", ["foo"]);
2280 t!(s: "C:\\foo\\bar", ["foo", "bar"]);
2281 t!(s: "C:\\foo", ["foo"]);
2283 t!(s: "\\\\server\\share\\foo\\bar", ["foo", "bar"]);
2284 t!(s: "\\\\server\\share\\foo", ["foo"]);
2285 t!(s: "\\\\server\\share", []);
2286 t!(s: "\\\\?\\foo\\bar\\baz", ["bar", "baz"]);
2287 t!(s: "\\\\?\\foo\\bar", ["bar"]);
2288 t!(s: "\\\\?\\foo", []);
2289 t!(s: "\\\\?\\", []);
2290 t!(s: "\\\\?\\a\\b", ["b"]);
2291 t!(s: "\\\\?\\a\\b\\", ["b"]);
2292 t!(s: "\\\\?\\foo\\bar\\\\baz", ["bar", "", "baz"]);
2293 t!(s: "\\\\?\\C:\\foo\\bar", ["foo", "bar"]);
2294 t!(s: "\\\\?\\C:\\foo", ["foo"]);
2295 t!(s: "\\\\?\\C:\\", []);
2296 t!(s: "\\\\?\\C:\\foo\\", ["foo"]);
2297 t!(s: "\\\\?\\UNC\\server\\share\\foo\\bar", ["foo", "bar"]);
2298 t!(s: "\\\\?\\UNC\\server\\share\\foo", ["foo"]);
2299 t!(s: "\\\\?\\UNC\\server\\share", []);
2300 t!(s: "\\\\.\\foo\\bar\\baz", ["bar", "baz"]);
2301 t!(s: "\\\\.\\foo\\bar", ["bar"]);
2302 t!(s: "\\\\.\\foo", []);
2306 fn test_components_iter() {
2308 (s: $path:expr, $exp:expr) => (
2310 let path = Path::new($path);
2311 let comps = path.components().collect::<Vec<&[u8]>>();
2312 let exp: &[&[u8]] = $exp;
2313 assert_eq!(comps.as_slice(), exp);
2314 let comps = path.components().rev().collect::<Vec<&[u8]>>();
2315 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
2316 assert_eq!(comps, exp);
2321 t!(s: "a\\b\\c", [b"a", b"b", b"c"]);
2323 // since this is really a wrapper around str_components, those tests suffice
2327 fn test_make_non_verbatim() {
2329 ($path:expr, $exp:expr) => (
2331 let path = Path::new($path);
2332 let exp: Option<&str> = $exp;
2333 let exp = exp.map(|s| Path::new(s));
2334 assert!(make_non_verbatim(&path) == exp);
2339 t!(r"\a\b\c", Some(r"\a\b\c"));
2340 t!(r"a\b\c", Some(r"a\b\c"));
2341 t!(r"C:\a\b\c", Some(r"C:\a\b\c"));
2342 t!(r"C:a\b\c", Some(r"C:a\b\c"));
2343 t!(r"\\server\share\foo", Some(r"\\server\share\foo"));
2344 t!(r"\\.\foo", None);
2345 t!(r"\\?\foo", None);
2346 t!(r"\\?\C:", None);
2347 t!(r"\\?\C:foo", None);
2348 t!(r"\\?\C:\", Some(r"C:\"));
2349 t!(r"\\?\C:\foo", Some(r"C:\foo"));
2350 t!(r"\\?\C:\foo\bar\baz", Some(r"C:\foo\bar\baz"));
2351 t!(r"\\?\C:\foo\.\bar\baz", None);
2352 t!(r"\\?\C:\foo\bar\..\baz", None);
2353 t!(r"\\?\C:\foo\bar\..", None);
2354 t!(r"\\?\UNC\server\share\foo", Some(r"\\server\share\foo"));
2355 t!(r"\\?\UNC\server\share", Some(r"\\server\share"));
2356 t!(r"\\?\UNC\server", None);
2357 t!(r"\\?\UNC\server\", None);