]> git.lizzy.rs Git - rust.git/blob - src/libstd/path/posix.rs
std: Rename slice::Vector to Slice
[rust.git] / src / libstd / path / posix.rs
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.
4 //
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.
10
11 //! POSIX file path handling
12
13 use c_str::{CString, ToCStr};
14 use clone::Clone;
15 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
16 use collections::{Collection, MutableSeq};
17 use from_str::FromStr;
18 use hash;
19 use io::Writer;
20 use iter::{DoubleEndedIterator, AdditiveIterator, Extendable, Iterator, Map};
21 use option::{Option, None, Some};
22 use str::Str;
23 use str;
24 use slice::{CloneableVector, Splits, Slice, VectorVector,
25             ImmutableEqSlice, ImmutableSlice};
26 use vec::Vec;
27
28 use super::{BytesContainer, GenericPath, GenericPathUnsafe};
29
30 /// Iterator that yields successive components of a Path as &[u8]
31 pub type Components<'a> = Splits<'a, u8>;
32
33 /// Iterator that yields successive components of a Path as Option<&str>
34 pub type StrComponents<'a> = Map<'a, &'a [u8], Option<&'a str>,
35                                        Components<'a>>;
36
37 /// Represents a POSIX file path
38 #[deriving(Clone)]
39 pub struct Path {
40     repr: Vec<u8>, // assumed to never be empty or contain NULs
41     sepidx: Option<uint> // index of the final separator in repr
42 }
43
44 /// The standard path separator character
45 pub static SEP: char = '/';
46
47 /// The standard path separator byte
48 pub static SEP_BYTE: u8 = SEP as u8;
49
50 /// Returns whether the given byte is a path separator
51 #[inline]
52 pub fn is_sep_byte(u: &u8) -> bool {
53     *u as char == SEP
54 }
55
56 /// Returns whether the given char is a path separator
57 #[inline]
58 pub fn is_sep(c: char) -> bool {
59     c == SEP
60 }
61
62 impl PartialEq for Path {
63     #[inline]
64     fn eq(&self, other: &Path) -> bool {
65         self.repr == other.repr
66     }
67 }
68
69 impl Eq for Path {}
70
71 impl PartialOrd for Path {
72     fn partial_cmp(&self, other: &Path) -> Option<Ordering> {
73         Some(self.cmp(other))
74     }
75 }
76
77 impl Ord for Path {
78     fn cmp(&self, other: &Path) -> Ordering {
79         self.repr.cmp(&other.repr)
80     }
81 }
82
83 impl FromStr for Path {
84     fn from_str(s: &str) -> Option<Path> {
85         Path::new_opt(s)
86     }
87 }
88
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
94 // reference.
95
96 impl ToCStr for Path {
97     #[inline]
98     fn to_c_str(&self) -> CString {
99         // The Path impl guarantees no internal NUL
100         unsafe { self.to_c_str_unchecked() }
101     }
102
103     #[inline]
104     unsafe fn to_c_str_unchecked(&self) -> CString {
105         self.as_vec().to_c_str_unchecked()
106     }
107 }
108
109 impl<'a> ToCStr for &'a Path {
110     #[inline]
111     fn to_c_str(&self) -> CString {
112         (*self).to_c_str()
113     }
114
115     #[inline]
116     unsafe fn to_c_str_unchecked(&self) -> CString {
117         (*self).to_c_str_unchecked()
118     }
119 }
120
121 impl<S: hash::Writer> hash::Hash<S> for Path {
122     #[inline]
123     fn hash(&self, state: &mut S) {
124         self.repr.hash(state)
125     }
126 }
127
128 impl BytesContainer for Path {
129     #[inline]
130     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
131         self.as_vec()
132     }
133     #[inline]
134     fn container_into_owned_bytes(self) -> Vec<u8> {
135         self.into_vec()
136     }
137 }
138
139 impl<'a> BytesContainer for &'a Path {
140     #[inline]
141     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
142         self.as_vec()
143     }
144 }
145
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 }
152     }
153
154     unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
155         let filename = filename.container_as_bytes();
156         match self.sepidx {
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);
160                 v.push(SEP_BYTE);
161                 v.push_all(filename);
162                 // FIXME: this is slow
163                 self.repr = Path::normalize(v.as_slice());
164             }
165             None => {
166                 self.repr = Path::normalize(filename);
167             }
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());
171                 v.push(SEP_BYTE);
172                 v.push_all(filename);
173                 // FIXME: this is slow
174                 self.repr = Path::normalize(v.as_slice());
175             }
176             Some(idx) => {
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());
182             }
183         }
184         self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
185     }
186
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);
192             }  else {
193                 let mut v = Vec::with_capacity(self.repr.len() + path.len() + 1);
194                 v.push_all(self.repr.as_slice());
195                 v.push(SEP_BYTE);
196                 v.push_all(path);
197                 // FIXME: this is slow
198                 self.repr = Path::normalize(v.as_slice());
199             }
200             self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
201         }
202     }
203 }
204
205 impl GenericPath for Path {
206     #[inline]
207     fn as_vec<'a>(&'a self) -> &'a [u8] {
208         self.repr.as_slice()
209     }
210
211     fn into_vec(self) -> Vec<u8> {
212         self.repr
213     }
214
215     fn dirname<'a>(&'a self) -> &'a [u8] {
216         match self.sepidx {
217             None if b".." == self.repr.as_slice() => self.repr.as_slice(),
218             None => dot_static,
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)
222         }
223     }
224
225     fn filename<'a>(&'a self) -> Option<&'a [u8]> {
226         match self.sepidx {
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))
233         }
234     }
235
236     fn pop(&mut self) -> bool {
237         match self.sepidx {
238             None if b"." == self.repr.as_slice() => false,
239             None => {
240                 self.repr = vec![b'.'];
241                 self.sepidx = None;
242                 true
243             }
244             Some(0) if b"/" == self.repr.as_slice() => false,
245             Some(idx) => {
246                 if idx == 0 {
247                     self.repr.truncate(idx+1);
248                 } else {
249                     self.repr.truncate(idx);
250                 }
251                 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
252                 true
253             }
254         }
255     }
256
257     fn root_path(&self) -> Option<Path> {
258         if self.is_absolute() {
259             Some(Path::new("/"))
260         } else {
261             None
262         }
263     }
264
265     #[inline]
266     fn is_absolute(&self) -> bool {
267         *self.repr.get(0) == SEP_BYTE
268     }
269
270     fn is_ancestor_of(&self, other: &Path) -> bool {
271         if self.is_absolute() != other.is_absolute() {
272             false
273         } else {
274             let mut ita = self.components();
275             let mut itb = other.components();
276             if b"." == self.repr.as_slice() {
277                 return match itb.next() {
278                     None => true,
279                     Some(b) => b != b".."
280                 };
281             }
282             loop {
283                 match (ita.next(), itb.next()) {
284                     (None, _) => break,
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"..");
289                     }
290                     _ => return false
291                 }
292             }
293             true
294         }
295     }
296
297     fn path_relative_from(&self, base: &Path) -> Option<Path> {
298         if self.is_absolute() != base.is_absolute() {
299             if self.is_absolute() {
300                 Some(self.clone())
301             } else {
302                 None
303             }
304         } else {
305             let mut ita = self.components();
306             let mut itb = base.components();
307             let mut comps = vec![];
308             loop {
309                 match (ita.next(), itb.next()) {
310                     (None, None) => break,
311                     (Some(a), None) => {
312                         comps.push(a);
313                         comps.extend(ita.by_ref());
314                         break;
315                     }
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);
322                         for _ in itb {
323                             comps.push(dot_dot_static);
324                         }
325                         comps.push(a);
326                         comps.extend(ita.by_ref());
327                         break;
328                     }
329                 }
330             }
331             Some(Path::new(comps.as_slice().connect_vec(&SEP_BYTE)))
332         }
333     }
334
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();
339         loop {
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
345             }
346         }
347         true
348     }
349 }
350
351 impl Path {
352     /// Returns a new Path from a byte vector or string
353     ///
354     /// # Failure
355     ///
356     /// Fails the task if the vector contains a NUL.
357     #[inline]
358     pub fn new<T: BytesContainer>(path: T) -> Path {
359         GenericPath::new(path)
360     }
361
362     /// Returns a new Path from a byte vector or string, if possible
363     #[inline]
364     pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
365         GenericPath::new_opt(path)
366     }
367
368     /// Returns a normalized byte vector representation of a path, by removing all empty
369     /// components, and unnecessary . and .. components.
370     fn normalize<V: Slice<u8>+CloneableVector<u8>>(v: V) -> Vec<u8> {
371         // borrowck is being very picky
372         let val = {
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);
376             match comps {
377                 None => None,
378                 Some(comps) => {
379                     if is_abs && comps.is_empty() {
380                         Some(vec![SEP_BYTE])
381                     } else {
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();
386                         if !is_abs {
387                             match it.next() {
388                                 None => (),
389                                 Some(comp) => v.push_all(comp)
390                             }
391                         }
392                         for comp in it {
393                             v.push(SEP_BYTE);
394                             v.push_all(comp);
395                         }
396                         Some(v)
397                     }
398                 }
399             }
400         };
401         match val {
402             None => Vec::from_slice(v.as_slice()),
403             Some(val) => val
404         }
405     }
406
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);
416         if v.is_empty() {
417             // consume the empty "" component
418             ret.next();
419         }
420         ret
421     }
422
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)
427     }
428 }
429
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() {
433         return None;
434     }
435     let mut comps: Vec<&'a [u8]> = vec![];
436     let mut n_up = 0u;
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) }
446     }
447     if changed {
448         if comps.is_empty() && !is_abs {
449             if v == b"." {
450                 return None;
451             }
452             comps.push(dot_static);
453         }
454         Some(comps)
455     } else {
456         None
457     }
458 }
459
460 static dot_static: &'static [u8] = b".";
461 static dot_dot_static: &'static [u8] = b"..";
462
463 #[cfg(test)]
464 mod tests {
465     use prelude::*;
466     use super::*;
467     use str;
468     use str::StrSlice;
469
470     macro_rules! t(
471         (s: $path:expr, $exp:expr) => (
472             {
473                 let path = $path;
474                 assert!(path.as_str() == Some($exp));
475             }
476         );
477         (v: $path:expr, $exp:expr) => (
478             {
479                 let path = $path;
480                 assert!(path.as_vec() == $exp);
481             }
482         )
483     )
484
485     #[test]
486     fn test_paths() {
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);
495
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");
504
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");
518
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(),
521                    b"/bar");
522
523         let p = Path::new(b"foo/bar\x80");
524         assert!(p.as_str() == None);
525     }
526
527     #[test]
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");
533     }
534
535     #[test]
536     fn test_null_byte() {
537         use task;
538         let result = task::try(proc() {
539             Path::new(b"foo/bar\0")
540         });
541         assert!(result.is_err());
542
543         let result = task::try(proc() {
544             Path::new("test").set_filename(b"f\0o")
545         });
546         assert!(result.is_err());
547
548         let result = task::try(proc() {
549             Path::new("test").push(b"f\0o");
550         });
551         assert!(result.is_err());
552     }
553
554     #[test]
555     fn test_display_str() {
556         macro_rules! t(
557             ($path:expr, $disp:ident, $exp:expr) => (
558                 {
559                     let path = Path::new($path);
560                     assert!(path.$disp().to_string().as_slice() == $exp);
561                 }
562             )
563         )
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, "");
570
571         macro_rules! t(
572             ($path:expr, $exp:expr) => (
573                 {
574                     let path = Path::new($path);
575                     let mo = path.display().as_maybe_owned();
576                     assert!(mo.as_slice() == $exp);
577                 }
578             );
579             ($path:expr, $exp:expr, filename) => (
580                 {
581                     let path = Path::new($path);
582                     let mo = path.filename_display().as_maybe_owned();
583                     assert!(mo.as_slice() == $exp);
584                 }
585             )
586         )
587
588         t!("foo", "foo");
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);
594     }
595
596     #[test]
597     fn test_display() {
598         macro_rules! t(
599             ($path:expr, $exp:expr, $expf:expr) => (
600                 {
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);
606                 }
607             )
608         )
609
610         t!(b"foo", "foo", "foo");
611         t!(b"foo/bar", "foo/bar", "bar");
612         t!(b"/", "/", "");
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");
617     }
618
619     #[test]
620     fn test_components() {
621         macro_rules! t(
622             (s: $path:expr, $op:ident, $exp:expr) => (
623                 {
624                     let path = Path::new($path);
625                     assert!(path.$op() == ($exp).as_bytes());
626                 }
627             );
628             (s: $path:expr, $op:ident, $exp:expr, opt) => (
629                 {
630                     let path = Path::new($path);
631                     let left = path.$op().map(|x| str::from_utf8(x).unwrap());
632                     assert!(left == $exp);
633                 }
634             );
635             (v: $path:expr, $op:ident, $exp:expr) => (
636                 {
637                     let arg = $path;
638                     let path = Path::new(arg);
639                     assert!(path.$op() == $exp);
640                 }
641             );
642         )
643
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);
655
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, "../..");
667
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);
683
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);
701     }
702
703     #[test]
704     fn test_push() {
705         macro_rules! t(
706             (s: $path:expr, $join:expr) => (
707                 {
708                     let path = $path;
709                     let join = $join;
710                     let mut p1 = Path::new(path);
711                     let p2 = p1.clone();
712                     p1.push(join);
713                     assert!(p1 == p2.join(join));
714                 }
715             )
716         )
717
718         t!(s: "a/b/c", "..");
719         t!(s: "/a/b/c", "d");
720         t!(s: "a/b", "c/d");
721         t!(s: "a/b", "/c/d");
722     }
723
724     #[test]
725     fn test_push_path() {
726         macro_rules! t(
727             (s: $path:expr, $push:expr, $exp:expr) => (
728                 {
729                     let mut p = Path::new($path);
730                     let push = Path::new($push);
731                     p.push(&push);
732                     assert!(p.as_str() == Some($exp));
733                 }
734             )
735         )
736
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");
743     }
744
745     #[test]
746     fn test_push_many() {
747         macro_rules! t(
748             (s: $path:expr, $push:expr, $exp:expr) => (
749                 {
750                     let mut p = Path::new($path);
751                     p.push_many($push);
752                     assert!(p.as_str() == Some($exp));
753                 }
754             );
755             (v: $path:expr, $push:expr, $exp:expr) => (
756                 {
757                     let mut p = Path::new($path);
758                     p.push_many($push);
759                     assert!(p.as_vec() == $exp);
760                 }
761             )
762         )
763
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");
771     }
772
773     #[test]
774     fn test_pop() {
775         macro_rules! t(
776             (s: $path:expr, $left:expr, $right:expr) => (
777                 {
778                     let mut p = Path::new($path);
779                     let result = p.pop();
780                     assert!(p.as_str() == Some($left));
781                     assert!(result == $right);
782                 }
783             );
784             (b: $path:expr, $left:expr, $right:expr) => (
785                 {
786                     let mut p = Path::new($path);
787                     let result = p.pop();
788                     assert!(p.as_vec() == $left);
789                     assert!(result == $right);
790                 }
791             )
792         )
793
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);
808     }
809
810     #[test]
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("/")));
814     }
815
816     #[test]
817     fn test_join() {
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");
827     }
828
829     #[test]
830     fn test_join_path() {
831         macro_rules! t(
832             (s: $path:expr, $join:expr, $exp:expr) => (
833                 {
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));
838                 }
839             )
840         )
841
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");
848     }
849
850     #[test]
851     fn test_join_many() {
852         macro_rules! t(
853             (s: $path:expr, $join:expr, $exp:expr) => (
854                 {
855                     let path = Path::new($path);
856                     let res = path.join_many($join);
857                     assert!(res.as_str() == Some($exp));
858                 }
859             );
860             (v: $path:expr, $join:expr, $exp:expr) => (
861                 {
862                     let path = Path::new($path);
863                     let res = path.join_many($join);
864                     assert!(res.as_vec() == $exp);
865                 }
866             )
867         )
868
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");
875     }
876
877     #[test]
878     fn test_with_helpers() {
879         let empty: &[u8] = [];
880
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"),
884               b"/\xFF/\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(""), "../..");
904
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"),
908               b"hi/there.\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"), ".");
926     }
927
928     #[test]
929     fn test_setters() {
930         macro_rules! t(
931             (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
932                 {
933                     let path = $path;
934                     let arg = $arg;
935                     let mut p1 = Path::new(path);
936                     p1.$set(arg);
937                     let p2 = Path::new(path);
938                     assert!(p1 == p2.$with(arg));
939                 }
940             );
941             (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
942                 {
943                     let path = $path;
944                     let arg = $arg;
945                     let mut p1 = Path::new(path);
946                     p1.$set(arg);
947                     let p2 = Path::new(path);
948                     assert!(p1 == p2.$with(arg));
949                 }
950             )
951         )
952
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, "");
961
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");
970     }
971
972     #[test]
973     fn test_getters() {
974         macro_rules! t(
975             (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
976                 {
977                     let path = $path;
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());
990                     let ext = $ext;
991                     assert!(path.extension_str() == ext,
992                             "`{}`.extension_str(): Expected `{:?}`, found `{:?}`",
993                             path.as_str().unwrap(), ext, path.extension_str());
994                 }
995             );
996             (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
997                 {
998                     let path = $path;
999                     assert!(path.filename() == $filename);
1000                     assert!(path.dirname() == $dirname);
1001                     assert!(path.filestem() == $filestem);
1002                     assert!(path.extension() == $ext);
1003                 }
1004             )
1005         )
1006
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);
1028     }
1029
1030     #[test]
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(), "../..");
1040     }
1041
1042     #[test]
1043     fn test_is_absolute() {
1044         macro_rules! t(
1045             (s: $path:expr, $abs:expr, $rel:expr) => (
1046                 {
1047                     let path = Path::new($path);
1048                     assert_eq!(path.is_absolute(), $abs);
1049                     assert_eq!(path.is_relative(), $rel);
1050                 }
1051             )
1052         )
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);
1061     }
1062
1063     #[test]
1064     fn test_is_ancestor_of() {
1065         macro_rules! t(
1066             (s: $path:expr, $dest:expr, $exp:expr) => (
1067                 {
1068                     let path = Path::new($path);
1069                     let dest = Path::new($dest);
1070                     assert_eq!(path.is_ancestor_of(&dest), $exp);
1071                 }
1072             )
1073         )
1074
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);
1095     }
1096
1097     #[test]
1098     fn test_ends_with_path() {
1099         macro_rules! t(
1100             (s: $path:expr, $child:expr, $exp:expr) => (
1101                 {
1102                     let path = Path::new($path);
1103                     let child = Path::new($child);
1104                     assert_eq!(path.ends_with_path(&child), $exp);
1105                 }
1106             );
1107             (v: $path:expr, $child:expr, $exp:expr) => (
1108                 {
1109                     let path = Path::new($path);
1110                     let child = Path::new($child);
1111                     assert_eq!(path.ends_with_path(&child), $exp);
1112                 }
1113             )
1114         )
1115
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);
1134     }
1135
1136     #[test]
1137     fn test_path_relative_from() {
1138         macro_rules! t(
1139             (s: $path:expr, $other:expr, $exp:expr) => (
1140                 {
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);
1145                 }
1146             )
1147         )
1148
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"));
1179     }
1180
1181     #[test]
1182     fn test_components_iter() {
1183         macro_rules! t(
1184             (s: $path:expr, $exp:expr) => (
1185                 {
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 {:?}",
1191                             comps, exps);
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 {:?}",
1195                             comps, exps);
1196                 }
1197             );
1198             (b: $arg:expr, [$($exp:expr),*]) => (
1199                 {
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)
1207                 }
1208             )
1209         )
1210
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"]);
1218         t!(s: "a", ["a"]);
1219         t!(s: "/a", ["a"]);
1220         t!(s: "/", []);
1221         t!(s: ".", ["."]);
1222         t!(s: "..", [".."]);
1223         t!(s: "../..", ["..", ".."]);
1224         t!(s: "../../foo", ["..", "..", "foo"]);
1225     }
1226
1227     #[test]
1228     fn test_str_components() {
1229         macro_rules! t(
1230             (b: $arg:expr, $exp:expr) => (
1231                 {
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);
1239                 }
1240             )
1241         )
1242
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
1248     }
1249 }
1250
1251 #[cfg(test)]
1252 mod bench {
1253     extern crate test;
1254     use self::test::Bencher;
1255     use super::*;
1256     use prelude::*;
1257
1258     #[bench]
1259     fn join_home_dir(b: &mut Bencher) {
1260         let posix_path = Path::new("/");
1261         b.iter(|| {
1262             posix_path.join("home");
1263         });
1264     }
1265
1266     #[bench]
1267     fn join_abs_path_home_dir(b: &mut Bencher) {
1268         let posix_path = Path::new("/");
1269         b.iter(|| {
1270             posix_path.join("/home");
1271         });
1272     }
1273
1274     #[bench]
1275     fn join_many_home_dir(b: &mut Bencher) {
1276         let posix_path = Path::new("/");
1277         b.iter(|| {
1278             posix_path.join_many(&["home"]);
1279         });
1280     }
1281
1282     #[bench]
1283     fn join_many_abs_path_home_dir(b: &mut Bencher) {
1284         let posix_path = Path::new("/");
1285         b.iter(|| {
1286             posix_path.join_many(&["/home"]);
1287         });
1288     }
1289
1290     #[bench]
1291     fn push_home_dir(b: &mut Bencher) {
1292         let mut posix_path = Path::new("/");
1293         b.iter(|| {
1294             posix_path.push("home");
1295         });
1296     }
1297
1298     #[bench]
1299     fn push_abs_path_home_dir(b: &mut Bencher) {
1300         let mut posix_path = Path::new("/");
1301         b.iter(|| {
1302             posix_path.push("/home");
1303         });
1304     }
1305
1306     #[bench]
1307     fn push_many_home_dir(b: &mut Bencher) {
1308         let mut posix_path = Path::new("/");
1309         b.iter(|| {
1310             posix_path.push_many(&["home"]);
1311         });
1312     }
1313
1314     #[bench]
1315     fn push_many_abs_path_home_dir(b: &mut Bencher) {
1316         let mut posix_path = Path::new("/");
1317         b.iter(|| {
1318             posix_path.push_many(&["/home"]);
1319         });
1320     }
1321
1322     #[bench]
1323     fn ends_with_path_home_dir(b: &mut Bencher) {
1324         let posix_home_path = Path::new("/home");
1325         b.iter(|| {
1326             posix_home_path.ends_with_path(&Path::new("home"));
1327         });
1328     }
1329
1330     #[bench]
1331     fn ends_with_path_missmatch_jome_home(b: &mut Bencher) {
1332         let posix_home_path = Path::new("/home");
1333         b.iter(|| {
1334             posix_home_path.ends_with_path(&Path::new("jome"));
1335         });
1336     }
1337
1338     #[bench]
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();
1342         sub.pop();
1343         b.iter(|| {
1344             path.is_ancestor_of(&sub);
1345         });
1346     }
1347
1348     #[bench]
1349     fn path_relative_from_forward(b: &mut Bencher) {
1350         let path = Path::new("/a/b/c");
1351         let mut other = path.clone();
1352         other.pop();
1353         b.iter(|| {
1354             path.path_relative_from(&other);
1355         });
1356     }
1357
1358     #[bench]
1359     fn path_relative_from_same_level(b: &mut Bencher) {
1360         let path = Path::new("/a/b/c");
1361         let mut other = path.clone();
1362         other.pop();
1363         other.push("d");
1364         b.iter(|| {
1365             path.path_relative_from(&other);
1366         });
1367     }
1368
1369     #[bench]
1370     fn path_relative_from_backward(b: &mut Bencher) {
1371         let path = Path::new("/a/b");
1372         let mut other = path.clone();
1373         other.push("c");
1374         b.iter(|| {
1375             path.path_relative_from(&other);
1376         });
1377     }
1378 }