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};
16 use collections::Collection;
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 ImmutableEqVector, ImmutableVector};
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 FromStr for Path {
72 fn from_str(s: &str) -> Option<Path> {
77 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
78 // we cannot usefully take ToCStr arguments by reference (without forcing an
79 // additional & around &str). So we are instead temporarily adding an instance
80 // for &Path, so that we can take ToCStr as owned. When DST lands, the &Path
81 // instance should be removed, and arguments bound by ToCStr should be passed by
84 impl ToCStr for Path {
86 fn to_c_str(&self) -> CString {
87 // The Path impl guarantees no internal NUL
88 unsafe { self.to_c_str_unchecked() }
92 unsafe fn to_c_str_unchecked(&self) -> CString {
93 self.as_vec().to_c_str_unchecked()
97 impl<'a> ToCStr for &'a Path {
99 fn to_c_str(&self) -> CString {
104 unsafe fn to_c_str_unchecked(&self) -> CString {
105 (*self).to_c_str_unchecked()
109 impl<S: hash::Writer> hash::Hash<S> for Path {
111 fn hash(&self, state: &mut S) {
112 self.repr.hash(state)
116 impl BytesContainer for Path {
118 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
122 fn container_into_owned_bytes(self) -> Vec<u8> {
127 impl<'a> BytesContainer for &'a Path {
129 fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
134 impl GenericPathUnsafe for Path {
135 unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
136 let path = Path::normalize(path.container_as_bytes());
137 assert!(!path.is_empty());
138 let idx = path.as_slice().rposition_elem(&SEP_BYTE);
139 Path{ repr: path, sepidx: idx }
142 unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
143 let filename = filename.container_as_bytes();
145 None if b".." == self.repr.as_slice() => {
146 let mut v = Vec::with_capacity(3 + filename.len());
147 v.push_all(dot_dot_static);
149 v.push_all(filename);
150 // FIXME: this is slow
151 self.repr = Path::normalize(v.as_slice());
154 self.repr = Path::normalize(filename);
156 Some(idx) if self.repr.slice_from(idx+1) == b".." => {
157 let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
158 v.push_all(self.repr.as_slice());
160 v.push_all(filename);
161 // FIXME: this is slow
162 self.repr = Path::normalize(v.as_slice());
165 let mut v = Vec::with_capacity(idx + 1 + filename.len());
166 v.push_all(self.repr.slice_to(idx+1));
167 v.push_all(filename);
168 // FIXME: this is slow
169 self.repr = Path::normalize(v.as_slice());
172 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
175 unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
176 let path = path.container_as_bytes();
177 if !path.is_empty() {
178 if path[0] == SEP_BYTE {
179 self.repr = Path::normalize(path);
181 let mut v = Vec::with_capacity(self.repr.len() + path.len() + 1);
182 v.push_all(self.repr.as_slice());
185 // FIXME: this is slow
186 self.repr = Path::normalize(v.as_slice());
188 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
193 impl GenericPath for Path {
195 fn as_vec<'a>(&'a self) -> &'a [u8] {
199 fn into_vec(self) -> Vec<u8> {
203 fn dirname<'a>(&'a self) -> &'a [u8] {
205 None if b".." == self.repr.as_slice() => self.repr.as_slice(),
207 Some(0) => self.repr.slice_to(1),
208 Some(idx) if self.repr.slice_from(idx+1) == b".." => self.repr.as_slice(),
209 Some(idx) => self.repr.slice_to(idx)
213 fn filename<'a>(&'a self) -> Option<&'a [u8]> {
215 None if b"." == self.repr.as_slice() ||
216 b".." == self.repr.as_slice() => None,
217 None => Some(self.repr.as_slice()),
218 Some(idx) if self.repr.slice_from(idx+1) == b".." => None,
219 Some(0) if self.repr.slice_from(1).is_empty() => None,
220 Some(idx) => Some(self.repr.slice_from(idx+1))
224 fn pop(&mut self) -> bool {
226 None if b"." == self.repr.as_slice() => false,
228 self.repr = vec!['.' as u8];
232 Some(0) if b"/" == self.repr.as_slice() => false,
235 self.repr.truncate(idx+1);
237 self.repr.truncate(idx);
239 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
245 fn root_path(&self) -> Option<Path> {
246 if self.is_absolute() {
254 fn is_absolute(&self) -> bool {
255 *self.repr.get(0) == SEP_BYTE
258 fn is_ancestor_of(&self, other: &Path) -> bool {
259 if self.is_absolute() != other.is_absolute() {
262 let mut ita = self.components();
263 let mut itb = other.components();
264 if b"." == self.repr.as_slice() {
265 return match itb.next() {
267 Some(b) => b != b".."
271 match (ita.next(), itb.next()) {
273 (Some(a), Some(b)) if a == b => { continue },
274 (Some(a), _) if a == b".." => {
275 // if ita contains only .. components, it's an ancestor
276 return ita.all(|x| x == b"..");
285 fn path_relative_from(&self, base: &Path) -> Option<Path> {
286 if self.is_absolute() != base.is_absolute() {
287 if self.is_absolute() {
293 let mut ita = self.components();
294 let mut itb = base.components();
295 let mut comps = vec![];
297 match (ita.next(), itb.next()) {
298 (None, None) => break,
301 comps.extend(ita.by_ref());
304 (None, _) => comps.push(dot_dot_static),
305 (Some(a), Some(b)) if comps.is_empty() && a == b => (),
306 (Some(a), Some(b)) if b == b"." => comps.push(a),
307 (Some(_), Some(b)) if b == b".." => return None,
308 (Some(a), Some(_)) => {
309 comps.push(dot_dot_static);
311 comps.push(dot_dot_static);
314 comps.extend(ita.by_ref());
319 Some(Path::new(comps.as_slice().connect_vec(&SEP_BYTE)))
323 fn ends_with_path(&self, child: &Path) -> bool {
324 if !child.is_relative() { return false; }
325 let mut selfit = self.components().rev();
326 let mut childit = child.components().rev();
328 match (selfit.next(), childit.next()) {
329 (Some(a), Some(b)) => if a != b { return false; },
330 (Some(_), None) => break,
331 (None, Some(_)) => return false,
332 (None, None) => break
340 /// Returns a new Path from a byte vector or string
344 /// Fails the task if the vector contains a NUL.
346 pub fn new<T: BytesContainer>(path: T) -> Path {
347 GenericPath::new(path)
350 /// Returns a new Path from a byte vector or string, if possible
352 pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
353 GenericPath::new_opt(path)
356 /// Returns a normalized byte vector representation of a path, by removing all empty
357 /// components, and unnecessary . and .. components.
358 fn normalize<V: Vector<u8>+CloneableVector<u8>>(v: V) -> Vec<u8> {
359 // borrowck is being very picky
361 let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE;
362 let v_ = if is_abs { v.as_slice().slice_from(1) } else { v.as_slice() };
363 let comps = normalize_helper(v_, is_abs);
367 if is_abs && comps.is_empty() {
370 let n = if is_abs { comps.len() } else { comps.len() - 1} +
371 comps.iter().map(|v| v.len()).sum();
372 let mut v = Vec::with_capacity(n);
373 let mut it = comps.move_iter();
377 Some(comp) => v.push_all(comp)
390 None => Vec::from_slice(v.as_slice()),
395 /// Returns an iterator that yields each component of the path in turn.
396 /// Does not distinguish between absolute and relative paths, e.g.
397 /// /a/b/c and a/b/c yield the same set of components.
398 /// A path of "/" yields no components. A path of "." yields one component.
399 pub fn components<'a>(&'a self) -> Components<'a> {
400 let v = if *self.repr.get(0) == SEP_BYTE {
401 self.repr.slice_from(1)
402 } else { self.repr.as_slice() };
403 let mut ret = v.split(is_sep_byte);
405 // consume the empty "" component
411 /// Returns an iterator that yields each component of the path as Option<&str>.
412 /// See components() for details.
413 pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
414 self.components().map(str::from_utf8)
418 // None result means the byte vector didn't need normalizing
419 fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<Vec<&'a [u8]>> {
420 if is_abs && v.as_slice().is_empty() {
423 let mut comps: Vec<&'a [u8]> = vec![];
425 let mut changed = false;
426 for comp in v.split(is_sep_byte) {
427 if comp.is_empty() { changed = true }
428 else if comp == b"." { changed = true }
429 else if comp == b".." {
430 if is_abs && comps.is_empty() { changed = true }
431 else if comps.len() == n_up { comps.push(dot_dot_static); n_up += 1 }
432 else { comps.pop().unwrap(); changed = true }
433 } else { comps.push(comp) }
436 if comps.is_empty() && !is_abs {
440 comps.push(dot_static);
448 static dot_static: &'static [u8] = b".";
449 static dot_dot_static: &'static [u8] = b"..";
459 (s: $path:expr, $exp:expr) => (
462 assert!(path.as_str() == Some($exp));
465 (v: $path:expr, $exp:expr) => (
468 assert!(path.as_vec() == $exp);
475 let empty: &[u8] = [];
476 t!(v: Path::new(empty), b".");
477 t!(v: Path::new(b"/"), b"/");
478 t!(v: Path::new(b"a/b/c"), b"a/b/c");
479 t!(v: Path::new(b"a/b/c\xFF"), b"a/b/c\xFF");
480 t!(v: Path::new(b"\xFF/../foo\x80"), b"foo\x80");
481 let p = Path::new(b"a/b/c\xFF");
482 assert!(p.as_str() == None);
484 t!(s: Path::new(""), ".");
485 t!(s: Path::new("/"), "/");
486 t!(s: Path::new("hi"), "hi");
487 t!(s: Path::new("hi/"), "hi");
488 t!(s: Path::new("/lib"), "/lib");
489 t!(s: Path::new("/lib/"), "/lib");
490 t!(s: Path::new("hi/there"), "hi/there");
491 t!(s: Path::new("hi/there.txt"), "hi/there.txt");
493 t!(s: Path::new("hi/there/"), "hi/there");
494 t!(s: Path::new("hi/../there"), "there");
495 t!(s: Path::new("../hi/there"), "../hi/there");
496 t!(s: Path::new("/../hi/there"), "/hi/there");
497 t!(s: Path::new("foo/.."), ".");
498 t!(s: Path::new("/foo/.."), "/");
499 t!(s: Path::new("/foo/../.."), "/");
500 t!(s: Path::new("/foo/../../bar"), "/bar");
501 t!(s: Path::new("/./hi/./there/."), "/hi/there");
502 t!(s: Path::new("/./hi/./there/./.."), "/hi");
503 t!(s: Path::new("foo/../.."), "..");
504 t!(s: Path::new("foo/../../.."), "../..");
505 t!(s: Path::new("foo/../../bar"), "../bar");
507 assert_eq!(Path::new(b"foo/bar").into_vec().as_slice(), b"foo/bar");
508 assert_eq!(Path::new(b"/foo/../../bar").into_vec().as_slice(),
511 let p = Path::new(b"foo/bar\x80");
512 assert!(p.as_str() == None);
516 fn test_opt_paths() {
517 assert!(Path::new_opt(b"foo/bar\0") == None);
518 t!(v: Path::new_opt(b"foo/bar").unwrap(), b"foo/bar");
519 assert!(Path::new_opt("foo/bar\0") == None);
520 t!(s: Path::new_opt("foo/bar").unwrap(), "foo/bar");
524 fn test_null_byte() {
526 let result = task::try(proc() {
527 Path::new(b"foo/bar\0")
529 assert!(result.is_err());
531 let result = task::try(proc() {
532 Path::new("test").set_filename(b"f\0o")
534 assert!(result.is_err());
536 let result = task::try(proc() {
537 Path::new("test").push(b"f\0o");
539 assert!(result.is_err());
543 fn test_display_str() {
545 ($path:expr, $disp:ident, $exp:expr) => (
547 let path = Path::new($path);
548 assert!(path.$disp().to_str().as_slice() == $exp);
552 t!("foo", display, "foo");
553 t!(b"foo\x80", display, "foo\uFFFD");
554 t!(b"foo\xFFbar", display, "foo\uFFFDbar");
555 t!(b"foo\xFF/bar", filename_display, "bar");
556 t!(b"foo/\xFFbar", filename_display, "\uFFFDbar");
557 t!(b"/", filename_display, "");
560 ($path:expr, $exp:expr) => (
562 let path = Path::new($path);
563 let mo = path.display().as_maybe_owned();
564 assert!(mo.as_slice() == $exp);
567 ($path:expr, $exp:expr, filename) => (
569 let path = Path::new($path);
570 let mo = path.filename_display().as_maybe_owned();
571 assert!(mo.as_slice() == $exp);
577 t!(b"foo\x80", "foo\uFFFD");
578 t!(b"foo\xFFbar", "foo\uFFFDbar");
579 t!(b"foo\xFF/bar", "bar", filename);
580 t!(b"foo/\xFFbar", "\uFFFDbar", filename);
581 t!(b"/", "", filename);
587 ($path:expr, $exp:expr, $expf:expr) => (
589 let path = Path::new($path);
590 let f = format!("{}", path.display());
591 assert!(f.as_slice() == $exp);
592 let f = format!("{}", path.filename_display());
593 assert!(f.as_slice() == $expf);
598 t!(b"foo", "foo", "foo");
599 t!(b"foo/bar", "foo/bar", "bar");
601 t!(b"foo\xFF", "foo\uFFFD", "foo\uFFFD");
602 t!(b"foo\xFF/bar", "foo\uFFFD/bar", "bar");
603 t!(b"foo/\xFFbar", "foo/\uFFFDbar", "\uFFFDbar");
604 t!(b"\xFFfoo/bar\xFF", "\uFFFDfoo/bar\uFFFD", "bar\uFFFD");
608 fn test_components() {
610 (s: $path:expr, $op:ident, $exp:expr) => (
612 let path = Path::new($path);
613 assert!(path.$op() == ($exp).as_bytes());
616 (s: $path:expr, $op:ident, $exp:expr, opt) => (
618 let path = Path::new($path);
619 let left = path.$op().map(|x| str::from_utf8(x).unwrap());
620 assert!(left == $exp);
623 (v: $path:expr, $op:ident, $exp:expr) => (
626 let path = Path::new(arg);
627 assert!(path.$op() == $exp);
632 t!(v: b"a/b/c", filename, Some(b"c"));
633 t!(v: b"a/b/c\xFF", filename, Some(b"c\xFF"));
634 t!(v: b"a/b\xFF/c", filename, Some(b"c"));
635 t!(s: "a/b/c", filename, Some("c"), opt);
636 t!(s: "/a/b/c", filename, Some("c"), opt);
637 t!(s: "a", filename, Some("a"), opt);
638 t!(s: "/a", filename, Some("a"), opt);
639 t!(s: ".", filename, None, opt);
640 t!(s: "/", filename, None, opt);
641 t!(s: "..", filename, None, opt);
642 t!(s: "../..", filename, None, opt);
644 t!(v: b"a/b/c", dirname, b"a/b");
645 t!(v: b"a/b/c\xFF", dirname, b"a/b");
646 t!(v: b"a/b\xFF/c", dirname, b"a/b\xFF");
647 t!(s: "a/b/c", dirname, "a/b");
648 t!(s: "/a/b/c", dirname, "/a/b");
649 t!(s: "a", dirname, ".");
650 t!(s: "/a", dirname, "/");
651 t!(s: ".", dirname, ".");
652 t!(s: "/", dirname, "/");
653 t!(s: "..", dirname, "..");
654 t!(s: "../..", dirname, "../..");
656 t!(v: b"hi/there.txt", filestem, Some(b"there"));
657 t!(v: b"hi/there\x80.txt", filestem, Some(b"there\x80"));
658 t!(v: b"hi/there.t\x80xt", filestem, Some(b"there"));
659 t!(s: "hi/there.txt", filestem, Some("there"), opt);
660 t!(s: "hi/there", filestem, Some("there"), opt);
661 t!(s: "there.txt", filestem, Some("there"), opt);
662 t!(s: "there", filestem, Some("there"), opt);
663 t!(s: ".", filestem, None, opt);
664 t!(s: "/", filestem, None, opt);
665 t!(s: "foo/.bar", filestem, Some(".bar"), opt);
666 t!(s: ".bar", filestem, Some(".bar"), opt);
667 t!(s: "..bar", filestem, Some("."), opt);
668 t!(s: "hi/there..txt", filestem, Some("there."), opt);
669 t!(s: "..", filestem, None, opt);
670 t!(s: "../..", filestem, None, opt);
672 t!(v: b"hi/there.txt", extension, Some(b"txt"));
673 t!(v: b"hi/there\x80.txt", extension, Some(b"txt"));
674 t!(v: b"hi/there.t\x80xt", extension, Some(b"t\x80xt"));
675 t!(v: b"hi/there", extension, None);
676 t!(v: b"hi/there\x80", extension, None);
677 t!(s: "hi/there.txt", extension, Some("txt"), opt);
678 t!(s: "hi/there", extension, None, opt);
679 t!(s: "there.txt", extension, Some("txt"), opt);
680 t!(s: "there", extension, None, opt);
681 t!(s: ".", extension, None, opt);
682 t!(s: "/", extension, None, opt);
683 t!(s: "foo/.bar", extension, None, opt);
684 t!(s: ".bar", extension, None, opt);
685 t!(s: "..bar", extension, Some("bar"), opt);
686 t!(s: "hi/there..txt", extension, Some("txt"), opt);
687 t!(s: "..", extension, None, opt);
688 t!(s: "../..", extension, None, opt);
694 (s: $path:expr, $join:expr) => (
698 let mut p1 = Path::new(path);
701 assert!(p1 == p2.join(join));
706 t!(s: "a/b/c", "..");
707 t!(s: "/a/b/c", "d");
709 t!(s: "a/b", "/c/d");
713 fn test_push_path() {
715 (s: $path:expr, $push:expr, $exp:expr) => (
717 let mut p = Path::new($path);
718 let push = Path::new($push);
720 assert!(p.as_str() == Some($exp));
725 t!(s: "a/b/c", "d", "a/b/c/d");
726 t!(s: "/a/b/c", "d", "/a/b/c/d");
727 t!(s: "a/b", "c/d", "a/b/c/d");
728 t!(s: "a/b", "/c/d", "/c/d");
729 t!(s: "a/b", ".", "a/b");
730 t!(s: "a/b", "../c", "a/c");
734 fn test_push_many() {
736 (s: $path:expr, $push:expr, $exp:expr) => (
738 let mut p = Path::new($path);
740 assert!(p.as_str() == Some($exp));
743 (v: $path:expr, $push:expr, $exp:expr) => (
745 let mut p = Path::new($path);
747 assert!(p.as_vec() == $exp);
752 t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
753 t!(s: "a/b/c", ["d", "/e"], "/e");
754 t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
755 t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
756 t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
757 t!(v: b"a/b/c", [b"d", b"/e", b"f"], b"/e/f");
758 t!(v: b"a/b/c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")], b"a/b/c/d/e");
764 (s: $path:expr, $left:expr, $right:expr) => (
766 let mut p = Path::new($path);
767 let result = p.pop();
768 assert!(p.as_str() == Some($left));
769 assert!(result == $right);
772 (b: $path:expr, $left:expr, $right:expr) => (
774 let mut p = Path::new($path);
775 let result = p.pop();
776 assert!(p.as_vec() == $left);
777 assert!(result == $right);
782 t!(b: b"a/b/c", b"a/b", true);
783 t!(b: b"a", b".", true);
784 t!(b: b".", b".", false);
785 t!(b: b"/a", b"/", true);
786 t!(b: b"/", b"/", false);
787 t!(b: b"a/b/c\x80", b"a/b", true);
788 t!(b: b"a/b\x80/c", b"a/b\x80", true);
789 t!(b: b"\xFF", b".", true);
790 t!(b: b"/\xFF", b"/", true);
791 t!(s: "a/b/c", "a/b", true);
792 t!(s: "a", ".", true);
793 t!(s: ".", ".", false);
794 t!(s: "/a", "/", true);
795 t!(s: "/", "/", false);
799 fn test_root_path() {
800 assert!(Path::new(b"a/b/c").root_path() == None);
801 assert!(Path::new(b"/a/b/c").root_path() == Some(Path::new("/")));
806 t!(v: Path::new(b"a/b/c").join(b".."), b"a/b");
807 t!(v: Path::new(b"/a/b/c").join(b"d"), b"/a/b/c/d");
808 t!(v: Path::new(b"a/\x80/c").join(b"\xFF"), b"a/\x80/c/\xFF");
809 t!(s: Path::new("a/b/c").join(".."), "a/b");
810 t!(s: Path::new("/a/b/c").join("d"), "/a/b/c/d");
811 t!(s: Path::new("a/b").join("c/d"), "a/b/c/d");
812 t!(s: Path::new("a/b").join("/c/d"), "/c/d");
813 t!(s: Path::new(".").join("a/b"), "a/b");
814 t!(s: Path::new("/").join("a/b"), "/a/b");
818 fn test_join_path() {
820 (s: $path:expr, $join:expr, $exp:expr) => (
822 let path = Path::new($path);
823 let join = Path::new($join);
824 let res = path.join(&join);
825 assert!(res.as_str() == Some($exp));
830 t!(s: "a/b/c", "..", "a/b");
831 t!(s: "/a/b/c", "d", "/a/b/c/d");
832 t!(s: "a/b", "c/d", "a/b/c/d");
833 t!(s: "a/b", "/c/d", "/c/d");
834 t!(s: ".", "a/b", "a/b");
835 t!(s: "/", "a/b", "/a/b");
839 fn test_join_many() {
841 (s: $path:expr, $join:expr, $exp:expr) => (
843 let path = Path::new($path);
844 let res = path.join_many($join);
845 assert!(res.as_str() == Some($exp));
848 (v: $path:expr, $join:expr, $exp:expr) => (
850 let path = Path::new($path);
851 let res = path.join_many($join);
852 assert!(res.as_vec() == $exp);
857 t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
858 t!(s: "a/b/c", ["..", "d"], "a/b/d");
859 t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
860 t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
861 t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
862 t!(v: b"a/b/c", [Vec::from_slice(b"d"), Vec::from_slice(b"e")], b"a/b/c/d/e");
866 fn test_with_helpers() {
867 let empty: &[u8] = [];
869 t!(v: Path::new(b"a/b/c").with_filename(b"d"), b"a/b/d");
870 t!(v: Path::new(b"a/b/c\xFF").with_filename(b"\x80"), b"a/b/\x80");
871 t!(v: Path::new(b"/\xFF/foo").with_filename(b"\xCD"),
873 t!(s: Path::new("a/b/c").with_filename("d"), "a/b/d");
874 t!(s: Path::new(".").with_filename("foo"), "foo");
875 t!(s: Path::new("/a/b/c").with_filename("d"), "/a/b/d");
876 t!(s: Path::new("/").with_filename("foo"), "/foo");
877 t!(s: Path::new("/a").with_filename("foo"), "/foo");
878 t!(s: Path::new("foo").with_filename("bar"), "bar");
879 t!(s: Path::new("/").with_filename("foo/"), "/foo");
880 t!(s: Path::new("/a").with_filename("foo/"), "/foo");
881 t!(s: Path::new("a/b/c").with_filename(""), "a/b");
882 t!(s: Path::new("a/b/c").with_filename("."), "a/b");
883 t!(s: Path::new("a/b/c").with_filename(".."), "a");
884 t!(s: Path::new("/a").with_filename(""), "/");
885 t!(s: Path::new("foo").with_filename(""), ".");
886 t!(s: Path::new("a/b/c").with_filename("d/e"), "a/b/d/e");
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("../..").with_filename("foo"), "../../foo");
890 t!(s: Path::new("..").with_filename(""), "..");
891 t!(s: Path::new("../..").with_filename(""), "../..");
893 t!(v: Path::new(b"hi/there\x80.txt").with_extension(b"exe"),
894 b"hi/there\x80.exe");
895 t!(v: Path::new(b"hi/there.txt\x80").with_extension(b"\xFF"),
897 t!(v: Path::new(b"hi/there\x80").with_extension(b"\xFF"),
898 b"hi/there\x80.\xFF");
899 t!(v: Path::new(b"hi/there.\xFF").with_extension(empty), b"hi/there");
900 t!(s: Path::new("hi/there.txt").with_extension("exe"), "hi/there.exe");
901 t!(s: Path::new("hi/there.txt").with_extension(""), "hi/there");
902 t!(s: Path::new("hi/there.txt").with_extension("."), "hi/there..");
903 t!(s: Path::new("hi/there.txt").with_extension(".."), "hi/there...");
904 t!(s: Path::new("hi/there").with_extension("txt"), "hi/there.txt");
905 t!(s: Path::new("hi/there").with_extension("."), "hi/there..");
906 t!(s: Path::new("hi/there").with_extension(".."), "hi/there...");
907 t!(s: Path::new("hi/there.").with_extension("txt"), "hi/there.txt");
908 t!(s: Path::new("hi/.foo").with_extension("txt"), "hi/.foo.txt");
909 t!(s: Path::new("hi/there.txt").with_extension(".foo"), "hi/there..foo");
910 t!(s: Path::new("/").with_extension("txt"), "/");
911 t!(s: Path::new("/").with_extension("."), "/");
912 t!(s: Path::new("/").with_extension(".."), "/");
913 t!(s: Path::new(".").with_extension("txt"), ".");
919 (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
923 let mut p1 = Path::new(path);
925 let p2 = Path::new(path);
926 assert!(p1 == p2.$with(arg));
929 (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
933 let mut p1 = Path::new(path);
935 let p2 = Path::new(path);
936 assert!(p1 == p2.$with(arg));
941 t!(v: b"a/b/c", set_filename, with_filename, b"d");
942 t!(v: b"/", set_filename, with_filename, b"foo");
943 t!(v: b"\x80", set_filename, with_filename, b"\xFF");
944 t!(s: "a/b/c", set_filename, with_filename, "d");
945 t!(s: "/", set_filename, with_filename, "foo");
946 t!(s: ".", set_filename, with_filename, "foo");
947 t!(s: "a/b", set_filename, with_filename, "");
948 t!(s: "a", set_filename, with_filename, "");
950 t!(v: b"hi/there.txt", set_extension, with_extension, b"exe");
951 t!(v: b"hi/there.t\x80xt", set_extension, with_extension, b"exe\xFF");
952 t!(s: "hi/there.txt", set_extension, with_extension, "exe");
953 t!(s: "hi/there.", set_extension, with_extension, "txt");
954 t!(s: "hi/there", set_extension, with_extension, "txt");
955 t!(s: "hi/there.txt", set_extension, with_extension, "");
956 t!(s: "hi/there", set_extension, with_extension, "");
957 t!(s: ".", set_extension, with_extension, "txt");
963 (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
966 let filename = $filename;
967 assert!(path.filename_str() == filename,
968 "{}.filename_str(): Expected `{:?}`, found {:?}",
969 path.as_str().unwrap(), filename, path.filename_str());
970 let dirname = $dirname;
971 assert!(path.dirname_str() == dirname,
972 "`{}`.dirname_str(): Expected `{:?}`, found `{:?}`",
973 path.as_str().unwrap(), dirname, path.dirname_str());
974 let filestem = $filestem;
975 assert!(path.filestem_str() == filestem,
976 "`{}`.filestem_str(): Expected `{:?}`, found `{:?}`",
977 path.as_str().unwrap(), filestem, path.filestem_str());
979 assert!(path.extension_str() == ext,
980 "`{}`.extension_str(): Expected `{:?}`, found `{:?}`",
981 path.as_str().unwrap(), ext, path.extension_str());
984 (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
987 assert!(path.filename() == $filename);
988 assert!(path.dirname() == $dirname);
989 assert!(path.filestem() == $filestem);
990 assert!(path.extension() == $ext);
995 t!(v: Path::new(b"a/b/c"), Some(b"c"), b"a/b", Some(b"c"), None);
996 t!(v: Path::new(b"a/b/\xFF"), Some(b"\xFF"), b"a/b", Some(b"\xFF"), None);
997 t!(v: Path::new(b"hi/there.\xFF"), Some(b"there.\xFF"), b"hi",
998 Some(b"there"), Some(b"\xFF"));
999 t!(s: Path::new("a/b/c"), Some("c"), Some("a/b"), Some("c"), None);
1000 t!(s: Path::new("."), None, Some("."), None, None);
1001 t!(s: Path::new("/"), None, Some("/"), None, None);
1002 t!(s: Path::new(".."), None, Some(".."), None, None);
1003 t!(s: Path::new("../.."), None, Some("../.."), None, None);
1004 t!(s: Path::new("hi/there.txt"), Some("there.txt"), Some("hi"),
1005 Some("there"), Some("txt"));
1006 t!(s: Path::new("hi/there"), Some("there"), Some("hi"), Some("there"), None);
1007 t!(s: Path::new("hi/there."), Some("there."), Some("hi"),
1008 Some("there"), Some(""));
1009 t!(s: Path::new("hi/.there"), Some(".there"), Some("hi"), Some(".there"), None);
1010 t!(s: Path::new("hi/..there"), Some("..there"), Some("hi"),
1011 Some("."), Some("there"));
1012 t!(s: Path::new(b"a/b/\xFF"), None, Some("a/b"), None, None);
1013 t!(s: Path::new(b"a/b/\xFF.txt"), None, Some("a/b"), None, Some("txt"));
1014 t!(s: Path::new(b"a/b/c.\x80"), None, Some("a/b"), Some("c"), None);
1015 t!(s: Path::new(b"\xFF/b"), Some("b"), None, Some("b"), None);
1019 fn test_dir_path() {
1020 t!(v: Path::new(b"hi/there\x80").dir_path(), b"hi");
1021 t!(v: Path::new(b"hi\xFF/there").dir_path(), b"hi\xFF");
1022 t!(s: Path::new("hi/there").dir_path(), "hi");
1023 t!(s: Path::new("hi").dir_path(), ".");
1024 t!(s: Path::new("/hi").dir_path(), "/");
1025 t!(s: Path::new("/").dir_path(), "/");
1026 t!(s: Path::new("..").dir_path(), "..");
1027 t!(s: Path::new("../..").dir_path(), "../..");
1031 fn test_is_absolute() {
1033 (s: $path:expr, $abs:expr, $rel:expr) => (
1035 let path = Path::new($path);
1036 assert_eq!(path.is_absolute(), $abs);
1037 assert_eq!(path.is_relative(), $rel);
1041 t!(s: "a/b/c", false, true);
1042 t!(s: "/a/b/c", true, false);
1043 t!(s: "a", false, true);
1044 t!(s: "/a", true, false);
1045 t!(s: ".", false, true);
1046 t!(s: "/", true, false);
1047 t!(s: "..", false, true);
1048 t!(s: "../..", false, true);
1052 fn test_is_ancestor_of() {
1054 (s: $path:expr, $dest:expr, $exp:expr) => (
1056 let path = Path::new($path);
1057 let dest = Path::new($dest);
1058 assert_eq!(path.is_ancestor_of(&dest), $exp);
1063 t!(s: "a/b/c", "a/b/c/d", true);
1064 t!(s: "a/b/c", "a/b/c", true);
1065 t!(s: "a/b/c", "a/b", false);
1066 t!(s: "/a/b/c", "/a/b/c", true);
1067 t!(s: "/a/b", "/a/b/c", true);
1068 t!(s: "/a/b/c/d", "/a/b/c", false);
1069 t!(s: "/a/b", "a/b/c", false);
1070 t!(s: "a/b", "/a/b/c", false);
1071 t!(s: "a/b/c", "a/b/d", false);
1072 t!(s: "../a/b/c", "a/b/c", false);
1073 t!(s: "a/b/c", "../a/b/c", false);
1074 t!(s: "a/b/c", "a/b/cd", false);
1075 t!(s: "a/b/cd", "a/b/c", false);
1076 t!(s: "../a/b", "../a/b/c", true);
1077 t!(s: ".", "a/b", true);
1078 t!(s: ".", ".", true);
1079 t!(s: "/", "/", true);
1080 t!(s: "/", "/a/b", true);
1081 t!(s: "..", "a/b", true);
1082 t!(s: "../..", "a/b", true);
1086 fn test_ends_with_path() {
1088 (s: $path:expr, $child:expr, $exp:expr) => (
1090 let path = Path::new($path);
1091 let child = Path::new($child);
1092 assert_eq!(path.ends_with_path(&child), $exp);
1095 (v: $path:expr, $child:expr, $exp:expr) => (
1097 let path = Path::new($path);
1098 let child = Path::new($child);
1099 assert_eq!(path.ends_with_path(&child), $exp);
1104 t!(s: "a/b/c", "c", true);
1105 t!(s: "a/b/c", "d", false);
1106 t!(s: "foo/bar/quux", "bar", false);
1107 t!(s: "foo/bar/quux", "barquux", false);
1108 t!(s: "a/b/c", "b/c", true);
1109 t!(s: "a/b/c", "a/b/c", true);
1110 t!(s: "a/b/c", "foo/a/b/c", false);
1111 t!(s: "/a/b/c", "a/b/c", true);
1112 t!(s: "/a/b/c", "/a/b/c", false); // child must be relative
1113 t!(s: "/a/b/c", "foo/a/b/c", false);
1114 t!(s: "a/b/c", "", false);
1115 t!(s: "", "", true);
1116 t!(s: "/a/b/c", "d/e/f", false);
1117 t!(s: "a/b/c", "a/b", false);
1118 t!(s: "a/b/c", "b", false);
1119 t!(v: b"a/b/c", b"b/c", true);
1120 t!(v: b"a/b/\xFF", b"\xFF", true);
1121 t!(v: b"a/b/\xFF", b"b/\xFF", true);
1125 fn test_path_relative_from() {
1127 (s: $path:expr, $other:expr, $exp:expr) => (
1129 let path = Path::new($path);
1130 let other = Path::new($other);
1131 let res = path.path_relative_from(&other);
1132 assert_eq!(res.as_ref().and_then(|x| x.as_str()), $exp);
1137 t!(s: "a/b/c", "a/b", Some("c"));
1138 t!(s: "a/b/c", "a/b/d", Some("../c"));
1139 t!(s: "a/b/c", "a/b/c/d", Some(".."));
1140 t!(s: "a/b/c", "a/b/c", Some("."));
1141 t!(s: "a/b/c", "a/b/c/d/e", Some("../.."));
1142 t!(s: "a/b/c", "a/d/e", Some("../../b/c"));
1143 t!(s: "a/b/c", "d/e/f", Some("../../../a/b/c"));
1144 t!(s: "a/b/c", "/a/b/c", None);
1145 t!(s: "/a/b/c", "a/b/c", Some("/a/b/c"));
1146 t!(s: "/a/b/c", "/a/b/c/d", Some(".."));
1147 t!(s: "/a/b/c", "/a/b", Some("c"));
1148 t!(s: "/a/b/c", "/a/b/c/d/e", Some("../.."));
1149 t!(s: "/a/b/c", "/a/d/e", Some("../../b/c"));
1150 t!(s: "/a/b/c", "/d/e/f", Some("../../../a/b/c"));
1151 t!(s: "hi/there.txt", "hi/there", Some("../there.txt"));
1152 t!(s: ".", "a", Some(".."));
1153 t!(s: ".", "a/b", Some("../.."));
1154 t!(s: ".", ".", Some("."));
1155 t!(s: "a", ".", Some("a"));
1156 t!(s: "a/b", ".", Some("a/b"));
1157 t!(s: "..", ".", Some(".."));
1158 t!(s: "a/b/c", "a/b/c", Some("."));
1159 t!(s: "/a/b/c", "/a/b/c", Some("."));
1160 t!(s: "/", "/", Some("."));
1161 t!(s: "/", ".", Some("/"));
1162 t!(s: "../../a", "b", Some("../../../a"));
1163 t!(s: "a", "../../b", None);
1164 t!(s: "../../a", "../../b", Some("../a"));
1165 t!(s: "../../a", "../../a/b", Some(".."));
1166 t!(s: "../../a/b", "../../a", Some("b"));
1170 fn test_components_iter() {
1172 (s: $path:expr, $exp:expr) => (
1174 let path = Path::new($path);
1175 let comps = path.components().collect::<Vec<&[u8]>>();
1176 let exp: &[&str] = $exp;
1177 let exps = exp.iter().map(|x| x.as_bytes()).collect::<Vec<&[u8]>>();
1178 assert!(comps == exps, "components: Expected {:?}, found {:?}",
1180 let comps = path.components().rev().collect::<Vec<&[u8]>>();
1181 let exps = exps.move_iter().rev().collect::<Vec<&[u8]>>();
1182 assert!(comps == exps, "rev_components: Expected {:?}, found {:?}",
1186 (b: $arg:expr, [$($exp:expr),*]) => (
1188 let path = Path::new($arg);
1189 let comps = path.components().collect::<Vec<&[u8]>>();
1190 let exp: &[&[u8]] = [$($exp),*];
1191 assert_eq!(comps.as_slice(), exp);
1192 let comps = path.components().rev().collect::<Vec<&[u8]>>();
1193 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
1194 assert_eq!(comps, exp)
1199 t!(b: b"a/b/c", [b"a", b"b", b"c"]);
1200 t!(b: b"/\xFF/a/\x80", [b"\xFF", b"a", b"\x80"]);
1201 t!(b: b"../../foo\xCDbar", [b"..", b"..", b"foo\xCDbar"]);
1202 t!(s: "a/b/c", ["a", "b", "c"]);
1203 t!(s: "a/b/d", ["a", "b", "d"]);
1204 t!(s: "a/b/cd", ["a", "b", "cd"]);
1205 t!(s: "/a/b/c", ["a", "b", "c"]);
1210 t!(s: "..", [".."]);
1211 t!(s: "../..", ["..", ".."]);
1212 t!(s: "../../foo", ["..", "..", "foo"]);
1216 fn test_str_components() {
1218 (b: $arg:expr, $exp:expr) => (
1220 let path = Path::new($arg);
1221 let comps = path.str_components().collect::<Vec<Option<&str>>>();
1222 let exp: &[Option<&str>] = $exp;
1223 assert_eq!(comps.as_slice(), exp);
1224 let comps = path.str_components().rev().collect::<Vec<Option<&str>>>();
1225 let exp = exp.iter().rev().map(|&x|x).collect::<Vec<Option<&str>>>();
1226 assert_eq!(comps, exp);
1231 t!(b: b"a/b/c", [Some("a"), Some("b"), Some("c")]);
1232 t!(b: b"/\xFF/a/\x80", [None, Some("a"), None]);
1233 t!(b: b"../../foo\xCDbar", [Some(".."), Some(".."), None]);
1234 // str_components is a wrapper around components, so no need to do
1235 // the full set of tests
1242 use self::test::Bencher;
1247 fn join_home_dir(b: &mut Bencher) {
1248 let posix_path = Path::new("/");
1250 posix_path.join("home");
1255 fn join_abs_path_home_dir(b: &mut Bencher) {
1256 let posix_path = Path::new("/");
1258 posix_path.join("/home");
1263 fn join_many_home_dir(b: &mut Bencher) {
1264 let posix_path = Path::new("/");
1266 posix_path.join_many(&["home"]);
1271 fn join_many_abs_path_home_dir(b: &mut Bencher) {
1272 let posix_path = Path::new("/");
1274 posix_path.join_many(&["/home"]);
1279 fn push_home_dir(b: &mut Bencher) {
1280 let mut posix_path = Path::new("/");
1282 posix_path.push("home");
1287 fn push_abs_path_home_dir(b: &mut Bencher) {
1288 let mut posix_path = Path::new("/");
1290 posix_path.push("/home");
1295 fn push_many_home_dir(b: &mut Bencher) {
1296 let mut posix_path = Path::new("/");
1298 posix_path.push_many(&["home"]);
1303 fn push_many_abs_path_home_dir(b: &mut Bencher) {
1304 let mut posix_path = Path::new("/");
1306 posix_path.push_many(&["/home"]);
1311 fn ends_with_path_home_dir(b: &mut Bencher) {
1312 let posix_home_path = Path::new("/home");
1314 posix_home_path.ends_with_path(&Path::new("home"));
1319 fn ends_with_path_missmatch_jome_home(b: &mut Bencher) {
1320 let posix_home_path = Path::new("/home");
1322 posix_home_path.ends_with_path(&Path::new("jome"));
1327 fn is_ancestor_of_path_with_10_dirs(b: &mut Bencher) {
1328 let path = Path::new("/home/1/2/3/4/5/6/7/8/9");
1329 let mut sub = path.clone();
1332 path.is_ancestor_of(&sub);
1337 fn path_relative_from_forward(b: &mut Bencher) {
1338 let path = Path::new("/a/b/c");
1339 let mut other = path.clone();
1342 path.path_relative_from(&other);
1347 fn path_relative_from_same_level(b: &mut Bencher) {
1348 let path = Path::new("/a/b/c");
1349 let mut other = path.clone();
1353 path.path_relative_from(&other);
1358 fn path_relative_from_backward(b: &mut Bencher) {
1359 let path = Path::new("/a/b");
1360 let mut other = path.clone();
1363 path.path_relative_from(&other);