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 collections::{Collection, MutableSeq};
17 use from_str::FromStr;
20 use iter::{DoubleEndedIterator, AdditiveIterator, Extendable, Iterator, Map};
21 use option::{Option, None, Some};
24 use slice::{CloneableVector, Splits, Vector, VectorVector,
25 ImmutableEqSlice, ImmutableSlice};
28 use super::{BytesContainer, GenericPath, GenericPathUnsafe};
30 /// Iterator that yields successive components of a Path as &[u8]
31 pub type Components<'a> = Splits<'a, u8>;
33 /// Iterator that yields successive components of a Path as Option<&str>
34 pub type StrComponents<'a> = Map<'a, &'a [u8], Option<&'a str>,
37 /// Represents a POSIX file path
40 repr: Vec<u8>, // assumed to never be empty or contain NULs
41 sepidx: Option<uint> // index of the final separator in repr
44 /// The standard path separator character
45 pub static SEP: char = '/';
47 /// The standard path separator byte
48 pub static SEP_BYTE: u8 = SEP as u8;
50 /// Returns whether the given byte is a path separator
52 pub fn is_sep_byte(u: &u8) -> bool {
56 /// Returns whether the given char is a path separator
58 pub fn is_sep(c: char) -> bool {
62 impl PartialEq for Path {
64 fn eq(&self, other: &Path) -> bool {
65 self.repr == other.repr
71 impl PartialOrd for Path {
72 fn partial_cmp(&self, other: &Path) -> Option<Ordering> {
78 fn cmp(&self, other: &Path) -> Ordering {
79 self.repr.cmp(&other.repr)
83 impl FromStr for Path {
84 fn from_str(s: &str) -> Option<Path> {
89 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
90 // we cannot usefully take ToCStr arguments by reference (without forcing an
91 // additional & around &str). So we are instead temporarily adding an instance
92 // for &Path, so that we can take ToCStr as owned. When DST lands, the &Path
93 // instance should be removed, and arguments bound by ToCStr should be passed by
96 impl ToCStr for Path {
98 fn to_c_str(&self) -> CString {
99 // The Path impl guarantees no internal NUL
100 unsafe { self.to_c_str_unchecked() }
104 unsafe fn to_c_str_unchecked(&self) -> CString {
105 self.as_vec().to_c_str_unchecked()
109 impl<'a> ToCStr for &'a Path {
111 fn to_c_str(&self) -> CString {
116 unsafe fn to_c_str_unchecked(&self) -> CString {
117 (*self).to_c_str_unchecked()
121 impl<S: hash::Writer> hash::Hash<S> for Path {
123 fn hash(&self, state: &mut S) {
124 self.repr.hash(state)
128 impl BytesContainer for Path {
130 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
134 fn container_into_owned_bytes(self) -> Vec<u8> {
139 impl<'a> BytesContainer for &'a Path {
141 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
146 impl GenericPathUnsafe for Path {
147 unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
148 let path = Path::normalize(path.container_as_bytes());
149 assert!(!path.is_empty());
150 let idx = path.as_slice().rposition_elem(&SEP_BYTE);
151 Path{ repr: path, sepidx: idx }
154 unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
155 let filename = filename.container_as_bytes();
157 None if b".." == self.repr.as_slice() => {
158 let mut v = Vec::with_capacity(3 + filename.len());
159 v.push_all(dot_dot_static);
161 v.push_all(filename);
162 // FIXME: this is slow
163 self.repr = Path::normalize(v.as_slice());
166 self.repr = Path::normalize(filename);
168 Some(idx) if self.repr.slice_from(idx+1) == b".." => {
169 let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
170 v.push_all(self.repr.as_slice());
172 v.push_all(filename);
173 // FIXME: this is slow
174 self.repr = Path::normalize(v.as_slice());
177 let mut v = Vec::with_capacity(idx + 1 + filename.len());
178 v.push_all(self.repr.slice_to(idx+1));
179 v.push_all(filename);
180 // FIXME: this is slow
181 self.repr = Path::normalize(v.as_slice());
184 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
187 unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
188 let path = path.container_as_bytes();
189 if !path.is_empty() {
190 if path[0] == SEP_BYTE {
191 self.repr = Path::normalize(path);
193 let mut v = Vec::with_capacity(self.repr.len() + path.len() + 1);
194 v.push_all(self.repr.as_slice());
197 // FIXME: this is slow
198 self.repr = Path::normalize(v.as_slice());
200 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
205 impl GenericPath for Path {
207 fn as_vec<'a>(&'a self) -> &'a [u8] {
211 fn into_vec(self) -> Vec<u8> {
215 fn dirname<'a>(&'a self) -> &'a [u8] {
217 None if b".." == self.repr.as_slice() => self.repr.as_slice(),
219 Some(0) => self.repr.slice_to(1),
220 Some(idx) if self.repr.slice_from(idx+1) == b".." => self.repr.as_slice(),
221 Some(idx) => self.repr.slice_to(idx)
225 fn filename<'a>(&'a self) -> Option<&'a [u8]> {
227 None if b"." == self.repr.as_slice() ||
228 b".." == self.repr.as_slice() => None,
229 None => Some(self.repr.as_slice()),
230 Some(idx) if self.repr.slice_from(idx+1) == b".." => None,
231 Some(0) if self.repr.slice_from(1).is_empty() => None,
232 Some(idx) => Some(self.repr.slice_from(idx+1))
236 fn pop(&mut self) -> bool {
238 None if b"." == self.repr.as_slice() => false,
240 self.repr = vec![b'.'];
244 Some(0) if b"/" == self.repr.as_slice() => false,
247 self.repr.truncate(idx+1);
249 self.repr.truncate(idx);
251 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
257 fn root_path(&self) -> Option<Path> {
258 if self.is_absolute() {
266 fn is_absolute(&self) -> bool {
267 *self.repr.get(0) == SEP_BYTE
270 fn is_ancestor_of(&self, other: &Path) -> bool {
271 if self.is_absolute() != other.is_absolute() {
274 let mut ita = self.components();
275 let mut itb = other.components();
276 if b"." == self.repr.as_slice() {
277 return match itb.next() {
279 Some(b) => b != b".."
283 match (ita.next(), itb.next()) {
285 (Some(a), Some(b)) if a == b => { continue },
286 (Some(a), _) if a == b".." => {
287 // if ita contains only .. components, it's an ancestor
288 return ita.all(|x| x == b"..");
297 fn path_relative_from(&self, base: &Path) -> Option<Path> {
298 if self.is_absolute() != base.is_absolute() {
299 if self.is_absolute() {
305 let mut ita = self.components();
306 let mut itb = base.components();
307 let mut comps = vec![];
309 match (ita.next(), itb.next()) {
310 (None, None) => break,
313 comps.extend(ita.by_ref());
316 (None, _) => comps.push(dot_dot_static),
317 (Some(a), Some(b)) if comps.is_empty() && a == b => (),
318 (Some(a), Some(b)) if b == b"." => comps.push(a),
319 (Some(_), Some(b)) if b == b".." => return None,
320 (Some(a), Some(_)) => {
321 comps.push(dot_dot_static);
323 comps.push(dot_dot_static);
326 comps.extend(ita.by_ref());
331 Some(Path::new(comps.as_slice().connect_vec(&SEP_BYTE)))
335 fn ends_with_path(&self, child: &Path) -> bool {
336 if !child.is_relative() { return false; }
337 let mut selfit = self.components().rev();
338 let mut childit = child.components().rev();
340 match (selfit.next(), childit.next()) {
341 (Some(a), Some(b)) => if a != b { return false; },
342 (Some(_), None) => break,
343 (None, Some(_)) => return false,
344 (None, None) => break
352 /// Returns a new Path from a byte vector or string
356 /// Fails the task if the vector contains a NUL.
358 pub fn new<T: BytesContainer>(path: T) -> Path {
359 GenericPath::new(path)
362 /// Returns a new Path from a byte vector or string, if possible
364 pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
365 GenericPath::new_opt(path)
368 /// Returns a normalized byte vector representation of a path, by removing all empty
369 /// components, and unnecessary . and .. components.
370 fn normalize<V: Vector<u8>+CloneableVector<u8>>(v: V) -> Vec<u8> {
371 // borrowck is being very picky
373 let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE;
374 let v_ = if is_abs { v.as_slice().slice_from(1) } else { v.as_slice() };
375 let comps = normalize_helper(v_, is_abs);
379 if is_abs && comps.is_empty() {
382 let n = if is_abs { comps.len() } else { comps.len() - 1} +
383 comps.iter().map(|v| v.len()).sum();
384 let mut v = Vec::with_capacity(n);
385 let mut it = comps.move_iter();
389 Some(comp) => v.push_all(comp)
402 None => Vec::from_slice(v.as_slice()),
407 /// Returns an iterator that yields each component of the path in turn.
408 /// Does not distinguish between absolute and relative paths, e.g.
409 /// /a/b/c and a/b/c yield the same set of components.
410 /// A path of "/" yields no components. A path of "." yields one component.
411 pub fn components<'a>(&'a self) -> Components<'a> {
412 let v = if *self.repr.get(0) == SEP_BYTE {
413 self.repr.slice_from(1)
414 } else { self.repr.as_slice() };
415 let mut ret = v.split(is_sep_byte);
417 // consume the empty "" component
423 /// Returns an iterator that yields each component of the path as Option<&str>.
424 /// See components() for details.
425 pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
426 self.components().map(str::from_utf8)
430 // None result means the byte vector didn't need normalizing
431 fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<Vec<&'a [u8]>> {
432 if is_abs && v.as_slice().is_empty() {
435 let mut comps: Vec<&'a [u8]> = vec![];
437 let mut changed = false;
438 for comp in v.split(is_sep_byte) {
439 if comp.is_empty() { changed = true }
440 else if comp == b"." { changed = true }
441 else if comp == b".." {
442 if is_abs && comps.is_empty() { changed = true }
443 else if comps.len() == n_up { comps.push(dot_dot_static); n_up += 1 }
444 else { comps.pop().unwrap(); changed = true }
445 } else { comps.push(comp) }
448 if comps.is_empty() && !is_abs {
452 comps.push(dot_static);
460 static dot_static: &'static [u8] = b".";
461 static dot_dot_static: &'static [u8] = b"..";
471 (s: $path:expr, $exp:expr) => (
474 assert!(path.as_str() == Some($exp));
477 (v: $path:expr, $exp:expr) => (
480 assert!(path.as_vec() == $exp);
487 let empty: &[u8] = [];
488 t!(v: Path::new(empty), b".");
489 t!(v: Path::new(b"/"), b"/");
490 t!(v: Path::new(b"a/b/c"), b"a/b/c");
491 t!(v: Path::new(b"a/b/c\xFF"), b"a/b/c\xFF");
492 t!(v: Path::new(b"\xFF/../foo\x80"), b"foo\x80");
493 let p = Path::new(b"a/b/c\xFF");
494 assert!(p.as_str() == None);
496 t!(s: Path::new(""), ".");
497 t!(s: Path::new("/"), "/");
498 t!(s: Path::new("hi"), "hi");
499 t!(s: Path::new("hi/"), "hi");
500 t!(s: Path::new("/lib"), "/lib");
501 t!(s: Path::new("/lib/"), "/lib");
502 t!(s: Path::new("hi/there"), "hi/there");
503 t!(s: Path::new("hi/there.txt"), "hi/there.txt");
505 t!(s: Path::new("hi/there/"), "hi/there");
506 t!(s: Path::new("hi/../there"), "there");
507 t!(s: Path::new("../hi/there"), "../hi/there");
508 t!(s: Path::new("/../hi/there"), "/hi/there");
509 t!(s: Path::new("foo/.."), ".");
510 t!(s: Path::new("/foo/.."), "/");
511 t!(s: Path::new("/foo/../.."), "/");
512 t!(s: Path::new("/foo/../../bar"), "/bar");
513 t!(s: Path::new("/./hi/./there/."), "/hi/there");
514 t!(s: Path::new("/./hi/./there/./.."), "/hi");
515 t!(s: Path::new("foo/../.."), "..");
516 t!(s: Path::new("foo/../../.."), "../..");
517 t!(s: Path::new("foo/../../bar"), "../bar");
519 assert_eq!(Path::new(b"foo/bar").into_vec().as_slice(), b"foo/bar");
520 assert_eq!(Path::new(b"/foo/../../bar").into_vec().as_slice(),
523 let p = Path::new(b"foo/bar\x80");
524 assert!(p.as_str() == None);
528 fn test_opt_paths() {
529 assert!(Path::new_opt(b"foo/bar\0") == None);
530 t!(v: Path::new_opt(b"foo/bar").unwrap(), b"foo/bar");
531 assert!(Path::new_opt("foo/bar\0") == None);
532 t!(s: Path::new_opt("foo/bar").unwrap(), "foo/bar");
536 fn test_null_byte() {
538 let result = task::try(proc() {
539 Path::new(b"foo/bar\0")
541 assert!(result.is_err());
543 let result = task::try(proc() {
544 Path::new("test").set_filename(b"f\0o")
546 assert!(result.is_err());
548 let result = task::try(proc() {
549 Path::new("test").push(b"f\0o");
551 assert!(result.is_err());
555 fn test_display_str() {
557 ($path:expr, $disp:ident, $exp:expr) => (
559 let path = Path::new($path);
560 assert!(path.$disp().to_string().as_slice() == $exp);
564 t!("foo", display, "foo");
565 t!(b"foo\x80", display, "foo\uFFFD");
566 t!(b"foo\xFFbar", display, "foo\uFFFDbar");
567 t!(b"foo\xFF/bar", filename_display, "bar");
568 t!(b"foo/\xFFbar", filename_display, "\uFFFDbar");
569 t!(b"/", filename_display, "");
572 ($path:expr, $exp:expr) => (
574 let path = Path::new($path);
575 let mo = path.display().as_maybe_owned();
576 assert!(mo.as_slice() == $exp);
579 ($path:expr, $exp:expr, filename) => (
581 let path = Path::new($path);
582 let mo = path.filename_display().as_maybe_owned();
583 assert!(mo.as_slice() == $exp);
589 t!(b"foo\x80", "foo\uFFFD");
590 t!(b"foo\xFFbar", "foo\uFFFDbar");
591 t!(b"foo\xFF/bar", "bar", filename);
592 t!(b"foo/\xFFbar", "\uFFFDbar", filename);
593 t!(b"/", "", filename);
599 ($path:expr, $exp:expr, $expf:expr) => (
601 let path = Path::new($path);
602 let f = format!("{}", path.display());
603 assert!(f.as_slice() == $exp);
604 let f = format!("{}", path.filename_display());
605 assert!(f.as_slice() == $expf);
610 t!(b"foo", "foo", "foo");
611 t!(b"foo/bar", "foo/bar", "bar");
613 t!(b"foo\xFF", "foo\uFFFD", "foo\uFFFD");
614 t!(b"foo\xFF/bar", "foo\uFFFD/bar", "bar");
615 t!(b"foo/\xFFbar", "foo/\uFFFDbar", "\uFFFDbar");
616 t!(b"\xFFfoo/bar\xFF", "\uFFFDfoo/bar\uFFFD", "bar\uFFFD");
620 fn test_components() {
622 (s: $path:expr, $op:ident, $exp:expr) => (
624 let path = Path::new($path);
625 assert!(path.$op() == ($exp).as_bytes());
628 (s: $path:expr, $op:ident, $exp:expr, opt) => (
630 let path = Path::new($path);
631 let left = path.$op().map(|x| str::from_utf8(x).unwrap());
632 assert!(left == $exp);
635 (v: $path:expr, $op:ident, $exp:expr) => (
638 let path = Path::new(arg);
639 assert!(path.$op() == $exp);
644 t!(v: b"a/b/c", filename, Some(b"c"));
645 t!(v: b"a/b/c\xFF", filename, Some(b"c\xFF"));
646 t!(v: b"a/b\xFF/c", filename, Some(b"c"));
647 t!(s: "a/b/c", filename, Some("c"), opt);
648 t!(s: "/a/b/c", filename, Some("c"), opt);
649 t!(s: "a", filename, Some("a"), opt);
650 t!(s: "/a", filename, Some("a"), opt);
651 t!(s: ".", filename, None, opt);
652 t!(s: "/", filename, None, opt);
653 t!(s: "..", filename, None, opt);
654 t!(s: "../..", filename, None, opt);
656 t!(v: b"a/b/c", dirname, b"a/b");
657 t!(v: b"a/b/c\xFF", dirname, b"a/b");
658 t!(v: b"a/b\xFF/c", dirname, b"a/b\xFF");
659 t!(s: "a/b/c", dirname, "a/b");
660 t!(s: "/a/b/c", dirname, "/a/b");
661 t!(s: "a", dirname, ".");
662 t!(s: "/a", dirname, "/");
663 t!(s: ".", dirname, ".");
664 t!(s: "/", dirname, "/");
665 t!(s: "..", dirname, "..");
666 t!(s: "../..", dirname, "../..");
668 t!(v: b"hi/there.txt", filestem, Some(b"there"));
669 t!(v: b"hi/there\x80.txt", filestem, Some(b"there\x80"));
670 t!(v: b"hi/there.t\x80xt", filestem, Some(b"there"));
671 t!(s: "hi/there.txt", filestem, Some("there"), opt);
672 t!(s: "hi/there", filestem, Some("there"), opt);
673 t!(s: "there.txt", filestem, Some("there"), opt);
674 t!(s: "there", filestem, Some("there"), opt);
675 t!(s: ".", filestem, None, opt);
676 t!(s: "/", filestem, None, opt);
677 t!(s: "foo/.bar", filestem, Some(".bar"), opt);
678 t!(s: ".bar", filestem, Some(".bar"), opt);
679 t!(s: "..bar", filestem, Some("."), opt);
680 t!(s: "hi/there..txt", filestem, Some("there."), opt);
681 t!(s: "..", filestem, None, opt);
682 t!(s: "../..", filestem, None, opt);
684 t!(v: b"hi/there.txt", extension, Some(b"txt"));
685 t!(v: b"hi/there\x80.txt", extension, Some(b"txt"));
686 t!(v: b"hi/there.t\x80xt", extension, Some(b"t\x80xt"));
687 t!(v: b"hi/there", extension, None);
688 t!(v: b"hi/there\x80", extension, None);
689 t!(s: "hi/there.txt", extension, Some("txt"), opt);
690 t!(s: "hi/there", extension, None, opt);
691 t!(s: "there.txt", extension, Some("txt"), opt);
692 t!(s: "there", extension, None, opt);
693 t!(s: ".", extension, None, opt);
694 t!(s: "/", extension, None, opt);
695 t!(s: "foo/.bar", extension, None, opt);
696 t!(s: ".bar", extension, None, opt);
697 t!(s: "..bar", extension, Some("bar"), opt);
698 t!(s: "hi/there..txt", extension, Some("txt"), opt);
699 t!(s: "..", extension, None, opt);
700 t!(s: "../..", extension, None, opt);
706 (s: $path:expr, $join:expr) => (
710 let mut p1 = Path::new(path);
713 assert!(p1 == p2.join(join));
718 t!(s: "a/b/c", "..");
719 t!(s: "/a/b/c", "d");
721 t!(s: "a/b", "/c/d");
725 fn test_push_path() {
727 (s: $path:expr, $push:expr, $exp:expr) => (
729 let mut p = Path::new($path);
730 let push = Path::new($push);
732 assert!(p.as_str() == Some($exp));
737 t!(s: "a/b/c", "d", "a/b/c/d");
738 t!(s: "/a/b/c", "d", "/a/b/c/d");
739 t!(s: "a/b", "c/d", "a/b/c/d");
740 t!(s: "a/b", "/c/d", "/c/d");
741 t!(s: "a/b", ".", "a/b");
742 t!(s: "a/b", "../c", "a/c");
746 fn test_push_many() {
748 (s: $path:expr, $push:expr, $exp:expr) => (
750 let mut p = Path::new($path);
752 assert!(p.as_str() == Some($exp));
755 (v: $path:expr, $push:expr, $exp:expr) => (
757 let mut p = Path::new($path);
759 assert!(p.as_vec() == $exp);
764 t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
765 t!(s: "a/b/c", ["d", "/e"], "/e");
766 t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
767 t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
768 t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
769 t!(v: b"a/b/c", [b"d", b"/e", b"f"], b"/e/f");
770 t!(v: b"a/b/c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")], b"a/b/c/d/e");
776 (s: $path:expr, $left:expr, $right:expr) => (
778 let mut p = Path::new($path);
779 let result = p.pop();
780 assert!(p.as_str() == Some($left));
781 assert!(result == $right);
784 (b: $path:expr, $left:expr, $right:expr) => (
786 let mut p = Path::new($path);
787 let result = p.pop();
788 assert!(p.as_vec() == $left);
789 assert!(result == $right);
794 t!(b: b"a/b/c", b"a/b", true);
795 t!(b: b"a", b".", true);
796 t!(b: b".", b".", false);
797 t!(b: b"/a", b"/", true);
798 t!(b: b"/", b"/", false);
799 t!(b: b"a/b/c\x80", b"a/b", true);
800 t!(b: b"a/b\x80/c", b"a/b\x80", true);
801 t!(b: b"\xFF", b".", true);
802 t!(b: b"/\xFF", b"/", true);
803 t!(s: "a/b/c", "a/b", true);
804 t!(s: "a", ".", true);
805 t!(s: ".", ".", false);
806 t!(s: "/a", "/", true);
807 t!(s: "/", "/", false);
811 fn test_root_path() {
812 assert!(Path::new(b"a/b/c").root_path() == None);
813 assert!(Path::new(b"/a/b/c").root_path() == Some(Path::new("/")));
818 t!(v: Path::new(b"a/b/c").join(b".."), b"a/b");
819 t!(v: Path::new(b"/a/b/c").join(b"d"), b"/a/b/c/d");
820 t!(v: Path::new(b"a/\x80/c").join(b"\xFF"), b"a/\x80/c/\xFF");
821 t!(s: Path::new("a/b/c").join(".."), "a/b");
822 t!(s: Path::new("/a/b/c").join("d"), "/a/b/c/d");
823 t!(s: Path::new("a/b").join("c/d"), "a/b/c/d");
824 t!(s: Path::new("a/b").join("/c/d"), "/c/d");
825 t!(s: Path::new(".").join("a/b"), "a/b");
826 t!(s: Path::new("/").join("a/b"), "/a/b");
830 fn test_join_path() {
832 (s: $path:expr, $join:expr, $exp:expr) => (
834 let path = Path::new($path);
835 let join = Path::new($join);
836 let res = path.join(&join);
837 assert!(res.as_str() == Some($exp));
842 t!(s: "a/b/c", "..", "a/b");
843 t!(s: "/a/b/c", "d", "/a/b/c/d");
844 t!(s: "a/b", "c/d", "a/b/c/d");
845 t!(s: "a/b", "/c/d", "/c/d");
846 t!(s: ".", "a/b", "a/b");
847 t!(s: "/", "a/b", "/a/b");
851 fn test_join_many() {
853 (s: $path:expr, $join:expr, $exp:expr) => (
855 let path = Path::new($path);
856 let res = path.join_many($join);
857 assert!(res.as_str() == Some($exp));
860 (v: $path:expr, $join:expr, $exp:expr) => (
862 let path = Path::new($path);
863 let res = path.join_many($join);
864 assert!(res.as_vec() == $exp);
869 t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
870 t!(s: "a/b/c", ["..", "d"], "a/b/d");
871 t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
872 t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
873 t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
874 t!(v: b"a/b/c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")], b"a/b/c/d/e");
878 fn test_with_helpers() {
879 let empty: &[u8] = [];
881 t!(v: Path::new(b"a/b/c").with_filename(b"d"), b"a/b/d");
882 t!(v: Path::new(b"a/b/c\xFF").with_filename(b"\x80"), b"a/b/\x80");
883 t!(v: Path::new(b"/\xFF/foo").with_filename(b"\xCD"),
885 t!(s: Path::new("a/b/c").with_filename("d"), "a/b/d");
886 t!(s: Path::new(".").with_filename("foo"), "foo");
887 t!(s: Path::new("/a/b/c").with_filename("d"), "/a/b/d");
888 t!(s: Path::new("/").with_filename("foo"), "/foo");
889 t!(s: Path::new("/a").with_filename("foo"), "/foo");
890 t!(s: Path::new("foo").with_filename("bar"), "bar");
891 t!(s: Path::new("/").with_filename("foo/"), "/foo");
892 t!(s: Path::new("/a").with_filename("foo/"), "/foo");
893 t!(s: Path::new("a/b/c").with_filename(""), "a/b");
894 t!(s: Path::new("a/b/c").with_filename("."), "a/b");
895 t!(s: Path::new("a/b/c").with_filename(".."), "a");
896 t!(s: Path::new("/a").with_filename(""), "/");
897 t!(s: Path::new("foo").with_filename(""), ".");
898 t!(s: Path::new("a/b/c").with_filename("d/e"), "a/b/d/e");
899 t!(s: Path::new("a/b/c").with_filename("/d"), "a/b/d");
900 t!(s: Path::new("..").with_filename("foo"), "../foo");
901 t!(s: Path::new("../..").with_filename("foo"), "../../foo");
902 t!(s: Path::new("..").with_filename(""), "..");
903 t!(s: Path::new("../..").with_filename(""), "../..");
905 t!(v: Path::new(b"hi/there\x80.txt").with_extension(b"exe"),
906 b"hi/there\x80.exe");
907 t!(v: Path::new(b"hi/there.txt\x80").with_extension(b"\xFF"),
909 t!(v: Path::new(b"hi/there\x80").with_extension(b"\xFF"),
910 b"hi/there\x80.\xFF");
911 t!(v: Path::new(b"hi/there.\xFF").with_extension(empty), b"hi/there");
912 t!(s: Path::new("hi/there.txt").with_extension("exe"), "hi/there.exe");
913 t!(s: Path::new("hi/there.txt").with_extension(""), "hi/there");
914 t!(s: Path::new("hi/there.txt").with_extension("."), "hi/there..");
915 t!(s: Path::new("hi/there.txt").with_extension(".."), "hi/there...");
916 t!(s: Path::new("hi/there").with_extension("txt"), "hi/there.txt");
917 t!(s: Path::new("hi/there").with_extension("."), "hi/there..");
918 t!(s: Path::new("hi/there").with_extension(".."), "hi/there...");
919 t!(s: Path::new("hi/there.").with_extension("txt"), "hi/there.txt");
920 t!(s: Path::new("hi/.foo").with_extension("txt"), "hi/.foo.txt");
921 t!(s: Path::new("hi/there.txt").with_extension(".foo"), "hi/there..foo");
922 t!(s: Path::new("/").with_extension("txt"), "/");
923 t!(s: Path::new("/").with_extension("."), "/");
924 t!(s: Path::new("/").with_extension(".."), "/");
925 t!(s: Path::new(".").with_extension("txt"), ".");
931 (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
935 let mut p1 = Path::new(path);
937 let p2 = Path::new(path);
938 assert!(p1 == p2.$with(arg));
941 (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
945 let mut p1 = Path::new(path);
947 let p2 = Path::new(path);
948 assert!(p1 == p2.$with(arg));
953 t!(v: b"a/b/c", set_filename, with_filename, b"d");
954 t!(v: b"/", set_filename, with_filename, b"foo");
955 t!(v: b"\x80", set_filename, with_filename, b"\xFF");
956 t!(s: "a/b/c", set_filename, with_filename, "d");
957 t!(s: "/", set_filename, with_filename, "foo");
958 t!(s: ".", set_filename, with_filename, "foo");
959 t!(s: "a/b", set_filename, with_filename, "");
960 t!(s: "a", set_filename, with_filename, "");
962 t!(v: b"hi/there.txt", set_extension, with_extension, b"exe");
963 t!(v: b"hi/there.t\x80xt", set_extension, with_extension, b"exe\xFF");
964 t!(s: "hi/there.txt", set_extension, with_extension, "exe");
965 t!(s: "hi/there.", set_extension, with_extension, "txt");
966 t!(s: "hi/there", set_extension, with_extension, "txt");
967 t!(s: "hi/there.txt", set_extension, with_extension, "");
968 t!(s: "hi/there", set_extension, with_extension, "");
969 t!(s: ".", set_extension, with_extension, "txt");
975 (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
978 let filename = $filename;
979 assert!(path.filename_str() == filename,
980 "{}.filename_str(): Expected `{:?}`, found {:?}",
981 path.as_str().unwrap(), filename, path.filename_str());
982 let dirname = $dirname;
983 assert!(path.dirname_str() == dirname,
984 "`{}`.dirname_str(): Expected `{:?}`, found `{:?}`",
985 path.as_str().unwrap(), dirname, path.dirname_str());
986 let filestem = $filestem;
987 assert!(path.filestem_str() == filestem,
988 "`{}`.filestem_str(): Expected `{:?}`, found `{:?}`",
989 path.as_str().unwrap(), filestem, path.filestem_str());
991 assert!(path.extension_str() == ext,
992 "`{}`.extension_str(): Expected `{:?}`, found `{:?}`",
993 path.as_str().unwrap(), ext, path.extension_str());
996 (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
999 assert!(path.filename() == $filename);
1000 assert!(path.dirname() == $dirname);
1001 assert!(path.filestem() == $filestem);
1002 assert!(path.extension() == $ext);
1007 t!(v: Path::new(b"a/b/c"), Some(b"c"), b"a/b", Some(b"c"), None);
1008 t!(v: Path::new(b"a/b/\xFF"), Some(b"\xFF"), b"a/b", Some(b"\xFF"), None);
1009 t!(v: Path::new(b"hi/there.\xFF"), Some(b"there.\xFF"), b"hi",
1010 Some(b"there"), Some(b"\xFF"));
1011 t!(s: Path::new("a/b/c"), Some("c"), Some("a/b"), Some("c"), None);
1012 t!(s: Path::new("."), None, Some("."), None, None);
1013 t!(s: Path::new("/"), None, Some("/"), None, None);
1014 t!(s: Path::new(".."), None, Some(".."), None, None);
1015 t!(s: Path::new("../.."), None, Some("../.."), None, None);
1016 t!(s: Path::new("hi/there.txt"), Some("there.txt"), Some("hi"),
1017 Some("there"), Some("txt"));
1018 t!(s: Path::new("hi/there"), Some("there"), Some("hi"), Some("there"), None);
1019 t!(s: Path::new("hi/there."), Some("there."), Some("hi"),
1020 Some("there"), Some(""));
1021 t!(s: Path::new("hi/.there"), Some(".there"), Some("hi"), Some(".there"), None);
1022 t!(s: Path::new("hi/..there"), Some("..there"), Some("hi"),
1023 Some("."), Some("there"));
1024 t!(s: Path::new(b"a/b/\xFF"), None, Some("a/b"), None, None);
1025 t!(s: Path::new(b"a/b/\xFF.txt"), None, Some("a/b"), None, Some("txt"));
1026 t!(s: Path::new(b"a/b/c.\x80"), None, Some("a/b"), Some("c"), None);
1027 t!(s: Path::new(b"\xFF/b"), Some("b"), None, Some("b"), None);
1031 fn test_dir_path() {
1032 t!(v: Path::new(b"hi/there\x80").dir_path(), b"hi");
1033 t!(v: Path::new(b"hi\xFF/there").dir_path(), b"hi\xFF");
1034 t!(s: Path::new("hi/there").dir_path(), "hi");
1035 t!(s: Path::new("hi").dir_path(), ".");
1036 t!(s: Path::new("/hi").dir_path(), "/");
1037 t!(s: Path::new("/").dir_path(), "/");
1038 t!(s: Path::new("..").dir_path(), "..");
1039 t!(s: Path::new("../..").dir_path(), "../..");
1043 fn test_is_absolute() {
1045 (s: $path:expr, $abs:expr, $rel:expr) => (
1047 let path = Path::new($path);
1048 assert_eq!(path.is_absolute(), $abs);
1049 assert_eq!(path.is_relative(), $rel);
1053 t!(s: "a/b/c", false, true);
1054 t!(s: "/a/b/c", true, false);
1055 t!(s: "a", false, true);
1056 t!(s: "/a", true, false);
1057 t!(s: ".", false, true);
1058 t!(s: "/", true, false);
1059 t!(s: "..", false, true);
1060 t!(s: "../..", false, true);
1064 fn test_is_ancestor_of() {
1066 (s: $path:expr, $dest:expr, $exp:expr) => (
1068 let path = Path::new($path);
1069 let dest = Path::new($dest);
1070 assert_eq!(path.is_ancestor_of(&dest), $exp);
1075 t!(s: "a/b/c", "a/b/c/d", true);
1076 t!(s: "a/b/c", "a/b/c", true);
1077 t!(s: "a/b/c", "a/b", false);
1078 t!(s: "/a/b/c", "/a/b/c", true);
1079 t!(s: "/a/b", "/a/b/c", true);
1080 t!(s: "/a/b/c/d", "/a/b/c", false);
1081 t!(s: "/a/b", "a/b/c", false);
1082 t!(s: "a/b", "/a/b/c", false);
1083 t!(s: "a/b/c", "a/b/d", false);
1084 t!(s: "../a/b/c", "a/b/c", false);
1085 t!(s: "a/b/c", "../a/b/c", false);
1086 t!(s: "a/b/c", "a/b/cd", false);
1087 t!(s: "a/b/cd", "a/b/c", false);
1088 t!(s: "../a/b", "../a/b/c", true);
1089 t!(s: ".", "a/b", true);
1090 t!(s: ".", ".", true);
1091 t!(s: "/", "/", true);
1092 t!(s: "/", "/a/b", true);
1093 t!(s: "..", "a/b", true);
1094 t!(s: "../..", "a/b", true);
1098 fn test_ends_with_path() {
1100 (s: $path:expr, $child:expr, $exp:expr) => (
1102 let path = Path::new($path);
1103 let child = Path::new($child);
1104 assert_eq!(path.ends_with_path(&child), $exp);
1107 (v: $path:expr, $child:expr, $exp:expr) => (
1109 let path = Path::new($path);
1110 let child = Path::new($child);
1111 assert_eq!(path.ends_with_path(&child), $exp);
1116 t!(s: "a/b/c", "c", true);
1117 t!(s: "a/b/c", "d", false);
1118 t!(s: "foo/bar/quux", "bar", false);
1119 t!(s: "foo/bar/quux", "barquux", false);
1120 t!(s: "a/b/c", "b/c", true);
1121 t!(s: "a/b/c", "a/b/c", true);
1122 t!(s: "a/b/c", "foo/a/b/c", false);
1123 t!(s: "/a/b/c", "a/b/c", true);
1124 t!(s: "/a/b/c", "/a/b/c", false); // child must be relative
1125 t!(s: "/a/b/c", "foo/a/b/c", false);
1126 t!(s: "a/b/c", "", false);
1127 t!(s: "", "", true);
1128 t!(s: "/a/b/c", "d/e/f", false);
1129 t!(s: "a/b/c", "a/b", false);
1130 t!(s: "a/b/c", "b", false);
1131 t!(v: b"a/b/c", b"b/c", true);
1132 t!(v: b"a/b/\xFF", b"\xFF", true);
1133 t!(v: b"a/b/\xFF", b"b/\xFF", true);
1137 fn test_path_relative_from() {
1139 (s: $path:expr, $other:expr, $exp:expr) => (
1141 let path = Path::new($path);
1142 let other = Path::new($other);
1143 let res = path.path_relative_from(&other);
1144 assert_eq!(res.as_ref().and_then(|x| x.as_str()), $exp);
1149 t!(s: "a/b/c", "a/b", Some("c"));
1150 t!(s: "a/b/c", "a/b/d", Some("../c"));
1151 t!(s: "a/b/c", "a/b/c/d", Some(".."));
1152 t!(s: "a/b/c", "a/b/c", Some("."));
1153 t!(s: "a/b/c", "a/b/c/d/e", Some("../.."));
1154 t!(s: "a/b/c", "a/d/e", Some("../../b/c"));
1155 t!(s: "a/b/c", "d/e/f", Some("../../../a/b/c"));
1156 t!(s: "a/b/c", "/a/b/c", None);
1157 t!(s: "/a/b/c", "a/b/c", Some("/a/b/c"));
1158 t!(s: "/a/b/c", "/a/b/c/d", Some(".."));
1159 t!(s: "/a/b/c", "/a/b", Some("c"));
1160 t!(s: "/a/b/c", "/a/b/c/d/e", Some("../.."));
1161 t!(s: "/a/b/c", "/a/d/e", Some("../../b/c"));
1162 t!(s: "/a/b/c", "/d/e/f", Some("../../../a/b/c"));
1163 t!(s: "hi/there.txt", "hi/there", Some("../there.txt"));
1164 t!(s: ".", "a", Some(".."));
1165 t!(s: ".", "a/b", Some("../.."));
1166 t!(s: ".", ".", Some("."));
1167 t!(s: "a", ".", Some("a"));
1168 t!(s: "a/b", ".", Some("a/b"));
1169 t!(s: "..", ".", Some(".."));
1170 t!(s: "a/b/c", "a/b/c", Some("."));
1171 t!(s: "/a/b/c", "/a/b/c", Some("."));
1172 t!(s: "/", "/", Some("."));
1173 t!(s: "/", ".", Some("/"));
1174 t!(s: "../../a", "b", Some("../../../a"));
1175 t!(s: "a", "../../b", None);
1176 t!(s: "../../a", "../../b", Some("../a"));
1177 t!(s: "../../a", "../../a/b", Some(".."));
1178 t!(s: "../../a/b", "../../a", Some("b"));
1182 fn test_components_iter() {
1184 (s: $path:expr, $exp:expr) => (
1186 let path = Path::new($path);
1187 let comps = path.components().collect::<Vec<&[u8]>>();
1188 let exp: &[&str] = $exp;
1189 let exps = exp.iter().map(|x| x.as_bytes()).collect::<Vec<&[u8]>>();
1190 assert!(comps == exps, "components: Expected {:?}, found {:?}",
1192 let comps = path.components().rev().collect::<Vec<&[u8]>>();
1193 let exps = exps.move_iter().rev().collect::<Vec<&[u8]>>();
1194 assert!(comps == exps, "rev_components: Expected {:?}, found {:?}",
1198 (b: $arg:expr, [$($exp:expr),*]) => (
1200 let path = Path::new($arg);
1201 let comps = path.components().collect::<Vec<&[u8]>>();
1202 let exp: &[&[u8]] = [$($exp),*];
1203 assert_eq!(comps.as_slice(), exp);
1204 let comps = path.components().rev().collect::<Vec<&[u8]>>();
1205 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
1206 assert_eq!(comps, exp)
1211 t!(b: b"a/b/c", [b"a", b"b", b"c"]);
1212 t!(b: b"/\xFF/a/\x80", [b"\xFF", b"a", b"\x80"]);
1213 t!(b: b"../../foo\xCDbar", [b"..", b"..", b"foo\xCDbar"]);
1214 t!(s: "a/b/c", ["a", "b", "c"]);
1215 t!(s: "a/b/d", ["a", "b", "d"]);
1216 t!(s: "a/b/cd", ["a", "b", "cd"]);
1217 t!(s: "/a/b/c", ["a", "b", "c"]);
1222 t!(s: "..", [".."]);
1223 t!(s: "../..", ["..", ".."]);
1224 t!(s: "../../foo", ["..", "..", "foo"]);
1228 fn test_str_components() {
1230 (b: $arg:expr, $exp:expr) => (
1232 let path = Path::new($arg);
1233 let comps = path.str_components().collect::<Vec<Option<&str>>>();
1234 let exp: &[Option<&str>] = $exp;
1235 assert_eq!(comps.as_slice(), exp);
1236 let comps = path.str_components().rev().collect::<Vec<Option<&str>>>();
1237 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<Option<&str>>>();
1238 assert_eq!(comps, exp);
1243 t!(b: b"a/b/c", [Some("a"), Some("b"), Some("c")]);
1244 t!(b: b"/\xFF/a/\x80", [None, Some("a"), None]);
1245 t!(b: b"../../foo\xCDbar", [Some(".."), Some(".."), None]);
1246 // str_components is a wrapper around components, so no need to do
1247 // the full set of tests
1254 use self::test::Bencher;
1259 fn join_home_dir(b: &mut Bencher) {
1260 let posix_path = Path::new("/");
1262 posix_path.join("home");
1267 fn join_abs_path_home_dir(b: &mut Bencher) {
1268 let posix_path = Path::new("/");
1270 posix_path.join("/home");
1275 fn join_many_home_dir(b: &mut Bencher) {
1276 let posix_path = Path::new("/");
1278 posix_path.join_many(&["home"]);
1283 fn join_many_abs_path_home_dir(b: &mut Bencher) {
1284 let posix_path = Path::new("/");
1286 posix_path.join_many(&["/home"]);
1291 fn push_home_dir(b: &mut Bencher) {
1292 let mut posix_path = Path::new("/");
1294 posix_path.push("home");
1299 fn push_abs_path_home_dir(b: &mut Bencher) {
1300 let mut posix_path = Path::new("/");
1302 posix_path.push("/home");
1307 fn push_many_home_dir(b: &mut Bencher) {
1308 let mut posix_path = Path::new("/");
1310 posix_path.push_many(&["home"]);
1315 fn push_many_abs_path_home_dir(b: &mut Bencher) {
1316 let mut posix_path = Path::new("/");
1318 posix_path.push_many(&["/home"]);
1323 fn ends_with_path_home_dir(b: &mut Bencher) {
1324 let posix_home_path = Path::new("/home");
1326 posix_home_path.ends_with_path(&Path::new("home"));
1331 fn ends_with_path_missmatch_jome_home(b: &mut Bencher) {
1332 let posix_home_path = Path::new("/home");
1334 posix_home_path.ends_with_path(&Path::new("jome"));
1339 fn is_ancestor_of_path_with_10_dirs(b: &mut Bencher) {
1340 let path = Path::new("/home/1/2/3/4/5/6/7/8/9");
1341 let mut sub = path.clone();
1344 path.is_ancestor_of(&sub);
1349 fn path_relative_from_forward(b: &mut Bencher) {
1350 let path = Path::new("/a/b/c");
1351 let mut other = path.clone();
1354 path.path_relative_from(&other);
1359 fn path_relative_from_same_level(b: &mut Bencher) {
1360 let path = Path::new("/a/b/c");
1361 let mut other = path.clone();
1365 path.path_relative_from(&other);
1370 fn path_relative_from_backward(b: &mut Bencher) {
1371 let path = Path::new("/a/b");
1372 let mut other = path.clone();
1375 path.path_relative_from(&other);