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};
16 use from_str::FromStr;
19 use iter::{DoubleEndedIterator, AdditiveIterator, Extend, Iterator, Map};
20 use option::{Option, None, Some};
23 use slice::{CloneSliceAllocPrelude, Splits, AsSlice, VectorVector,
24 PartialEqSlicePrelude, SlicePrelude};
27 use super::{BytesContainer, GenericPath, GenericPathUnsafe};
29 /// Iterator that yields successive components of a Path as &[u8]
30 pub type Components<'a> = Splits<'a, u8>;
32 /// Iterator that yields successive components of a Path as Option<&str>
33 pub type StrComponents<'a> = Map<'a, &'a [u8], Option<&'a str>,
36 /// Represents a POSIX file path
39 repr: Vec<u8>, // assumed to never be empty or contain NULs
40 sepidx: Option<uint> // index of the final separator in repr
43 /// The standard path separator character
44 pub const SEP: char = '/';
46 /// The standard path separator byte
47 pub const SEP_BYTE: u8 = SEP as u8;
49 /// Returns whether the given byte is a path separator
51 pub fn is_sep_byte(u: &u8) -> bool {
55 /// Returns whether the given char is a path separator
57 pub fn is_sep(c: char) -> bool {
61 impl PartialEq for Path {
63 fn eq(&self, other: &Path) -> bool {
64 self.repr == other.repr
70 impl PartialOrd for Path {
71 fn partial_cmp(&self, other: &Path) -> Option<Ordering> {
77 fn cmp(&self, other: &Path) -> Ordering {
78 self.repr.cmp(&other.repr)
82 impl FromStr for Path {
83 fn from_str(s: &str) -> Option<Path> {
88 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
89 // we cannot usefully take ToCStr arguments by reference (without forcing an
90 // additional & around &str). So we are instead temporarily adding an instance
91 // for &Path, so that we can take ToCStr as owned. When DST lands, the &Path
92 // instance should be removed, and arguments bound by ToCStr should be passed by
95 impl ToCStr for Path {
97 fn to_c_str(&self) -> CString {
98 // The Path impl guarantees no internal NUL
99 unsafe { self.to_c_str_unchecked() }
103 unsafe fn to_c_str_unchecked(&self) -> CString {
104 self.as_vec().to_c_str_unchecked()
108 impl<S: hash::Writer> hash::Hash<S> for Path {
110 fn hash(&self, state: &mut S) {
111 self.repr.hash(state)
115 impl BytesContainer for Path {
117 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
122 impl GenericPathUnsafe for Path {
123 unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
124 let path = Path::normalize(path.container_as_bytes());
125 assert!(!path.is_empty());
126 let idx = path.as_slice().rposition_elem(&SEP_BYTE);
127 Path{ repr: path, sepidx: idx }
130 unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
131 let filename = filename.container_as_bytes();
133 None if b".." == self.repr.as_slice() => {
134 let mut v = Vec::with_capacity(3 + filename.len());
135 v.push_all(dot_dot_static);
137 v.push_all(filename);
138 // FIXME: this is slow
139 self.repr = Path::normalize(v.as_slice());
142 self.repr = Path::normalize(filename);
144 Some(idx) if self.repr[idx+1..] == b".." => {
145 let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
146 v.push_all(self.repr.as_slice());
148 v.push_all(filename);
149 // FIXME: this is slow
150 self.repr = Path::normalize(v.as_slice());
153 let mut v = Vec::with_capacity(idx + 1 + filename.len());
154 v.push_all(self.repr[..idx+1]);
155 v.push_all(filename);
156 // FIXME: this is slow
157 self.repr = Path::normalize(v.as_slice());
160 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
163 unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
164 let path = path.container_as_bytes();
165 if !path.is_empty() {
166 if path[0] == SEP_BYTE {
167 self.repr = Path::normalize(path);
169 let mut v = Vec::with_capacity(self.repr.len() + path.len() + 1);
170 v.push_all(self.repr.as_slice());
173 // FIXME: this is slow
174 self.repr = Path::normalize(v.as_slice());
176 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
181 impl GenericPath for Path {
183 fn as_vec<'a>(&'a self) -> &'a [u8] {
187 fn into_vec(self) -> Vec<u8> {
191 fn dirname<'a>(&'a self) -> &'a [u8] {
193 None if b".." == self.repr.as_slice() => self.repr.as_slice(),
195 Some(0) => self.repr[..1],
196 Some(idx) if self.repr[idx+1..] == b".." => self.repr.as_slice(),
197 Some(idx) => self.repr[..idx]
201 fn filename<'a>(&'a self) -> Option<&'a [u8]> {
203 None if b"." == self.repr.as_slice() ||
204 b".." == self.repr.as_slice() => None,
205 None => Some(self.repr.as_slice()),
206 Some(idx) if self.repr[idx+1..] == b".." => None,
207 Some(0) if self.repr[1..].is_empty() => None,
208 Some(idx) => Some(self.repr[idx+1..])
212 fn pop(&mut self) -> bool {
214 None if b"." == self.repr.as_slice() => false,
216 self.repr = vec![b'.'];
220 Some(0) if b"/" == self.repr.as_slice() => false,
223 self.repr.truncate(idx+1);
225 self.repr.truncate(idx);
227 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
233 fn root_path(&self) -> Option<Path> {
234 if self.is_absolute() {
242 fn is_absolute(&self) -> bool {
243 self.repr[0] == SEP_BYTE
246 fn is_ancestor_of(&self, other: &Path) -> bool {
247 if self.is_absolute() != other.is_absolute() {
250 let mut ita = self.components();
251 let mut itb = other.components();
252 if b"." == self.repr.as_slice() {
253 return match itb.next() {
255 Some(b) => b != b".."
259 match (ita.next(), itb.next()) {
261 (Some(a), Some(b)) if a == b => { continue },
262 (Some(a), _) if a == b".." => {
263 // if ita contains only .. components, it's an ancestor
264 return ita.all(|x| x == b"..");
273 fn path_relative_from(&self, base: &Path) -> Option<Path> {
274 if self.is_absolute() != base.is_absolute() {
275 if self.is_absolute() {
281 let mut ita = self.components();
282 let mut itb = base.components();
283 let mut comps = vec![];
285 match (ita.next(), itb.next()) {
286 (None, None) => break,
289 comps.extend(ita.by_ref());
292 (None, _) => comps.push(dot_dot_static),
293 (Some(a), Some(b)) if comps.is_empty() && a == b => (),
294 (Some(a), Some(b)) if b == b"." => comps.push(a),
295 (Some(_), Some(b)) if b == b".." => return None,
296 (Some(a), Some(_)) => {
297 comps.push(dot_dot_static);
299 comps.push(dot_dot_static);
302 comps.extend(ita.by_ref());
307 Some(Path::new(comps.as_slice().connect_vec(&SEP_BYTE)))
311 fn ends_with_path(&self, child: &Path) -> bool {
312 if !child.is_relative() { return false; }
313 let mut selfit = self.components().rev();
314 let mut childit = child.components().rev();
316 match (selfit.next(), childit.next()) {
317 (Some(a), Some(b)) => if a != b { return false; },
318 (Some(_), None) => break,
319 (None, Some(_)) => return false,
320 (None, None) => break
328 /// Returns a new Path from a byte vector or string
332 /// Fails the task if the vector contains a NUL.
334 pub fn new<T: BytesContainer>(path: T) -> Path {
335 GenericPath::new(path)
338 /// Returns a new Path from a byte vector or string, if possible
340 pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
341 GenericPath::new_opt(path)
344 /// Returns a normalized byte vector representation of a path, by removing all empty
345 /// components, and unnecessary . and .. components.
346 fn normalize<V: AsSlice<u8>>(v: V) -> Vec<u8> {
347 // borrowck is being very picky
349 let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE;
350 let v_ = if is_abs { v.as_slice()[1..] } else { v.as_slice() };
351 let comps = normalize_helper(v_, is_abs);
355 if is_abs && comps.is_empty() {
358 let n = if is_abs { comps.len() } else { comps.len() - 1} +
359 comps.iter().map(|v| v.len()).sum();
360 let mut v = Vec::with_capacity(n);
361 let mut it = comps.into_iter();
365 Some(comp) => v.push_all(comp)
378 None => v.as_slice().to_vec(),
383 /// Returns an iterator that yields each component of the path in turn.
384 /// Does not distinguish between absolute and relative paths, e.g.
385 /// /a/b/c and a/b/c yield the same set of components.
386 /// A path of "/" yields no components. A path of "." yields one component.
387 pub fn components<'a>(&'a self) -> Components<'a> {
388 let v = if self.repr[0] == SEP_BYTE {
390 } else { self.repr.as_slice() };
391 let mut ret = v.split(is_sep_byte);
393 // consume the empty "" component
399 /// Returns an iterator that yields each component of the path as Option<&str>.
400 /// See components() for details.
401 pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
402 self.components().map(str::from_utf8)
406 // None result means the byte vector didn't need normalizing
407 fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<Vec<&'a [u8]>> {
408 if is_abs && v.as_slice().is_empty() {
411 let mut comps: Vec<&'a [u8]> = vec![];
413 let mut changed = false;
414 for comp in v.split(is_sep_byte) {
415 if comp.is_empty() { changed = true }
416 else if comp == b"." { changed = true }
417 else if comp == b".." {
418 if is_abs && comps.is_empty() { changed = true }
419 else if comps.len() == n_up { comps.push(dot_dot_static); n_up += 1 }
420 else { comps.pop().unwrap(); changed = true }
421 } else { comps.push(comp) }
424 if comps.is_empty() && !is_abs {
428 comps.push(dot_static);
436 #[allow(non_upper_case_globals)]
437 static dot_static: &'static [u8] = b".";
438 #[allow(non_upper_case_globals)]
439 static dot_dot_static: &'static [u8] = b"..";
450 (s: $path:expr, $exp:expr) => (
453 assert!(path.as_str() == Some($exp));
456 (v: $path:expr, $exp:expr) => (
459 assert!(path.as_vec() == $exp);
466 let empty: &[u8] = [];
467 t!(v: Path::new(empty), b".");
468 t!(v: Path::new(b"/"), b"/");
469 t!(v: Path::new(b"a/b/c"), b"a/b/c");
470 t!(v: Path::new(b"a/b/c\xFF"), b"a/b/c\xFF");
471 t!(v: Path::new(b"\xFF/../foo\x80"), b"foo\x80");
472 let p = Path::new(b"a/b/c\xFF");
473 assert!(p.as_str() == None);
475 t!(s: Path::new(""), ".");
476 t!(s: Path::new("/"), "/");
477 t!(s: Path::new("hi"), "hi");
478 t!(s: Path::new("hi/"), "hi");
479 t!(s: Path::new("/lib"), "/lib");
480 t!(s: Path::new("/lib/"), "/lib");
481 t!(s: Path::new("hi/there"), "hi/there");
482 t!(s: Path::new("hi/there.txt"), "hi/there.txt");
484 t!(s: Path::new("hi/there/"), "hi/there");
485 t!(s: Path::new("hi/../there"), "there");
486 t!(s: Path::new("../hi/there"), "../hi/there");
487 t!(s: Path::new("/../hi/there"), "/hi/there");
488 t!(s: Path::new("foo/.."), ".");
489 t!(s: Path::new("/foo/.."), "/");
490 t!(s: Path::new("/foo/../.."), "/");
491 t!(s: Path::new("/foo/../../bar"), "/bar");
492 t!(s: Path::new("/./hi/./there/."), "/hi/there");
493 t!(s: Path::new("/./hi/./there/./.."), "/hi");
494 t!(s: Path::new("foo/../.."), "..");
495 t!(s: Path::new("foo/../../.."), "../..");
496 t!(s: Path::new("foo/../../bar"), "../bar");
498 assert_eq!(Path::new(b"foo/bar").into_vec().as_slice(), b"foo/bar");
499 assert_eq!(Path::new(b"/foo/../../bar").into_vec().as_slice(),
502 let p = Path::new(b"foo/bar\x80");
503 assert!(p.as_str() == None);
507 fn test_opt_paths() {
508 assert!(Path::new_opt(b"foo/bar\0") == None);
509 t!(v: Path::new_opt(b"foo/bar").unwrap(), b"foo/bar");
510 assert!(Path::new_opt("foo/bar\0") == None);
511 t!(s: Path::new_opt("foo/bar").unwrap(), "foo/bar");
515 fn test_null_byte() {
517 let result = task::try(proc() {
518 Path::new(b"foo/bar\0")
520 assert!(result.is_err());
522 let result = task::try(proc() {
523 Path::new("test").set_filename(b"f\0o")
525 assert!(result.is_err());
527 let result = task::try(proc() {
528 Path::new("test").push(b"f\0o");
530 assert!(result.is_err());
534 fn test_display_str() {
536 ($path:expr, $disp:ident, $exp:expr) => (
538 let path = Path::new($path);
539 assert!(path.$disp().to_string().as_slice() == $exp);
543 t!("foo", display, "foo");
544 t!(b"foo\x80", display, "foo\uFFFD");
545 t!(b"foo\xFFbar", display, "foo\uFFFDbar");
546 t!(b"foo\xFF/bar", filename_display, "bar");
547 t!(b"foo/\xFFbar", filename_display, "\uFFFDbar");
548 t!(b"/", filename_display, "");
551 ($path:expr, $exp:expr) => (
553 let path = Path::new($path);
554 let mo = path.display().as_maybe_owned();
555 assert!(mo.as_slice() == $exp);
558 ($path:expr, $exp:expr, filename) => (
560 let path = Path::new($path);
561 let mo = path.filename_display().as_maybe_owned();
562 assert!(mo.as_slice() == $exp);
568 t!(b"foo\x80", "foo\uFFFD");
569 t!(b"foo\xFFbar", "foo\uFFFDbar");
570 t!(b"foo\xFF/bar", "bar", filename);
571 t!(b"foo/\xFFbar", "\uFFFDbar", filename);
572 t!(b"/", "", filename);
578 ($path:expr, $exp:expr, $expf:expr) => (
580 let path = Path::new($path);
581 let f = format!("{}", path.display());
582 assert!(f.as_slice() == $exp);
583 let f = format!("{}", path.filename_display());
584 assert!(f.as_slice() == $expf);
589 t!(b"foo", "foo", "foo");
590 t!(b"foo/bar", "foo/bar", "bar");
592 t!(b"foo\xFF", "foo\uFFFD", "foo\uFFFD");
593 t!(b"foo\xFF/bar", "foo\uFFFD/bar", "bar");
594 t!(b"foo/\xFFbar", "foo/\uFFFDbar", "\uFFFDbar");
595 t!(b"\xFFfoo/bar\xFF", "\uFFFDfoo/bar\uFFFD", "bar\uFFFD");
599 fn test_components() {
601 (s: $path:expr, $op:ident, $exp:expr) => (
604 let path = Path::new($path);
605 assert!(path.$op() == mem::transmute(($exp).as_bytes()));
609 (s: $path:expr, $op:ident, $exp:expr, opt) => (
611 let path = Path::new($path);
612 let left = path.$op().map(|x| str::from_utf8(x).unwrap());
613 assert!(left == $exp);
616 (v: $path:expr, $op:ident, $exp:expr) => (
620 let path = Path::new(arg);
621 assert!(path.$op() == mem::transmute($exp));
627 t!(v: b"a/b/c", filename, Some(b"c"));
628 t!(v: b"a/b/c\xFF", filename, Some(b"c\xFF"));
629 t!(v: b"a/b\xFF/c", filename, Some(b"c"));
630 t!(s: "a/b/c", filename, Some("c"), opt);
631 t!(s: "/a/b/c", filename, Some("c"), opt);
632 t!(s: "a", filename, Some("a"), opt);
633 t!(s: "/a", filename, Some("a"), opt);
634 t!(s: ".", filename, None, opt);
635 t!(s: "/", filename, None, opt);
636 t!(s: "..", filename, None, opt);
637 t!(s: "../..", filename, None, opt);
639 t!(v: b"a/b/c", dirname, b"a/b");
640 t!(v: b"a/b/c\xFF", dirname, b"a/b");
641 t!(v: b"a/b\xFF/c", dirname, b"a/b\xFF");
642 t!(s: "a/b/c", dirname, "a/b");
643 t!(s: "/a/b/c", dirname, "/a/b");
644 t!(s: "a", dirname, ".");
645 t!(s: "/a", dirname, "/");
646 t!(s: ".", dirname, ".");
647 t!(s: "/", dirname, "/");
648 t!(s: "..", dirname, "..");
649 t!(s: "../..", dirname, "../..");
651 t!(v: b"hi/there.txt", filestem, Some(b"there"));
652 t!(v: b"hi/there\x80.txt", filestem, Some(b"there\x80"));
653 t!(v: b"hi/there.t\x80xt", filestem, Some(b"there"));
654 t!(s: "hi/there.txt", filestem, Some("there"), opt);
655 t!(s: "hi/there", filestem, Some("there"), opt);
656 t!(s: "there.txt", filestem, Some("there"), opt);
657 t!(s: "there", filestem, Some("there"), opt);
658 t!(s: ".", filestem, None, opt);
659 t!(s: "/", filestem, None, opt);
660 t!(s: "foo/.bar", filestem, Some(".bar"), opt);
661 t!(s: ".bar", filestem, Some(".bar"), opt);
662 t!(s: "..bar", filestem, Some("."), opt);
663 t!(s: "hi/there..txt", filestem, Some("there."), opt);
664 t!(s: "..", filestem, None, opt);
665 t!(s: "../..", filestem, None, opt);
667 t!(v: b"hi/there.txt", extension, Some(b"txt"));
668 t!(v: b"hi/there\x80.txt", extension, Some(b"txt"));
669 t!(v: b"hi/there.t\x80xt", extension, Some(b"t\x80xt"));
670 let no: Option<&'static [u8]> = None;
671 t!(v: b"hi/there", extension, no);
672 t!(v: b"hi/there\x80", extension, no);
673 t!(s: "hi/there.txt", extension, Some("txt"), opt);
674 t!(s: "hi/there", extension, None, opt);
675 t!(s: "there.txt", extension, Some("txt"), opt);
676 t!(s: "there", extension, None, opt);
677 t!(s: ".", extension, None, opt);
678 t!(s: "/", extension, None, opt);
679 t!(s: "foo/.bar", extension, None, opt);
680 t!(s: ".bar", extension, None, opt);
681 t!(s: "..bar", extension, Some("bar"), opt);
682 t!(s: "hi/there..txt", extension, Some("txt"), opt);
683 t!(s: "..", extension, None, opt);
684 t!(s: "../..", extension, None, opt);
690 (s: $path:expr, $join:expr) => (
694 let mut p1 = Path::new(path);
697 assert!(p1 == p2.join(join));
702 t!(s: "a/b/c", "..");
703 t!(s: "/a/b/c", "d");
705 t!(s: "a/b", "/c/d");
709 fn test_push_path() {
711 (s: $path:expr, $push:expr, $exp:expr) => (
713 let mut p = Path::new($path);
714 let push = Path::new($push);
716 assert!(p.as_str() == Some($exp));
721 t!(s: "a/b/c", "d", "a/b/c/d");
722 t!(s: "/a/b/c", "d", "/a/b/c/d");
723 t!(s: "a/b", "c/d", "a/b/c/d");
724 t!(s: "a/b", "/c/d", "/c/d");
725 t!(s: "a/b", ".", "a/b");
726 t!(s: "a/b", "../c", "a/c");
730 fn test_push_many() {
732 (s: $path:expr, $push:expr, $exp:expr) => (
734 let mut p = Path::new($path);
736 assert!(p.as_str() == Some($exp));
739 (v: $path:expr, $push:expr, $exp:expr) => (
741 let mut p = Path::new($path);
743 assert!(p.as_vec() == $exp);
748 t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
749 t!(s: "a/b/c", ["d", "/e"], "/e");
750 t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
751 t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
752 t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
753 t!(v: b"a/b/c", [b"d", b"/e", b"f"], b"/e/f");
754 t!(v: b"a/b/c", [b"d".to_vec(), b"e".to_vec()], b"a/b/c/d/e");
760 (s: $path:expr, $left:expr, $right:expr) => (
762 let mut p = Path::new($path);
763 let result = p.pop();
764 assert!(p.as_str() == Some($left));
765 assert!(result == $right);
768 (b: $path:expr, $left:expr, $right:expr) => (
770 let mut p = Path::new($path);
771 let result = p.pop();
772 assert!(p.as_vec() == $left);
773 assert!(result == $right);
778 t!(b: b"a/b/c", b"a/b", true);
779 t!(b: b"a", b".", true);
780 t!(b: b".", b".", false);
781 t!(b: b"/a", b"/", true);
782 t!(b: b"/", b"/", false);
783 t!(b: b"a/b/c\x80", b"a/b", true);
784 t!(b: b"a/b\x80/c", b"a/b\x80", true);
785 t!(b: b"\xFF", b".", true);
786 t!(b: b"/\xFF", b"/", true);
787 t!(s: "a/b/c", "a/b", true);
788 t!(s: "a", ".", true);
789 t!(s: ".", ".", false);
790 t!(s: "/a", "/", true);
791 t!(s: "/", "/", false);
795 fn test_root_path() {
796 assert!(Path::new(b"a/b/c").root_path() == None);
797 assert!(Path::new(b"/a/b/c").root_path() == Some(Path::new("/")));
802 t!(v: Path::new(b"a/b/c").join(b".."), b"a/b");
803 t!(v: Path::new(b"/a/b/c").join(b"d"), b"/a/b/c/d");
804 t!(v: Path::new(b"a/\x80/c").join(b"\xFF"), b"a/\x80/c/\xFF");
805 t!(s: Path::new("a/b/c").join(".."), "a/b");
806 t!(s: Path::new("/a/b/c").join("d"), "/a/b/c/d");
807 t!(s: Path::new("a/b").join("c/d"), "a/b/c/d");
808 t!(s: Path::new("a/b").join("/c/d"), "/c/d");
809 t!(s: Path::new(".").join("a/b"), "a/b");
810 t!(s: Path::new("/").join("a/b"), "/a/b");
814 fn test_join_path() {
816 (s: $path:expr, $join:expr, $exp:expr) => (
818 let path = Path::new($path);
819 let join = Path::new($join);
820 let res = path.join(&join);
821 assert!(res.as_str() == Some($exp));
826 t!(s: "a/b/c", "..", "a/b");
827 t!(s: "/a/b/c", "d", "/a/b/c/d");
828 t!(s: "a/b", "c/d", "a/b/c/d");
829 t!(s: "a/b", "/c/d", "/c/d");
830 t!(s: ".", "a/b", "a/b");
831 t!(s: "/", "a/b", "/a/b");
835 fn test_join_many() {
837 (s: $path:expr, $join:expr, $exp:expr) => (
839 let path = Path::new($path);
840 let res = path.join_many($join);
841 assert!(res.as_str() == Some($exp));
844 (v: $path:expr, $join:expr, $exp:expr) => (
846 let path = Path::new($path);
847 let res = path.join_many($join);
848 assert!(res.as_vec() == $exp);
853 t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
854 t!(s: "a/b/c", ["..", "d"], "a/b/d");
855 t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
856 t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
857 t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
858 t!(v: b"a/b/c", [b"d".to_vec(), b"e".to_vec()], b"a/b/c/d/e");
862 fn test_with_helpers() {
863 let empty: &[u8] = [];
865 t!(v: Path::new(b"a/b/c").with_filename(b"d"), b"a/b/d");
866 t!(v: Path::new(b"a/b/c\xFF").with_filename(b"\x80"), b"a/b/\x80");
867 t!(v: Path::new(b"/\xFF/foo").with_filename(b"\xCD"),
869 t!(s: Path::new("a/b/c").with_filename("d"), "a/b/d");
870 t!(s: Path::new(".").with_filename("foo"), "foo");
871 t!(s: Path::new("/a/b/c").with_filename("d"), "/a/b/d");
872 t!(s: Path::new("/").with_filename("foo"), "/foo");
873 t!(s: Path::new("/a").with_filename("foo"), "/foo");
874 t!(s: Path::new("foo").with_filename("bar"), "bar");
875 t!(s: Path::new("/").with_filename("foo/"), "/foo");
876 t!(s: Path::new("/a").with_filename("foo/"), "/foo");
877 t!(s: Path::new("a/b/c").with_filename(""), "a/b");
878 t!(s: Path::new("a/b/c").with_filename("."), "a/b");
879 t!(s: Path::new("a/b/c").with_filename(".."), "a");
880 t!(s: Path::new("/a").with_filename(""), "/");
881 t!(s: Path::new("foo").with_filename(""), ".");
882 t!(s: Path::new("a/b/c").with_filename("d/e"), "a/b/d/e");
883 t!(s: Path::new("a/b/c").with_filename("/d"), "a/b/d");
884 t!(s: Path::new("..").with_filename("foo"), "../foo");
885 t!(s: Path::new("../..").with_filename("foo"), "../../foo");
886 t!(s: Path::new("..").with_filename(""), "..");
887 t!(s: Path::new("../..").with_filename(""), "../..");
889 t!(v: Path::new(b"hi/there\x80.txt").with_extension(b"exe"),
890 b"hi/there\x80.exe");
891 t!(v: Path::new(b"hi/there.txt\x80").with_extension(b"\xFF"),
893 t!(v: Path::new(b"hi/there\x80").with_extension(b"\xFF"),
894 b"hi/there\x80.\xFF");
895 t!(v: Path::new(b"hi/there.\xFF").with_extension(empty), b"hi/there");
896 t!(s: Path::new("hi/there.txt").with_extension("exe"), "hi/there.exe");
897 t!(s: Path::new("hi/there.txt").with_extension(""), "hi/there");
898 t!(s: Path::new("hi/there.txt").with_extension("."), "hi/there..");
899 t!(s: Path::new("hi/there.txt").with_extension(".."), "hi/there...");
900 t!(s: Path::new("hi/there").with_extension("txt"), "hi/there.txt");
901 t!(s: Path::new("hi/there").with_extension("."), "hi/there..");
902 t!(s: Path::new("hi/there").with_extension(".."), "hi/there...");
903 t!(s: Path::new("hi/there.").with_extension("txt"), "hi/there.txt");
904 t!(s: Path::new("hi/.foo").with_extension("txt"), "hi/.foo.txt");
905 t!(s: Path::new("hi/there.txt").with_extension(".foo"), "hi/there..foo");
906 t!(s: Path::new("/").with_extension("txt"), "/");
907 t!(s: Path::new("/").with_extension("."), "/");
908 t!(s: Path::new("/").with_extension(".."), "/");
909 t!(s: Path::new(".").with_extension("txt"), ".");
915 (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
919 let mut p1 = Path::new(path);
921 let p2 = Path::new(path);
922 assert!(p1 == p2.$with(arg));
925 (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
929 let mut p1 = Path::new(path);
931 let p2 = Path::new(path);
932 assert!(p1 == p2.$with(arg));
937 t!(v: b"a/b/c", set_filename, with_filename, b"d");
938 t!(v: b"/", set_filename, with_filename, b"foo");
939 t!(v: b"\x80", set_filename, with_filename, b"\xFF");
940 t!(s: "a/b/c", set_filename, with_filename, "d");
941 t!(s: "/", set_filename, with_filename, "foo");
942 t!(s: ".", set_filename, with_filename, "foo");
943 t!(s: "a/b", set_filename, with_filename, "");
944 t!(s: "a", set_filename, with_filename, "");
946 t!(v: b"hi/there.txt", set_extension, with_extension, b"exe");
947 t!(v: b"hi/there.t\x80xt", set_extension, with_extension, b"exe\xFF");
948 t!(s: "hi/there.txt", set_extension, with_extension, "exe");
949 t!(s: "hi/there.", set_extension, with_extension, "txt");
950 t!(s: "hi/there", set_extension, with_extension, "txt");
951 t!(s: "hi/there.txt", set_extension, with_extension, "");
952 t!(s: "hi/there", set_extension, with_extension, "");
953 t!(s: ".", set_extension, with_extension, "txt");
959 (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
963 let filename = $filename;
964 assert!(path.filename_str() == filename,
965 "{}.filename_str(): Expected `{}`, found {}",
966 path.as_str().unwrap(), filename, path.filename_str());
967 let dirname = $dirname;
968 assert!(path.dirname_str() == dirname,
969 "`{}`.dirname_str(): Expected `{}`, found `{}`",
970 path.as_str().unwrap(), dirname, path.dirname_str());
971 let filestem = $filestem;
972 assert!(path.filestem_str() == filestem,
973 "`{}`.filestem_str(): Expected `{}`, found `{}`",
974 path.as_str().unwrap(), filestem, path.filestem_str());
976 assert!(path.extension_str() == mem::transmute(ext),
977 "`{}`.extension_str(): Expected `{}`, found `{}`",
978 path.as_str().unwrap(), ext, path.extension_str());
982 (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
986 assert!(path.filename() == mem::transmute($filename));
987 assert!(path.dirname() == mem::transmute($dirname));
988 assert!(path.filestem() == mem::transmute($filestem));
989 assert!(path.extension() == mem::transmute($ext));
995 let no: Option<&'static str> = None;
996 t!(v: Path::new(b"a/b/c"), Some(b"c"), b"a/b", Some(b"c"), no);
997 t!(v: Path::new(b"a/b/\xFF"), Some(b"\xFF"), b"a/b", Some(b"\xFF"), no);
998 t!(v: Path::new(b"hi/there.\xFF"), Some(b"there.\xFF"), b"hi",
999 Some(b"there"), Some(b"\xFF"));
1000 t!(s: Path::new("a/b/c"), Some("c"), Some("a/b"), Some("c"), no);
1001 t!(s: Path::new("."), None, Some("."), None, no);
1002 t!(s: Path::new("/"), None, Some("/"), None, no);
1003 t!(s: Path::new(".."), None, Some(".."), None, no);
1004 t!(s: Path::new("../.."), None, Some("../.."), None, no);
1005 t!(s: Path::new("hi/there.txt"), Some("there.txt"), Some("hi"),
1006 Some("there"), Some("txt"));
1007 t!(s: Path::new("hi/there"), Some("there"), Some("hi"), Some("there"), no);
1008 t!(s: Path::new("hi/there."), Some("there."), Some("hi"),
1009 Some("there"), Some(""));
1010 t!(s: Path::new("hi/.there"), Some(".there"), Some("hi"), Some(".there"), no);
1011 t!(s: Path::new("hi/..there"), Some("..there"), Some("hi"),
1012 Some("."), Some("there"));
1013 t!(s: Path::new(b"a/b/\xFF"), None, Some("a/b"), None, no);
1014 t!(s: Path::new(b"a/b/\xFF.txt"), None, Some("a/b"), None, Some("txt"));
1015 t!(s: Path::new(b"a/b/c.\x80"), None, Some("a/b"), Some("c"), no);
1016 t!(s: Path::new(b"\xFF/b"), Some("b"), None, Some("b"), no);
1020 fn test_dir_path() {
1021 t!(v: Path::new(b"hi/there\x80").dir_path(), b"hi");
1022 t!(v: Path::new(b"hi\xFF/there").dir_path(), b"hi\xFF");
1023 t!(s: Path::new("hi/there").dir_path(), "hi");
1024 t!(s: Path::new("hi").dir_path(), ".");
1025 t!(s: Path::new("/hi").dir_path(), "/");
1026 t!(s: Path::new("/").dir_path(), "/");
1027 t!(s: Path::new("..").dir_path(), "..");
1028 t!(s: Path::new("../..").dir_path(), "../..");
1032 fn test_is_absolute() {
1034 (s: $path:expr, $abs:expr, $rel:expr) => (
1036 let path = Path::new($path);
1037 assert_eq!(path.is_absolute(), $abs);
1038 assert_eq!(path.is_relative(), $rel);
1042 t!(s: "a/b/c", false, true);
1043 t!(s: "/a/b/c", true, false);
1044 t!(s: "a", false, true);
1045 t!(s: "/a", true, false);
1046 t!(s: ".", false, true);
1047 t!(s: "/", true, false);
1048 t!(s: "..", false, true);
1049 t!(s: "../..", false, true);
1053 fn test_is_ancestor_of() {
1055 (s: $path:expr, $dest:expr, $exp:expr) => (
1057 let path = Path::new($path);
1058 let dest = Path::new($dest);
1059 assert_eq!(path.is_ancestor_of(&dest), $exp);
1064 t!(s: "a/b/c", "a/b/c/d", true);
1065 t!(s: "a/b/c", "a/b/c", true);
1066 t!(s: "a/b/c", "a/b", false);
1067 t!(s: "/a/b/c", "/a/b/c", true);
1068 t!(s: "/a/b", "/a/b/c", true);
1069 t!(s: "/a/b/c/d", "/a/b/c", false);
1070 t!(s: "/a/b", "a/b/c", false);
1071 t!(s: "a/b", "/a/b/c", false);
1072 t!(s: "a/b/c", "a/b/d", false);
1073 t!(s: "../a/b/c", "a/b/c", false);
1074 t!(s: "a/b/c", "../a/b/c", false);
1075 t!(s: "a/b/c", "a/b/cd", false);
1076 t!(s: "a/b/cd", "a/b/c", false);
1077 t!(s: "../a/b", "../a/b/c", true);
1078 t!(s: ".", "a/b", true);
1079 t!(s: ".", ".", true);
1080 t!(s: "/", "/", true);
1081 t!(s: "/", "/a/b", true);
1082 t!(s: "..", "a/b", true);
1083 t!(s: "../..", "a/b", true);
1087 fn test_ends_with_path() {
1089 (s: $path:expr, $child:expr, $exp:expr) => (
1091 let path = Path::new($path);
1092 let child = Path::new($child);
1093 assert_eq!(path.ends_with_path(&child), $exp);
1096 (v: $path:expr, $child:expr, $exp:expr) => (
1098 let path = Path::new($path);
1099 let child = Path::new($child);
1100 assert_eq!(path.ends_with_path(&child), $exp);
1105 t!(s: "a/b/c", "c", true);
1106 t!(s: "a/b/c", "d", false);
1107 t!(s: "foo/bar/quux", "bar", false);
1108 t!(s: "foo/bar/quux", "barquux", false);
1109 t!(s: "a/b/c", "b/c", true);
1110 t!(s: "a/b/c", "a/b/c", true);
1111 t!(s: "a/b/c", "foo/a/b/c", false);
1112 t!(s: "/a/b/c", "a/b/c", true);
1113 t!(s: "/a/b/c", "/a/b/c", false); // child must be relative
1114 t!(s: "/a/b/c", "foo/a/b/c", false);
1115 t!(s: "a/b/c", "", false);
1116 t!(s: "", "", true);
1117 t!(s: "/a/b/c", "d/e/f", false);
1118 t!(s: "a/b/c", "a/b", false);
1119 t!(s: "a/b/c", "b", false);
1120 t!(v: b"a/b/c", b"b/c", true);
1121 t!(v: b"a/b/\xFF", b"\xFF", true);
1122 t!(v: b"a/b/\xFF", b"b/\xFF", true);
1126 fn test_path_relative_from() {
1128 (s: $path:expr, $other:expr, $exp:expr) => (
1130 let path = Path::new($path);
1131 let other = Path::new($other);
1132 let res = path.path_relative_from(&other);
1133 assert_eq!(res.as_ref().and_then(|x| x.as_str()), $exp);
1138 t!(s: "a/b/c", "a/b", Some("c"));
1139 t!(s: "a/b/c", "a/b/d", Some("../c"));
1140 t!(s: "a/b/c", "a/b/c/d", Some(".."));
1141 t!(s: "a/b/c", "a/b/c", Some("."));
1142 t!(s: "a/b/c", "a/b/c/d/e", Some("../.."));
1143 t!(s: "a/b/c", "a/d/e", Some("../../b/c"));
1144 t!(s: "a/b/c", "d/e/f", Some("../../../a/b/c"));
1145 t!(s: "a/b/c", "/a/b/c", None);
1146 t!(s: "/a/b/c", "a/b/c", Some("/a/b/c"));
1147 t!(s: "/a/b/c", "/a/b/c/d", Some(".."));
1148 t!(s: "/a/b/c", "/a/b", Some("c"));
1149 t!(s: "/a/b/c", "/a/b/c/d/e", Some("../.."));
1150 t!(s: "/a/b/c", "/a/d/e", Some("../../b/c"));
1151 t!(s: "/a/b/c", "/d/e/f", Some("../../../a/b/c"));
1152 t!(s: "hi/there.txt", "hi/there", Some("../there.txt"));
1153 t!(s: ".", "a", Some(".."));
1154 t!(s: ".", "a/b", Some("../.."));
1155 t!(s: ".", ".", Some("."));
1156 t!(s: "a", ".", Some("a"));
1157 t!(s: "a/b", ".", Some("a/b"));
1158 t!(s: "..", ".", Some(".."));
1159 t!(s: "a/b/c", "a/b/c", Some("."));
1160 t!(s: "/a/b/c", "/a/b/c", Some("."));
1161 t!(s: "/", "/", Some("."));
1162 t!(s: "/", ".", Some("/"));
1163 t!(s: "../../a", "b", Some("../../../a"));
1164 t!(s: "a", "../../b", None);
1165 t!(s: "../../a", "../../b", Some("../a"));
1166 t!(s: "../../a", "../../a/b", Some(".."));
1167 t!(s: "../../a/b", "../../a", Some("b"));
1171 fn test_components_iter() {
1173 (s: $path:expr, $exp:expr) => (
1175 let path = Path::new($path);
1176 let comps = path.components().collect::<Vec<&[u8]>>();
1177 let exp: &[&str] = $exp;
1178 let exps = exp.iter().map(|x| x.as_bytes()).collect::<Vec<&[u8]>>();
1179 assert!(comps == exps, "components: Expected {}, found {}",
1181 let comps = path.components().rev().collect::<Vec<&[u8]>>();
1182 let exps = exps.into_iter().rev().collect::<Vec<&[u8]>>();
1183 assert!(comps == exps, "rev_components: Expected {}, found {}",
1187 (b: $arg:expr, [$($exp:expr),*]) => (
1189 let path = Path::new($arg);
1190 let comps = path.components().collect::<Vec<&[u8]>>();
1191 let exp: &[&[u8]] = [$($exp),*];
1192 assert_eq!(comps.as_slice(), exp);
1193 let comps = path.components().rev().collect::<Vec<&[u8]>>();
1194 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
1195 assert_eq!(comps, exp)
1200 t!(b: b"a/b/c", [b"a", b"b", b"c"]);
1201 t!(b: b"/\xFF/a/\x80", [b"\xFF", b"a", b"\x80"]);
1202 t!(b: b"../../foo\xCDbar", [b"..", b"..", b"foo\xCDbar"]);
1203 t!(s: "a/b/c", ["a", "b", "c"]);
1204 t!(s: "a/b/d", ["a", "b", "d"]);
1205 t!(s: "a/b/cd", ["a", "b", "cd"]);
1206 t!(s: "/a/b/c", ["a", "b", "c"]);
1211 t!(s: "..", [".."]);
1212 t!(s: "../..", ["..", ".."]);
1213 t!(s: "../../foo", ["..", "..", "foo"]);
1217 fn test_str_components() {
1219 (b: $arg:expr, $exp:expr) => (
1221 let path = Path::new($arg);
1222 let comps = path.str_components().collect::<Vec<Option<&str>>>();
1223 let exp: &[Option<&str>] = $exp;
1224 assert_eq!(comps.as_slice(), exp);
1225 let comps = path.str_components().rev().collect::<Vec<Option<&str>>>();
1226 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<Option<&str>>>();
1227 assert_eq!(comps, exp);
1232 t!(b: b"a/b/c", [Some("a"), Some("b"), Some("c")]);
1233 t!(b: b"/\xFF/a/\x80", [None, Some("a"), None]);
1234 t!(b: b"../../foo\xCDbar", [Some(".."), Some(".."), None]);
1235 // str_components is a wrapper around components, so no need to do
1236 // the full set of tests
1243 use self::test::Bencher;
1248 fn join_home_dir(b: &mut Bencher) {
1249 let posix_path = Path::new("/");
1251 posix_path.join("home");
1256 fn join_abs_path_home_dir(b: &mut Bencher) {
1257 let posix_path = Path::new("/");
1259 posix_path.join("/home");
1264 fn join_many_home_dir(b: &mut Bencher) {
1265 let posix_path = Path::new("/");
1267 posix_path.join_many(&["home"]);
1272 fn join_many_abs_path_home_dir(b: &mut Bencher) {
1273 let posix_path = Path::new("/");
1275 posix_path.join_many(&["/home"]);
1280 fn push_home_dir(b: &mut Bencher) {
1281 let mut posix_path = Path::new("/");
1283 posix_path.push("home");
1288 fn push_abs_path_home_dir(b: &mut Bencher) {
1289 let mut posix_path = Path::new("/");
1291 posix_path.push("/home");
1296 fn push_many_home_dir(b: &mut Bencher) {
1297 let mut posix_path = Path::new("/");
1299 posix_path.push_many(&["home"]);
1304 fn push_many_abs_path_home_dir(b: &mut Bencher) {
1305 let mut posix_path = Path::new("/");
1307 posix_path.push_many(&["/home"]);
1312 fn ends_with_path_home_dir(b: &mut Bencher) {
1313 let posix_home_path = Path::new("/home");
1315 posix_home_path.ends_with_path(&Path::new("home"));
1320 fn ends_with_path_missmatch_jome_home(b: &mut Bencher) {
1321 let posix_home_path = Path::new("/home");
1323 posix_home_path.ends_with_path(&Path::new("jome"));
1328 fn is_ancestor_of_path_with_10_dirs(b: &mut Bencher) {
1329 let path = Path::new("/home/1/2/3/4/5/6/7/8/9");
1330 let mut sub = path.clone();
1333 path.is_ancestor_of(&sub);
1338 fn path_relative_from_forward(b: &mut Bencher) {
1339 let path = Path::new("/a/b/c");
1340 let mut other = path.clone();
1343 path.path_relative_from(&other);
1348 fn path_relative_from_same_level(b: &mut Bencher) {
1349 let path = Path::new("/a/b/c");
1350 let mut other = path.clone();
1354 path.path_relative_from(&other);
1359 fn path_relative_from_backward(b: &mut Bencher) {
1360 let path = Path::new("/a/b");
1361 let mut other = path.clone();
1364 path.path_relative_from(&other);