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 //! POSIX file path handling
13 use c_str::{CString, ToCStr};
15 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
18 use iter::{DoubleEndedIteratorExt, AdditiveIterator, Extend};
19 use iter::{Iterator, IteratorExt, Map};
21 use option::Option::{None, Some};
23 use str::{FromStr, Str};
25 use slice::{CloneSliceAllocPrelude, Splits, AsSlice, VectorVector,
26 PartialEqSlicePrelude, SlicePrelude};
29 use super::{BytesContainer, GenericPath, GenericPathUnsafe};
31 /// Iterator that yields successive components of a Path as &[u8]
32 pub type Components<'a> = Splits<'a, u8>;
34 /// Iterator that yields successive components of a Path as Option<&str>
35 pub type StrComponents<'a> = Map<'a, &'a [u8], Option<&'a str>,
38 /// Represents a POSIX file path
41 repr: Vec<u8>, // assumed to never be empty or contain NULs
42 sepidx: Option<uint> // index of the final separator in repr
45 /// The standard path separator character
46 pub const SEP: char = '/';
48 /// The standard path separator byte
49 pub const SEP_BYTE: u8 = SEP as u8;
51 /// Returns whether the given byte is a path separator
53 pub fn is_sep_byte(u: &u8) -> bool {
57 /// Returns whether the given char is a path separator
59 pub fn is_sep(c: char) -> bool {
63 impl PartialEq for Path {
65 fn eq(&self, other: &Path) -> bool {
66 self.repr == other.repr
72 impl PartialOrd for Path {
73 fn partial_cmp(&self, other: &Path) -> Option<Ordering> {
79 fn cmp(&self, other: &Path) -> Ordering {
80 self.repr.cmp(&other.repr)
84 impl FromStr for Path {
85 fn from_str(s: &str) -> Option<Path> {
90 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
91 // we cannot usefully take ToCStr arguments by reference (without forcing an
92 // additional & around &str). So we are instead temporarily adding an instance
93 // for &Path, so that we can take ToCStr as owned. When DST lands, the &Path
94 // instance should be removed, and arguments bound by ToCStr should be passed by
97 impl ToCStr for Path {
99 fn to_c_str(&self) -> CString {
100 // The Path impl guarantees no internal NUL
101 unsafe { self.to_c_str_unchecked() }
105 unsafe fn to_c_str_unchecked(&self) -> CString {
106 self.as_vec().to_c_str_unchecked()
110 impl<S: hash::Writer> hash::Hash<S> for Path {
112 fn hash(&self, state: &mut S) {
113 self.repr.hash(state)
117 impl BytesContainer for Path {
119 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
124 impl GenericPathUnsafe for Path {
125 unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
126 let path = Path::normalize(path.container_as_bytes());
127 assert!(!path.is_empty());
128 let idx = path.as_slice().rposition_elem(&SEP_BYTE);
129 Path{ repr: path, sepidx: idx }
132 unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
133 let filename = filename.container_as_bytes();
135 None if b".." == self.repr.as_slice() => {
136 let mut v = Vec::with_capacity(3 + filename.len());
137 v.push_all(dot_dot_static);
139 v.push_all(filename);
140 // FIXME: this is slow
141 self.repr = Path::normalize(v.as_slice());
144 self.repr = Path::normalize(filename);
146 Some(idx) if self.repr[idx+1..] == b".." => {
147 let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
148 v.push_all(self.repr.as_slice());
150 v.push_all(filename);
151 // FIXME: this is slow
152 self.repr = Path::normalize(v.as_slice());
155 let mut v = Vec::with_capacity(idx + 1 + filename.len());
156 v.push_all(self.repr[..idx+1]);
157 v.push_all(filename);
158 // FIXME: this is slow
159 self.repr = Path::normalize(v.as_slice());
162 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
165 unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
166 let path = path.container_as_bytes();
167 if !path.is_empty() {
168 if path[0] == SEP_BYTE {
169 self.repr = Path::normalize(path);
171 let mut v = Vec::with_capacity(self.repr.len() + path.len() + 1);
172 v.push_all(self.repr.as_slice());
175 // FIXME: this is slow
176 self.repr = Path::normalize(v.as_slice());
178 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
183 impl GenericPath for Path {
185 fn as_vec<'a>(&'a self) -> &'a [u8] {
189 fn into_vec(self) -> Vec<u8> {
193 fn dirname<'a>(&'a self) -> &'a [u8] {
195 None if b".." == self.repr.as_slice() => self.repr.as_slice(),
197 Some(0) => self.repr[..1],
198 Some(idx) if self.repr[idx+1..] == b".." => self.repr.as_slice(),
199 Some(idx) => self.repr[..idx]
203 fn filename<'a>(&'a self) -> Option<&'a [u8]> {
205 None if b"." == self.repr.as_slice() ||
206 b".." == self.repr.as_slice() => None,
207 None => Some(self.repr.as_slice()),
208 Some(idx) if self.repr[idx+1..] == b".." => None,
209 Some(0) if self.repr[1..].is_empty() => None,
210 Some(idx) => Some(self.repr[idx+1..])
214 fn pop(&mut self) -> bool {
216 None if b"." == self.repr.as_slice() => false,
218 self.repr = vec![b'.'];
222 Some(0) if b"/" == self.repr.as_slice() => false,
225 self.repr.truncate(idx+1);
227 self.repr.truncate(idx);
229 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
235 fn root_path(&self) -> Option<Path> {
236 if self.is_absolute() {
244 fn is_absolute(&self) -> bool {
245 self.repr[0] == SEP_BYTE
248 fn is_ancestor_of(&self, other: &Path) -> bool {
249 if self.is_absolute() != other.is_absolute() {
252 let mut ita = self.components();
253 let mut itb = other.components();
254 if b"." == self.repr.as_slice() {
255 return match itb.next() {
257 Some(b) => b != b".."
261 match (ita.next(), itb.next()) {
263 (Some(a), Some(b)) if a == b => { continue },
264 (Some(a), _) if a == b".." => {
265 // if ita contains only .. components, it's an ancestor
266 return ita.all(|x| x == b"..");
275 fn path_relative_from(&self, base: &Path) -> Option<Path> {
276 if self.is_absolute() != base.is_absolute() {
277 if self.is_absolute() {
283 let mut ita = self.components();
284 let mut itb = base.components();
285 let mut comps = vec![];
287 match (ita.next(), itb.next()) {
288 (None, None) => break,
291 comps.extend(ita.by_ref());
294 (None, _) => comps.push(dot_dot_static),
295 (Some(a), Some(b)) if comps.is_empty() && a == b => (),
296 (Some(a), Some(b)) if b == b"." => comps.push(a),
297 (Some(_), Some(b)) if b == b".." => return None,
298 (Some(a), Some(_)) => {
299 comps.push(dot_dot_static);
301 comps.push(dot_dot_static);
304 comps.extend(ita.by_ref());
309 Some(Path::new(comps.as_slice().connect_vec(&SEP_BYTE)))
313 fn ends_with_path(&self, child: &Path) -> bool {
314 if !child.is_relative() { return false; }
315 let mut selfit = self.components().rev();
316 let mut childit = child.components().rev();
318 match (selfit.next(), childit.next()) {
319 (Some(a), Some(b)) => if a != b { return false; },
320 (Some(_), None) => break,
321 (None, Some(_)) => return false,
322 (None, None) => break
330 /// Returns a new Path from a byte vector or string
334 /// Panics the task if the vector contains a NUL.
336 pub fn new<T: BytesContainer>(path: T) -> Path {
337 GenericPath::new(path)
340 /// Returns a new Path from a byte vector or string, if possible
342 pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
343 GenericPath::new_opt(path)
346 /// Returns a normalized byte vector representation of a path, by removing all empty
347 /// components, and unnecessary . and .. components.
348 fn normalize<Sized? V: AsSlice<u8>>(v: &V) -> Vec<u8> {
349 // borrowck is being very picky
351 let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE;
352 let v_ = if is_abs { v.as_slice()[1..] } else { v.as_slice() };
353 let comps = normalize_helper(v_, is_abs);
357 if is_abs && comps.is_empty() {
360 let n = if is_abs { comps.len() } else { comps.len() - 1} +
361 comps.iter().map(|v| v.len()).sum();
362 let mut v = Vec::with_capacity(n);
363 let mut it = comps.into_iter();
367 Some(comp) => v.push_all(comp)
380 None => v.as_slice().to_vec(),
385 /// Returns an iterator that yields each component of the path in turn.
386 /// Does not distinguish between absolute and relative paths, e.g.
387 /// /a/b/c and a/b/c yield the same set of components.
388 /// A path of "/" yields no components. A path of "." yields one component.
389 pub fn components<'a>(&'a self) -> Components<'a> {
390 let v = if self.repr[0] == SEP_BYTE {
392 } else { self.repr.as_slice() };
393 let mut ret = v.split(is_sep_byte);
395 // consume the empty "" component
401 /// Returns an iterator that yields each component of the path as Option<&str>.
402 /// See components() for details.
403 pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
404 self.components().map(str::from_utf8)
408 // None result means the byte vector didn't need normalizing
409 fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<Vec<&'a [u8]>> {
410 if is_abs && v.as_slice().is_empty() {
413 let mut comps: Vec<&'a [u8]> = vec![];
415 let mut changed = false;
416 for comp in v.split(is_sep_byte) {
417 if comp.is_empty() { changed = true }
418 else if comp == b"." { changed = true }
419 else if comp == b".." {
420 if is_abs && comps.is_empty() { changed = true }
421 else if comps.len() == n_up { comps.push(dot_dot_static); n_up += 1 }
422 else { comps.pop().unwrap(); changed = true }
423 } else { comps.push(comp) }
426 if comps.is_empty() && !is_abs {
430 comps.push(dot_static);
438 #[allow(non_upper_case_globals)]
439 static dot_static: &'static [u8] = b".";
440 #[allow(non_upper_case_globals)]
441 static dot_dot_static: &'static [u8] = b"..";
451 (s: $path:expr, $exp:expr) => (
454 assert!(path.as_str() == Some($exp));
457 (v: $path:expr, $exp:expr) => (
460 assert!(path.as_vec() == $exp);
467 let empty: &[u8] = &[];
468 t!(v: Path::new(empty), b".");
469 t!(v: Path::new(b"/"), b"/");
470 t!(v: Path::new(b"a/b/c"), b"a/b/c");
471 t!(v: Path::new(b"a/b/c\xFF"), b"a/b/c\xFF");
472 t!(v: Path::new(b"\xFF/../foo\x80"), b"foo\x80");
473 let p = Path::new(b"a/b/c\xFF");
474 assert!(p.as_str() == None);
476 t!(s: Path::new(""), ".");
477 t!(s: Path::new("/"), "/");
478 t!(s: Path::new("hi"), "hi");
479 t!(s: Path::new("hi/"), "hi");
480 t!(s: Path::new("/lib"), "/lib");
481 t!(s: Path::new("/lib/"), "/lib");
482 t!(s: Path::new("hi/there"), "hi/there");
483 t!(s: Path::new("hi/there.txt"), "hi/there.txt");
485 t!(s: Path::new("hi/there/"), "hi/there");
486 t!(s: Path::new("hi/../there"), "there");
487 t!(s: Path::new("../hi/there"), "../hi/there");
488 t!(s: Path::new("/../hi/there"), "/hi/there");
489 t!(s: Path::new("foo/.."), ".");
490 t!(s: Path::new("/foo/.."), "/");
491 t!(s: Path::new("/foo/../.."), "/");
492 t!(s: Path::new("/foo/../../bar"), "/bar");
493 t!(s: Path::new("/./hi/./there/."), "/hi/there");
494 t!(s: Path::new("/./hi/./there/./.."), "/hi");
495 t!(s: Path::new("foo/../.."), "..");
496 t!(s: Path::new("foo/../../.."), "../..");
497 t!(s: Path::new("foo/../../bar"), "../bar");
499 assert_eq!(Path::new(b"foo/bar").into_vec().as_slice(), b"foo/bar");
500 assert_eq!(Path::new(b"/foo/../../bar").into_vec().as_slice(),
503 let p = Path::new(b"foo/bar\x80");
504 assert!(p.as_str() == None);
508 fn test_opt_paths() {
509 assert!(Path::new_opt(b"foo/bar\0") == None);
510 t!(v: Path::new_opt(b"foo/bar").unwrap(), b"foo/bar");
511 assert!(Path::new_opt("foo/bar\0") == None);
512 t!(s: Path::new_opt("foo/bar").unwrap(), "foo/bar");
516 fn test_null_byte() {
518 let result = task::try(proc() {
519 Path::new(b"foo/bar\0")
521 assert!(result.is_err());
523 let result = task::try(proc() {
524 Path::new("test").set_filename(b"f\0o")
526 assert!(result.is_err());
528 let result = task::try(proc() {
529 Path::new("test").push(b"f\0o");
531 assert!(result.is_err());
535 fn test_display_str() {
537 ($path:expr, $disp:ident, $exp:expr) => (
539 let path = Path::new($path);
540 assert!(path.$disp().to_string().as_slice() == $exp);
544 t!("foo", display, "foo");
545 t!(b"foo\x80", display, "foo\uFFFD");
546 t!(b"foo\xFFbar", display, "foo\uFFFDbar");
547 t!(b"foo\xFF/bar", filename_display, "bar");
548 t!(b"foo/\xFFbar", filename_display, "\uFFFDbar");
549 t!(b"/", filename_display, "");
552 ($path:expr, $exp:expr) => (
554 let path = Path::new($path);
555 let mo = path.display().as_cow();
556 assert!(mo.as_slice() == $exp);
559 ($path:expr, $exp:expr, filename) => (
561 let path = Path::new($path);
562 let mo = path.filename_display().as_cow();
563 assert!(mo.as_slice() == $exp);
569 t!(b"foo\x80", "foo\uFFFD");
570 t!(b"foo\xFFbar", "foo\uFFFDbar");
571 t!(b"foo\xFF/bar", "bar", filename);
572 t!(b"foo/\xFFbar", "\uFFFDbar", filename);
573 t!(b"/", "", filename);
579 ($path:expr, $exp:expr, $expf:expr) => (
581 let path = Path::new($path);
582 let f = format!("{}", path.display());
583 assert!(f.as_slice() == $exp);
584 let f = format!("{}", path.filename_display());
585 assert!(f.as_slice() == $expf);
590 t!(b"foo", "foo", "foo");
591 t!(b"foo/bar", "foo/bar", "bar");
593 t!(b"foo\xFF", "foo\uFFFD", "foo\uFFFD");
594 t!(b"foo\xFF/bar", "foo\uFFFD/bar", "bar");
595 t!(b"foo/\xFFbar", "foo/\uFFFDbar", "\uFFFDbar");
596 t!(b"\xFFfoo/bar\xFF", "\uFFFDfoo/bar\uFFFD", "bar\uFFFD");
600 fn test_components() {
602 (s: $path:expr, $op:ident, $exp:expr) => (
604 let path = Path::new($path);
605 assert!(path.$op() == ($exp).as_bytes());
608 (s: $path:expr, $op:ident, $exp:expr, opt) => (
610 let path = Path::new($path);
611 let left = path.$op().map(|x| str::from_utf8(x).unwrap());
612 assert!(left == $exp);
615 (v: $path:expr, $op:ident, $exp:expr) => (
618 let path = Path::new(arg);
619 assert!(path.$op() == $exp);
624 t!(v: b"a/b/c", filename, Some(b"c"));
625 t!(v: b"a/b/c\xFF", filename, Some(b"c\xFF"));
626 t!(v: b"a/b\xFF/c", filename, Some(b"c"));
627 t!(s: "a/b/c", filename, Some("c"), opt);
628 t!(s: "/a/b/c", filename, Some("c"), opt);
629 t!(s: "a", filename, Some("a"), opt);
630 t!(s: "/a", filename, Some("a"), opt);
631 t!(s: ".", filename, None, opt);
632 t!(s: "/", filename, None, opt);
633 t!(s: "..", filename, None, opt);
634 t!(s: "../..", filename, None, opt);
636 t!(v: b"a/b/c", dirname, b"a/b");
637 t!(v: b"a/b/c\xFF", dirname, b"a/b");
638 t!(v: b"a/b\xFF/c", dirname, b"a/b\xFF");
639 t!(s: "a/b/c", dirname, "a/b");
640 t!(s: "/a/b/c", dirname, "/a/b");
641 t!(s: "a", dirname, ".");
642 t!(s: "/a", dirname, "/");
643 t!(s: ".", dirname, ".");
644 t!(s: "/", dirname, "/");
645 t!(s: "..", dirname, "..");
646 t!(s: "../..", dirname, "../..");
648 t!(v: b"hi/there.txt", filestem, Some(b"there"));
649 t!(v: b"hi/there\x80.txt", filestem, Some(b"there\x80"));
650 t!(v: b"hi/there.t\x80xt", filestem, Some(b"there"));
651 t!(s: "hi/there.txt", filestem, Some("there"), opt);
652 t!(s: "hi/there", filestem, Some("there"), opt);
653 t!(s: "there.txt", filestem, Some("there"), opt);
654 t!(s: "there", filestem, Some("there"), opt);
655 t!(s: ".", filestem, None, opt);
656 t!(s: "/", filestem, None, opt);
657 t!(s: "foo/.bar", filestem, Some(".bar"), opt);
658 t!(s: ".bar", filestem, Some(".bar"), opt);
659 t!(s: "..bar", filestem, Some("."), opt);
660 t!(s: "hi/there..txt", filestem, Some("there."), opt);
661 t!(s: "..", filestem, None, opt);
662 t!(s: "../..", filestem, None, opt);
664 t!(v: b"hi/there.txt", extension, Some(b"txt"));
665 t!(v: b"hi/there\x80.txt", extension, Some(b"txt"));
666 t!(v: b"hi/there.t\x80xt", extension, Some(b"t\x80xt"));
667 t!(v: b"hi/there", extension, None);
668 t!(v: b"hi/there\x80", extension, None);
669 t!(s: "hi/there.txt", extension, Some("txt"), opt);
670 t!(s: "hi/there", extension, None, opt);
671 t!(s: "there.txt", extension, Some("txt"), opt);
672 t!(s: "there", extension, None, opt);
673 t!(s: ".", extension, None, opt);
674 t!(s: "/", extension, None, opt);
675 t!(s: "foo/.bar", extension, None, opt);
676 t!(s: ".bar", extension, None, opt);
677 t!(s: "..bar", extension, Some("bar"), opt);
678 t!(s: "hi/there..txt", extension, Some("txt"), opt);
679 t!(s: "..", extension, None, opt);
680 t!(s: "../..", extension, None, opt);
686 (s: $path:expr, $join:expr) => (
690 let mut p1 = Path::new(path);
693 assert!(p1 == p2.join(join));
698 t!(s: "a/b/c", "..");
699 t!(s: "/a/b/c", "d");
701 t!(s: "a/b", "/c/d");
705 fn test_push_path() {
707 (s: $path:expr, $push:expr, $exp:expr) => (
709 let mut p = Path::new($path);
710 let push = Path::new($push);
712 assert!(p.as_str() == Some($exp));
717 t!(s: "a/b/c", "d", "a/b/c/d");
718 t!(s: "/a/b/c", "d", "/a/b/c/d");
719 t!(s: "a/b", "c/d", "a/b/c/d");
720 t!(s: "a/b", "/c/d", "/c/d");
721 t!(s: "a/b", ".", "a/b");
722 t!(s: "a/b", "../c", "a/c");
726 fn test_push_many() {
728 (s: $path:expr, $push:expr, $exp:expr) => (
730 let mut p = Path::new($path);
732 assert!(p.as_str() == Some($exp));
735 (v: $path:expr, $push:expr, $exp:expr) => (
737 let mut p = Path::new($path);
739 assert!(p.as_vec() == $exp);
744 t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
745 t!(s: "a/b/c", ["d", "/e"], "/e");
746 t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
747 t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
748 t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
749 t!(v: b"a/b/c", [b"d", b"/e", b"f"], b"/e/f");
750 t!(v: b"a/b/c", [b"d".to_vec(), b"e".to_vec()], b"a/b/c/d/e");
756 (s: $path:expr, $left:expr, $right:expr) => (
758 let mut p = Path::new($path);
759 let result = p.pop();
760 assert!(p.as_str() == Some($left));
761 assert!(result == $right);
764 (b: $path:expr, $left:expr, $right:expr) => (
766 let mut p = Path::new($path);
767 let result = p.pop();
768 assert!(p.as_vec() == $left);
769 assert!(result == $right);
774 t!(b: b"a/b/c", b"a/b", true);
775 t!(b: b"a", b".", true);
776 t!(b: b".", b".", false);
777 t!(b: b"/a", b"/", true);
778 t!(b: b"/", b"/", false);
779 t!(b: b"a/b/c\x80", b"a/b", true);
780 t!(b: b"a/b\x80/c", b"a/b\x80", true);
781 t!(b: b"\xFF", b".", true);
782 t!(b: b"/\xFF", b"/", true);
783 t!(s: "a/b/c", "a/b", true);
784 t!(s: "a", ".", true);
785 t!(s: ".", ".", false);
786 t!(s: "/a", "/", true);
787 t!(s: "/", "/", false);
791 fn test_root_path() {
792 assert!(Path::new(b"a/b/c").root_path() == None);
793 assert!(Path::new(b"/a/b/c").root_path() == Some(Path::new("/")));
798 t!(v: Path::new(b"a/b/c").join(b".."), b"a/b");
799 t!(v: Path::new(b"/a/b/c").join(b"d"), b"/a/b/c/d");
800 t!(v: Path::new(b"a/\x80/c").join(b"\xFF"), b"a/\x80/c/\xFF");
801 t!(s: Path::new("a/b/c").join(".."), "a/b");
802 t!(s: Path::new("/a/b/c").join("d"), "/a/b/c/d");
803 t!(s: Path::new("a/b").join("c/d"), "a/b/c/d");
804 t!(s: Path::new("a/b").join("/c/d"), "/c/d");
805 t!(s: Path::new(".").join("a/b"), "a/b");
806 t!(s: Path::new("/").join("a/b"), "/a/b");
810 fn test_join_path() {
812 (s: $path:expr, $join:expr, $exp:expr) => (
814 let path = Path::new($path);
815 let join = Path::new($join);
816 let res = path.join(&join);
817 assert!(res.as_str() == Some($exp));
822 t!(s: "a/b/c", "..", "a/b");
823 t!(s: "/a/b/c", "d", "/a/b/c/d");
824 t!(s: "a/b", "c/d", "a/b/c/d");
825 t!(s: "a/b", "/c/d", "/c/d");
826 t!(s: ".", "a/b", "a/b");
827 t!(s: "/", "a/b", "/a/b");
831 fn test_join_many() {
833 (s: $path:expr, $join:expr, $exp:expr) => (
835 let path = Path::new($path);
836 let res = path.join_many(&$join);
837 assert!(res.as_str() == Some($exp));
840 (v: $path:expr, $join:expr, $exp:expr) => (
842 let path = Path::new($path);
843 let res = path.join_many(&$join);
844 assert!(res.as_vec() == $exp);
849 t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
850 t!(s: "a/b/c", ["..", "d"], "a/b/d");
851 t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
852 t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
853 t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
854 t!(v: b"a/b/c", [b"d".to_vec(), b"e".to_vec()], b"a/b/c/d/e");
858 fn test_with_helpers() {
859 let empty: &[u8] = &[];
861 t!(v: Path::new(b"a/b/c").with_filename(b"d"), b"a/b/d");
862 t!(v: Path::new(b"a/b/c\xFF").with_filename(b"\x80"), b"a/b/\x80");
863 t!(v: Path::new(b"/\xFF/foo").with_filename(b"\xCD"),
865 t!(s: Path::new("a/b/c").with_filename("d"), "a/b/d");
866 t!(s: Path::new(".").with_filename("foo"), "foo");
867 t!(s: Path::new("/a/b/c").with_filename("d"), "/a/b/d");
868 t!(s: Path::new("/").with_filename("foo"), "/foo");
869 t!(s: Path::new("/a").with_filename("foo"), "/foo");
870 t!(s: Path::new("foo").with_filename("bar"), "bar");
871 t!(s: Path::new("/").with_filename("foo/"), "/foo");
872 t!(s: Path::new("/a").with_filename("foo/"), "/foo");
873 t!(s: Path::new("a/b/c").with_filename(""), "a/b");
874 t!(s: Path::new("a/b/c").with_filename("."), "a/b");
875 t!(s: Path::new("a/b/c").with_filename(".."), "a");
876 t!(s: Path::new("/a").with_filename(""), "/");
877 t!(s: Path::new("foo").with_filename(""), ".");
878 t!(s: Path::new("a/b/c").with_filename("d/e"), "a/b/d/e");
879 t!(s: Path::new("a/b/c").with_filename("/d"), "a/b/d");
880 t!(s: Path::new("..").with_filename("foo"), "../foo");
881 t!(s: Path::new("../..").with_filename("foo"), "../../foo");
882 t!(s: Path::new("..").with_filename(""), "..");
883 t!(s: Path::new("../..").with_filename(""), "../..");
885 t!(v: Path::new(b"hi/there\x80.txt").with_extension(b"exe"),
886 b"hi/there\x80.exe");
887 t!(v: Path::new(b"hi/there.txt\x80").with_extension(b"\xFF"),
889 t!(v: Path::new(b"hi/there\x80").with_extension(b"\xFF"),
890 b"hi/there\x80.\xFF");
891 t!(v: Path::new(b"hi/there.\xFF").with_extension(empty), b"hi/there");
892 t!(s: Path::new("hi/there.txt").with_extension("exe"), "hi/there.exe");
893 t!(s: Path::new("hi/there.txt").with_extension(""), "hi/there");
894 t!(s: Path::new("hi/there.txt").with_extension("."), "hi/there..");
895 t!(s: Path::new("hi/there.txt").with_extension(".."), "hi/there...");
896 t!(s: Path::new("hi/there").with_extension("txt"), "hi/there.txt");
897 t!(s: Path::new("hi/there").with_extension("."), "hi/there..");
898 t!(s: Path::new("hi/there").with_extension(".."), "hi/there...");
899 t!(s: Path::new("hi/there.").with_extension("txt"), "hi/there.txt");
900 t!(s: Path::new("hi/.foo").with_extension("txt"), "hi/.foo.txt");
901 t!(s: Path::new("hi/there.txt").with_extension(".foo"), "hi/there..foo");
902 t!(s: Path::new("/").with_extension("txt"), "/");
903 t!(s: Path::new("/").with_extension("."), "/");
904 t!(s: Path::new("/").with_extension(".."), "/");
905 t!(s: Path::new(".").with_extension("txt"), ".");
911 (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
915 let mut p1 = Path::new(path);
917 let p2 = Path::new(path);
918 assert!(p1 == p2.$with(arg));
921 (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
925 let mut p1 = Path::new(path);
927 let p2 = Path::new(path);
928 assert!(p1 == p2.$with(arg));
933 t!(v: b"a/b/c", set_filename, with_filename, b"d");
934 t!(v: b"/", set_filename, with_filename, b"foo");
935 t!(v: b"\x80", set_filename, with_filename, b"\xFF");
936 t!(s: "a/b/c", set_filename, with_filename, "d");
937 t!(s: "/", set_filename, with_filename, "foo");
938 t!(s: ".", set_filename, with_filename, "foo");
939 t!(s: "a/b", set_filename, with_filename, "");
940 t!(s: "a", set_filename, with_filename, "");
942 t!(v: b"hi/there.txt", set_extension, with_extension, b"exe");
943 t!(v: b"hi/there.t\x80xt", set_extension, with_extension, b"exe\xFF");
944 t!(s: "hi/there.txt", set_extension, with_extension, "exe");
945 t!(s: "hi/there.", set_extension, with_extension, "txt");
946 t!(s: "hi/there", set_extension, with_extension, "txt");
947 t!(s: "hi/there.txt", set_extension, with_extension, "");
948 t!(s: "hi/there", set_extension, with_extension, "");
949 t!(s: ".", set_extension, with_extension, "txt");
955 (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
958 let filename = $filename;
959 assert!(path.filename_str() == filename,
960 "{}.filename_str(): Expected `{}`, found {}",
961 path.as_str().unwrap(), filename, path.filename_str());
962 let dirname = $dirname;
963 assert!(path.dirname_str() == dirname,
964 "`{}`.dirname_str(): Expected `{}`, found `{}`",
965 path.as_str().unwrap(), dirname, path.dirname_str());
966 let filestem = $filestem;
967 assert!(path.filestem_str() == filestem,
968 "`{}`.filestem_str(): Expected `{}`, found `{}`",
969 path.as_str().unwrap(), filestem, path.filestem_str());
971 assert!(path.extension_str() == ext,
972 "`{}`.extension_str(): Expected `{}`, found `{}`",
973 path.as_str().unwrap(), ext, path.extension_str());
976 (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
979 assert!(path.filename() == $filename);
980 assert!(path.dirname() == $dirname);
981 assert!(path.filestem() == $filestem);
982 assert!(path.extension() == $ext);
987 t!(v: Path::new(b"a/b/c"), Some(b"c"), b"a/b", Some(b"c"), None);
988 t!(v: Path::new(b"a/b/\xFF"), Some(b"\xFF"), b"a/b", Some(b"\xFF"), None);
989 t!(v: Path::new(b"hi/there.\xFF"), Some(b"there.\xFF"), b"hi",
990 Some(b"there"), Some(b"\xFF"));
991 t!(s: Path::new("a/b/c"), Some("c"), Some("a/b"), Some("c"), None);
992 t!(s: Path::new("."), None, Some("."), None, None);
993 t!(s: Path::new("/"), None, Some("/"), None, None);
994 t!(s: Path::new(".."), None, Some(".."), None, None);
995 t!(s: Path::new("../.."), None, Some("../.."), None, None);
996 t!(s: Path::new("hi/there.txt"), Some("there.txt"), Some("hi"),
997 Some("there"), Some("txt"));
998 t!(s: Path::new("hi/there"), Some("there"), Some("hi"), Some("there"), None);
999 t!(s: Path::new("hi/there."), Some("there."), Some("hi"),
1000 Some("there"), Some(""));
1001 t!(s: Path::new("hi/.there"), Some(".there"), Some("hi"), Some(".there"), None);
1002 t!(s: Path::new("hi/..there"), Some("..there"), Some("hi"),
1003 Some("."), Some("there"));
1004 t!(s: Path::new(b"a/b/\xFF"), None, Some("a/b"), None, None);
1005 t!(s: Path::new(b"a/b/\xFF.txt"), None, Some("a/b"), None, Some("txt"));
1006 t!(s: Path::new(b"a/b/c.\x80"), None, Some("a/b"), Some("c"), None);
1007 t!(s: Path::new(b"\xFF/b"), Some("b"), None, Some("b"), None);
1011 fn test_dir_path() {
1012 t!(v: Path::new(b"hi/there\x80").dir_path(), b"hi");
1013 t!(v: Path::new(b"hi\xFF/there").dir_path(), b"hi\xFF");
1014 t!(s: Path::new("hi/there").dir_path(), "hi");
1015 t!(s: Path::new("hi").dir_path(), ".");
1016 t!(s: Path::new("/hi").dir_path(), "/");
1017 t!(s: Path::new("/").dir_path(), "/");
1018 t!(s: Path::new("..").dir_path(), "..");
1019 t!(s: Path::new("../..").dir_path(), "../..");
1023 fn test_is_absolute() {
1025 (s: $path:expr, $abs:expr, $rel:expr) => (
1027 let path = Path::new($path);
1028 assert_eq!(path.is_absolute(), $abs);
1029 assert_eq!(path.is_relative(), $rel);
1033 t!(s: "a/b/c", false, true);
1034 t!(s: "/a/b/c", true, false);
1035 t!(s: "a", false, true);
1036 t!(s: "/a", true, false);
1037 t!(s: ".", false, true);
1038 t!(s: "/", true, false);
1039 t!(s: "..", false, true);
1040 t!(s: "../..", false, true);
1044 fn test_is_ancestor_of() {
1046 (s: $path:expr, $dest:expr, $exp:expr) => (
1048 let path = Path::new($path);
1049 let dest = Path::new($dest);
1050 assert_eq!(path.is_ancestor_of(&dest), $exp);
1055 t!(s: "a/b/c", "a/b/c/d", true);
1056 t!(s: "a/b/c", "a/b/c", true);
1057 t!(s: "a/b/c", "a/b", false);
1058 t!(s: "/a/b/c", "/a/b/c", true);
1059 t!(s: "/a/b", "/a/b/c", true);
1060 t!(s: "/a/b/c/d", "/a/b/c", false);
1061 t!(s: "/a/b", "a/b/c", false);
1062 t!(s: "a/b", "/a/b/c", false);
1063 t!(s: "a/b/c", "a/b/d", false);
1064 t!(s: "../a/b/c", "a/b/c", false);
1065 t!(s: "a/b/c", "../a/b/c", false);
1066 t!(s: "a/b/c", "a/b/cd", false);
1067 t!(s: "a/b/cd", "a/b/c", false);
1068 t!(s: "../a/b", "../a/b/c", true);
1069 t!(s: ".", "a/b", true);
1070 t!(s: ".", ".", true);
1071 t!(s: "/", "/", true);
1072 t!(s: "/", "/a/b", true);
1073 t!(s: "..", "a/b", true);
1074 t!(s: "../..", "a/b", true);
1078 fn test_ends_with_path() {
1080 (s: $path:expr, $child:expr, $exp:expr) => (
1082 let path = Path::new($path);
1083 let child = Path::new($child);
1084 assert_eq!(path.ends_with_path(&child), $exp);
1087 (v: $path:expr, $child:expr, $exp:expr) => (
1089 let path = Path::new($path);
1090 let child = Path::new($child);
1091 assert_eq!(path.ends_with_path(&child), $exp);
1096 t!(s: "a/b/c", "c", true);
1097 t!(s: "a/b/c", "d", false);
1098 t!(s: "foo/bar/quux", "bar", false);
1099 t!(s: "foo/bar/quux", "barquux", false);
1100 t!(s: "a/b/c", "b/c", true);
1101 t!(s: "a/b/c", "a/b/c", true);
1102 t!(s: "a/b/c", "foo/a/b/c", false);
1103 t!(s: "/a/b/c", "a/b/c", true);
1104 t!(s: "/a/b/c", "/a/b/c", false); // child must be relative
1105 t!(s: "/a/b/c", "foo/a/b/c", false);
1106 t!(s: "a/b/c", "", false);
1107 t!(s: "", "", true);
1108 t!(s: "/a/b/c", "d/e/f", false);
1109 t!(s: "a/b/c", "a/b", false);
1110 t!(s: "a/b/c", "b", false);
1111 t!(v: b"a/b/c", b"b/c", true);
1112 t!(v: b"a/b/\xFF", b"\xFF", true);
1113 t!(v: b"a/b/\xFF", b"b/\xFF", true);
1117 fn test_path_relative_from() {
1119 (s: $path:expr, $other:expr, $exp:expr) => (
1121 let path = Path::new($path);
1122 let other = Path::new($other);
1123 let res = path.path_relative_from(&other);
1124 assert_eq!(res.as_ref().and_then(|x| x.as_str()), $exp);
1129 t!(s: "a/b/c", "a/b", Some("c"));
1130 t!(s: "a/b/c", "a/b/d", Some("../c"));
1131 t!(s: "a/b/c", "a/b/c/d", Some(".."));
1132 t!(s: "a/b/c", "a/b/c", Some("."));
1133 t!(s: "a/b/c", "a/b/c/d/e", Some("../.."));
1134 t!(s: "a/b/c", "a/d/e", Some("../../b/c"));
1135 t!(s: "a/b/c", "d/e/f", Some("../../../a/b/c"));
1136 t!(s: "a/b/c", "/a/b/c", None);
1137 t!(s: "/a/b/c", "a/b/c", Some("/a/b/c"));
1138 t!(s: "/a/b/c", "/a/b/c/d", Some(".."));
1139 t!(s: "/a/b/c", "/a/b", Some("c"));
1140 t!(s: "/a/b/c", "/a/b/c/d/e", Some("../.."));
1141 t!(s: "/a/b/c", "/a/d/e", Some("../../b/c"));
1142 t!(s: "/a/b/c", "/d/e/f", Some("../../../a/b/c"));
1143 t!(s: "hi/there.txt", "hi/there", Some("../there.txt"));
1144 t!(s: ".", "a", Some(".."));
1145 t!(s: ".", "a/b", Some("../.."));
1146 t!(s: ".", ".", Some("."));
1147 t!(s: "a", ".", Some("a"));
1148 t!(s: "a/b", ".", Some("a/b"));
1149 t!(s: "..", ".", Some(".."));
1150 t!(s: "a/b/c", "a/b/c", Some("."));
1151 t!(s: "/a/b/c", "/a/b/c", Some("."));
1152 t!(s: "/", "/", Some("."));
1153 t!(s: "/", ".", Some("/"));
1154 t!(s: "../../a", "b", Some("../../../a"));
1155 t!(s: "a", "../../b", None);
1156 t!(s: "../../a", "../../b", Some("../a"));
1157 t!(s: "../../a", "../../a/b", Some(".."));
1158 t!(s: "../../a/b", "../../a", Some("b"));
1162 fn test_components_iter() {
1164 (s: $path:expr, $exp:expr) => (
1166 let path = Path::new($path);
1167 let comps = path.components().collect::<Vec<&[u8]>>();
1168 let exp: &[&str] = &$exp;
1169 let exps = exp.iter().map(|x| x.as_bytes()).collect::<Vec<&[u8]>>();
1170 assert!(comps == exps, "components: Expected {}, found {}",
1172 let comps = path.components().rev().collect::<Vec<&[u8]>>();
1173 let exps = exps.into_iter().rev().collect::<Vec<&[u8]>>();
1174 assert!(comps == exps, "rev_components: Expected {}, found {}",
1178 (b: $arg:expr, [$($exp:expr),*]) => (
1180 let path = Path::new($arg);
1181 let comps = path.components().collect::<Vec<&[u8]>>();
1182 let exp: &[&[u8]] = &[$($exp),*];
1183 assert_eq!(comps.as_slice(), exp);
1184 let comps = path.components().rev().collect::<Vec<&[u8]>>();
1185 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
1186 assert_eq!(comps, exp)
1191 t!(b: b"a/b/c", [b"a", b"b", b"c"]);
1192 t!(b: b"/\xFF/a/\x80", [b"\xFF", b"a", b"\x80"]);
1193 t!(b: b"../../foo\xCDbar", [b"..", b"..", b"foo\xCDbar"]);
1194 t!(s: "a/b/c", ["a", "b", "c"]);
1195 t!(s: "a/b/d", ["a", "b", "d"]);
1196 t!(s: "a/b/cd", ["a", "b", "cd"]);
1197 t!(s: "/a/b/c", ["a", "b", "c"]);
1202 t!(s: "..", [".."]);
1203 t!(s: "../..", ["..", ".."]);
1204 t!(s: "../../foo", ["..", "..", "foo"]);
1208 fn test_str_components() {
1210 (b: $arg:expr, $exp:expr) => (
1212 let path = Path::new($arg);
1213 let comps = path.str_components().collect::<Vec<Option<&str>>>();
1214 let exp: &[Option<&str>] = &$exp;
1215 assert_eq!(comps.as_slice(), exp);
1216 let comps = path.str_components().rev().collect::<Vec<Option<&str>>>();
1217 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<Option<&str>>>();
1218 assert_eq!(comps, exp);
1223 t!(b: b"a/b/c", [Some("a"), Some("b"), Some("c")]);
1224 t!(b: b"/\xFF/a/\x80", [None, Some("a"), None]);
1225 t!(b: b"../../foo\xCDbar", [Some(".."), Some(".."), None]);
1226 // str_components is a wrapper around components, so no need to do
1227 // the full set of tests
1234 use self::test::Bencher;
1239 fn join_home_dir(b: &mut Bencher) {
1240 let posix_path = Path::new("/");
1242 posix_path.join("home");
1247 fn join_abs_path_home_dir(b: &mut Bencher) {
1248 let posix_path = Path::new("/");
1250 posix_path.join("/home");
1255 fn join_many_home_dir(b: &mut Bencher) {
1256 let posix_path = Path::new("/");
1258 posix_path.join_many(&["home"]);
1263 fn join_many_abs_path_home_dir(b: &mut Bencher) {
1264 let posix_path = Path::new("/");
1266 posix_path.join_many(&["/home"]);
1271 fn push_home_dir(b: &mut Bencher) {
1272 let mut posix_path = Path::new("/");
1274 posix_path.push("home");
1279 fn push_abs_path_home_dir(b: &mut Bencher) {
1280 let mut posix_path = Path::new("/");
1282 posix_path.push("/home");
1287 fn push_many_home_dir(b: &mut Bencher) {
1288 let mut posix_path = Path::new("/");
1290 posix_path.push_many(&["home"]);
1295 fn push_many_abs_path_home_dir(b: &mut Bencher) {
1296 let mut posix_path = Path::new("/");
1298 posix_path.push_many(&["/home"]);
1303 fn ends_with_path_home_dir(b: &mut Bencher) {
1304 let posix_home_path = Path::new("/home");
1306 posix_home_path.ends_with_path(&Path::new("home"));
1311 fn ends_with_path_missmatch_jome_home(b: &mut Bencher) {
1312 let posix_home_path = Path::new("/home");
1314 posix_home_path.ends_with_path(&Path::new("jome"));
1319 fn is_ancestor_of_path_with_10_dirs(b: &mut Bencher) {
1320 let path = Path::new("/home/1/2/3/4/5/6/7/8/9");
1321 let mut sub = path.clone();
1324 path.is_ancestor_of(&sub);
1329 fn path_relative_from_forward(b: &mut Bencher) {
1330 let path = Path::new("/a/b/c");
1331 let mut other = path.clone();
1334 path.path_relative_from(&other);
1339 fn path_relative_from_same_level(b: &mut Bencher) {
1340 let path = Path::new("/a/b/c");
1341 let mut other = path.clone();
1345 path.path_relative_from(&other);
1350 fn path_relative_from_backward(b: &mut Bencher) {
1351 let path = Path::new("/a/b");
1352 let mut other = path.clone();
1355 path.path_relative_from(&other);