]> git.lizzy.rs Git - rust.git/blob - src/libstd/path/posix.rs
Add a doctest for the std::string::as_string method.
[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 hash;
17 use io::Writer;
18 use iter::{DoubleEndedIteratorExt, AdditiveIterator, Extend};
19 use iter::{Iterator, IteratorExt, Map};
20 use option::Option;
21 use option::Option::{None, Some};
22 use kinds::Sized;
23 use str::{FromStr, Str};
24 use str;
25 use slice::{CloneSliceAllocPrelude, Splits, AsSlice, VectorVector,
26             PartialEqSlicePrelude, SlicePrelude};
27 use vec::Vec;
28
29 use super::{BytesContainer, GenericPath, GenericPathUnsafe};
30
31 /// Iterator that yields successive components of a Path as &[u8]
32 pub type Components<'a> = Splits<'a, u8>;
33
34 /// Iterator that yields successive components of a Path as Option<&str>
35 pub type StrComponents<'a> = Map<'a, &'a [u8], Option<&'a str>,
36                                        Components<'a>>;
37
38 /// Represents a POSIX file path
39 #[deriving(Clone)]
40 pub struct Path {
41     repr: Vec<u8>, // assumed to never be empty or contain NULs
42     sepidx: Option<uint> // index of the final separator in repr
43 }
44
45 /// The standard path separator character
46 pub const SEP: char = '/';
47
48 /// The standard path separator byte
49 pub const SEP_BYTE: u8 = SEP as u8;
50
51 /// Returns whether the given byte is a path separator
52 #[inline]
53 pub fn is_sep_byte(u: &u8) -> bool {
54     *u as char == SEP
55 }
56
57 /// Returns whether the given char is a path separator
58 #[inline]
59 pub fn is_sep(c: char) -> bool {
60     c == SEP
61 }
62
63 impl PartialEq for Path {
64     #[inline]
65     fn eq(&self, other: &Path) -> bool {
66         self.repr == other.repr
67     }
68 }
69
70 impl Eq for Path {}
71
72 impl PartialOrd for Path {
73     fn partial_cmp(&self, other: &Path) -> Option<Ordering> {
74         Some(self.cmp(other))
75     }
76 }
77
78 impl Ord for Path {
79     fn cmp(&self, other: &Path) -> Ordering {
80         self.repr.cmp(&other.repr)
81     }
82 }
83
84 impl FromStr for Path {
85     fn from_str(s: &str) -> Option<Path> {
86         Path::new_opt(s)
87     }
88 }
89
90 // FIXME (#12938): Until DST lands, we cannot decompose &str into & and str, so
91 // we cannot usefully take ToCStr arguments by reference (without forcing an
92 // additional & around &str). So we are instead temporarily adding an instance
93 // for &Path, so that we can take ToCStr as owned. When DST lands, the &Path
94 // instance should be removed, and arguments bound by ToCStr should be passed by
95 // reference.
96
97 impl ToCStr for Path {
98     #[inline]
99     fn to_c_str(&self) -> CString {
100         // The Path impl guarantees no internal NUL
101         unsafe { self.to_c_str_unchecked() }
102     }
103
104     #[inline]
105     unsafe fn to_c_str_unchecked(&self) -> CString {
106         self.as_vec().to_c_str_unchecked()
107     }
108 }
109
110 impl<S: hash::Writer> hash::Hash<S> for Path {
111     #[inline]
112     fn hash(&self, state: &mut S) {
113         self.repr.hash(state)
114     }
115 }
116
117 impl BytesContainer for Path {
118     #[inline]
119     fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
120         self.as_vec()
121     }
122 }
123
124 impl GenericPathUnsafe for Path {
125     unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Path {
126         let path = Path::normalize(path.container_as_bytes());
127         assert!(!path.is_empty());
128         let idx = path.as_slice().rposition_elem(&SEP_BYTE);
129         Path{ repr: path, sepidx: idx }
130     }
131
132     unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T) {
133         let filename = filename.container_as_bytes();
134         match self.sepidx {
135             None if b".." == self.repr.as_slice() => {
136                 let mut v = Vec::with_capacity(3 + filename.len());
137                 v.push_all(dot_dot_static);
138                 v.push(SEP_BYTE);
139                 v.push_all(filename);
140                 // FIXME: this is slow
141                 self.repr = Path::normalize(v.as_slice());
142             }
143             None => {
144                 self.repr = Path::normalize(filename);
145             }
146             Some(idx) if self.repr[idx+1..] == b".." => {
147                 let mut v = Vec::with_capacity(self.repr.len() + 1 + filename.len());
148                 v.push_all(self.repr.as_slice());
149                 v.push(SEP_BYTE);
150                 v.push_all(filename);
151                 // FIXME: this is slow
152                 self.repr = Path::normalize(v.as_slice());
153             }
154             Some(idx) => {
155                 let mut v = Vec::with_capacity(idx + 1 + filename.len());
156                 v.push_all(self.repr[..idx+1]);
157                 v.push_all(filename);
158                 // FIXME: this is slow
159                 self.repr = Path::normalize(v.as_slice());
160             }
161         }
162         self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
163     }
164
165     unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T) {
166         let path = path.container_as_bytes();
167         if !path.is_empty() {
168             if path[0] == SEP_BYTE {
169                 self.repr = Path::normalize(path);
170             }  else {
171                 let mut v = Vec::with_capacity(self.repr.len() + path.len() + 1);
172                 v.push_all(self.repr.as_slice());
173                 v.push(SEP_BYTE);
174                 v.push_all(path);
175                 // FIXME: this is slow
176                 self.repr = Path::normalize(v.as_slice());
177             }
178             self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
179         }
180     }
181 }
182
183 impl GenericPath for Path {
184     #[inline]
185     fn as_vec<'a>(&'a self) -> &'a [u8] {
186         self.repr.as_slice()
187     }
188
189     fn into_vec(self) -> Vec<u8> {
190         self.repr
191     }
192
193     fn dirname<'a>(&'a self) -> &'a [u8] {
194         match self.sepidx {
195             None if b".." == self.repr.as_slice() => self.repr.as_slice(),
196             None => dot_static,
197             Some(0) => self.repr[..1],
198             Some(idx) if self.repr[idx+1..] == b".." => self.repr.as_slice(),
199             Some(idx) => self.repr[..idx]
200         }
201     }
202
203     fn filename<'a>(&'a self) -> Option<&'a [u8]> {
204         match self.sepidx {
205             None if b"." == self.repr.as_slice() ||
206                 b".." == self.repr.as_slice() => None,
207             None => Some(self.repr.as_slice()),
208             Some(idx) if self.repr[idx+1..] == b".." => None,
209             Some(0) if self.repr[1..].is_empty() => None,
210             Some(idx) => Some(self.repr[idx+1..])
211         }
212     }
213
214     fn pop(&mut self) -> bool {
215         match self.sepidx {
216             None if b"." == self.repr.as_slice() => false,
217             None => {
218                 self.repr = vec![b'.'];
219                 self.sepidx = None;
220                 true
221             }
222             Some(0) if b"/" == self.repr.as_slice() => false,
223             Some(idx) => {
224                 if idx == 0 {
225                     self.repr.truncate(idx+1);
226                 } else {
227                     self.repr.truncate(idx);
228                 }
229                 self.sepidx = self.repr.as_slice().rposition_elem(&SEP_BYTE);
230                 true
231             }
232         }
233     }
234
235     fn root_path(&self) -> Option<Path> {
236         if self.is_absolute() {
237             Some(Path::new("/"))
238         } else {
239             None
240         }
241     }
242
243     #[inline]
244     fn is_absolute(&self) -> bool {
245         self.repr[0] == SEP_BYTE
246     }
247
248     fn is_ancestor_of(&self, other: &Path) -> bool {
249         if self.is_absolute() != other.is_absolute() {
250             false
251         } else {
252             let mut ita = self.components();
253             let mut itb = other.components();
254             if b"." == self.repr.as_slice() {
255                 return match itb.next() {
256                     None => true,
257                     Some(b) => b != b".."
258                 };
259             }
260             loop {
261                 match (ita.next(), itb.next()) {
262                     (None, _) => break,
263                     (Some(a), Some(b)) if a == b => { continue },
264                     (Some(a), _) if a == b".." => {
265                         // if ita contains only .. components, it's an ancestor
266                         return ita.all(|x| x == b"..");
267                     }
268                     _ => return false
269                 }
270             }
271             true
272         }
273     }
274
275     fn path_relative_from(&self, base: &Path) -> Option<Path> {
276         if self.is_absolute() != base.is_absolute() {
277             if self.is_absolute() {
278                 Some(self.clone())
279             } else {
280                 None
281             }
282         } else {
283             let mut ita = self.components();
284             let mut itb = base.components();
285             let mut comps = vec![];
286             loop {
287                 match (ita.next(), itb.next()) {
288                     (None, None) => break,
289                     (Some(a), None) => {
290                         comps.push(a);
291                         comps.extend(ita.by_ref());
292                         break;
293                     }
294                     (None, _) => comps.push(dot_dot_static),
295                     (Some(a), Some(b)) if comps.is_empty() && a == b => (),
296                     (Some(a), Some(b)) if b == b"." => comps.push(a),
297                     (Some(_), Some(b)) if b == b".." => return None,
298                     (Some(a), Some(_)) => {
299                         comps.push(dot_dot_static);
300                         for _ in itb {
301                             comps.push(dot_dot_static);
302                         }
303                         comps.push(a);
304                         comps.extend(ita.by_ref());
305                         break;
306                     }
307                 }
308             }
309             Some(Path::new(comps.as_slice().connect_vec(&SEP_BYTE)))
310         }
311     }
312
313     fn ends_with_path(&self, child: &Path) -> bool {
314         if !child.is_relative() { return false; }
315         let mut selfit = self.components().rev();
316         let mut childit = child.components().rev();
317         loop {
318             match (selfit.next(), childit.next()) {
319                 (Some(a), Some(b)) => if a != b { return false; },
320                 (Some(_), None) => break,
321                 (None, Some(_)) => return false,
322                 (None, None) => break
323             }
324         }
325         true
326     }
327 }
328
329 impl Path {
330     /// Returns a new Path from a byte vector or string
331     ///
332     /// # Panics
333     ///
334     /// Panics the task if the vector contains a NUL.
335     #[inline]
336     pub fn new<T: BytesContainer>(path: T) -> Path {
337         GenericPath::new(path)
338     }
339
340     /// Returns a new Path from a byte vector or string, if possible
341     #[inline]
342     pub fn new_opt<T: BytesContainer>(path: T) -> Option<Path> {
343         GenericPath::new_opt(path)
344     }
345
346     /// Returns a normalized byte vector representation of a path, by removing all empty
347     /// components, and unnecessary . and .. components.
348     fn normalize<Sized? V: AsSlice<u8>>(v: &V) -> Vec<u8> {
349         // borrowck is being very picky
350         let val = {
351             let is_abs = !v.as_slice().is_empty() && v.as_slice()[0] == SEP_BYTE;
352             let v_ = if is_abs { v.as_slice()[1..] } else { v.as_slice() };
353             let comps = normalize_helper(v_, is_abs);
354             match comps {
355                 None => None,
356                 Some(comps) => {
357                     if is_abs && comps.is_empty() {
358                         Some(vec![SEP_BYTE])
359                     } else {
360                         let n = if is_abs { comps.len() } else { comps.len() - 1} +
361                                 comps.iter().map(|v| v.len()).sum();
362                         let mut v = Vec::with_capacity(n);
363                         let mut it = comps.into_iter();
364                         if !is_abs {
365                             match it.next() {
366                                 None => (),
367                                 Some(comp) => v.push_all(comp)
368                             }
369                         }
370                         for comp in it {
371                             v.push(SEP_BYTE);
372                             v.push_all(comp);
373                         }
374                         Some(v)
375                     }
376                 }
377             }
378         };
379         match val {
380             None => v.as_slice().to_vec(),
381             Some(val) => val
382         }
383     }
384
385     /// Returns an iterator that yields each component of the path in turn.
386     /// Does not distinguish between absolute and relative paths, e.g.
387     /// /a/b/c and a/b/c yield the same set of components.
388     /// A path of "/" yields no components. A path of "." yields one component.
389     pub fn components<'a>(&'a self) -> Components<'a> {
390         let v = if self.repr[0] == SEP_BYTE {
391             self.repr[1..]
392         } else { self.repr.as_slice() };
393         let mut ret = v.split(is_sep_byte);
394         if v.is_empty() {
395             // consume the empty "" component
396             ret.next();
397         }
398         ret
399     }
400
401     /// Returns an iterator that yields each component of the path as Option<&str>.
402     /// See components() for details.
403     pub fn str_components<'a>(&'a self) -> StrComponents<'a> {
404         self.components().map(str::from_utf8)
405     }
406 }
407
408 // None result means the byte vector didn't need normalizing
409 fn normalize_helper<'a>(v: &'a [u8], is_abs: bool) -> Option<Vec<&'a [u8]>> {
410     if is_abs && v.as_slice().is_empty() {
411         return None;
412     }
413     let mut comps: Vec<&'a [u8]> = vec![];
414     let mut n_up = 0u;
415     let mut changed = false;
416     for comp in v.split(is_sep_byte) {
417         if comp.is_empty() { changed = true }
418         else if comp == b"." { changed = true }
419         else if comp == b".." {
420             if is_abs && comps.is_empty() { changed = true }
421             else if comps.len() == n_up { comps.push(dot_dot_static); n_up += 1 }
422             else { comps.pop().unwrap(); changed = true }
423         } else { comps.push(comp) }
424     }
425     if changed {
426         if comps.is_empty() && !is_abs {
427             if v == b"." {
428                 return None;
429             }
430             comps.push(dot_static);
431         }
432         Some(comps)
433     } else {
434         None
435     }
436 }
437
438 #[allow(non_upper_case_globals)]
439 static dot_static: &'static [u8] = b".";
440 #[allow(non_upper_case_globals)]
441 static dot_dot_static: &'static [u8] = b"..";
442
443 #[cfg(test)]
444 mod tests {
445     use prelude::*;
446     use super::*;
447     use str;
448     use str::StrPrelude;
449
450     macro_rules! t(
451         (s: $path:expr, $exp:expr) => (
452             {
453                 let path = $path;
454                 assert!(path.as_str() == Some($exp));
455             }
456         );
457         (v: $path:expr, $exp:expr) => (
458             {
459                 let path = $path;
460                 assert!(path.as_vec() == $exp);
461             }
462         )
463     )
464
465     #[test]
466     fn test_paths() {
467         let empty: &[u8] = &[];
468         t!(v: Path::new(empty), b".");
469         t!(v: Path::new(b"/"), b"/");
470         t!(v: Path::new(b"a/b/c"), b"a/b/c");
471         t!(v: Path::new(b"a/b/c\xFF"), b"a/b/c\xFF");
472         t!(v: Path::new(b"\xFF/../foo\x80"), b"foo\x80");
473         let p = Path::new(b"a/b/c\xFF");
474         assert!(p.as_str() == None);
475
476         t!(s: Path::new(""), ".");
477         t!(s: Path::new("/"), "/");
478         t!(s: Path::new("hi"), "hi");
479         t!(s: Path::new("hi/"), "hi");
480         t!(s: Path::new("/lib"), "/lib");
481         t!(s: Path::new("/lib/"), "/lib");
482         t!(s: Path::new("hi/there"), "hi/there");
483         t!(s: Path::new("hi/there.txt"), "hi/there.txt");
484
485         t!(s: Path::new("hi/there/"), "hi/there");
486         t!(s: Path::new("hi/../there"), "there");
487         t!(s: Path::new("../hi/there"), "../hi/there");
488         t!(s: Path::new("/../hi/there"), "/hi/there");
489         t!(s: Path::new("foo/.."), ".");
490         t!(s: Path::new("/foo/.."), "/");
491         t!(s: Path::new("/foo/../.."), "/");
492         t!(s: Path::new("/foo/../../bar"), "/bar");
493         t!(s: Path::new("/./hi/./there/."), "/hi/there");
494         t!(s: Path::new("/./hi/./there/./.."), "/hi");
495         t!(s: Path::new("foo/../.."), "..");
496         t!(s: Path::new("foo/../../.."), "../..");
497         t!(s: Path::new("foo/../../bar"), "../bar");
498
499         assert_eq!(Path::new(b"foo/bar").into_vec().as_slice(), b"foo/bar");
500         assert_eq!(Path::new(b"/foo/../../bar").into_vec().as_slice(),
501                    b"/bar");
502
503         let p = Path::new(b"foo/bar\x80");
504         assert!(p.as_str() == None);
505     }
506
507     #[test]
508     fn test_opt_paths() {
509         assert!(Path::new_opt(b"foo/bar\0") == None);
510         t!(v: Path::new_opt(b"foo/bar").unwrap(), b"foo/bar");
511         assert!(Path::new_opt("foo/bar\0") == None);
512         t!(s: Path::new_opt("foo/bar").unwrap(), "foo/bar");
513     }
514
515     #[test]
516     fn test_null_byte() {
517         use task;
518         let result = task::try(proc() {
519             Path::new(b"foo/bar\0")
520         });
521         assert!(result.is_err());
522
523         let result = task::try(proc() {
524             Path::new("test").set_filename(b"f\0o")
525         });
526         assert!(result.is_err());
527
528         let result = task::try(proc() {
529             Path::new("test").push(b"f\0o");
530         });
531         assert!(result.is_err());
532     }
533
534     #[test]
535     fn test_display_str() {
536         macro_rules! t(
537             ($path:expr, $disp:ident, $exp:expr) => (
538                 {
539                     let path = Path::new($path);
540                     assert!(path.$disp().to_string().as_slice() == $exp);
541                 }
542             )
543         )
544         t!("foo", display, "foo");
545         t!(b"foo\x80", display, "foo\uFFFD");
546         t!(b"foo\xFFbar", display, "foo\uFFFDbar");
547         t!(b"foo\xFF/bar", filename_display, "bar");
548         t!(b"foo/\xFFbar", filename_display, "\uFFFDbar");
549         t!(b"/", filename_display, "");
550
551         macro_rules! t(
552             ($path:expr, $exp:expr) => (
553                 {
554                     let path = Path::new($path);
555                     let mo = path.display().as_cow();
556                     assert!(mo.as_slice() == $exp);
557                 }
558             );
559             ($path:expr, $exp:expr, filename) => (
560                 {
561                     let path = Path::new($path);
562                     let mo = path.filename_display().as_cow();
563                     assert!(mo.as_slice() == $exp);
564                 }
565             )
566         )
567
568         t!("foo", "foo");
569         t!(b"foo\x80", "foo\uFFFD");
570         t!(b"foo\xFFbar", "foo\uFFFDbar");
571         t!(b"foo\xFF/bar", "bar", filename);
572         t!(b"foo/\xFFbar", "\uFFFDbar", filename);
573         t!(b"/", "", filename);
574     }
575
576     #[test]
577     fn test_display() {
578         macro_rules! t(
579             ($path:expr, $exp:expr, $expf:expr) => (
580                 {
581                     let path = Path::new($path);
582                     let f = format!("{}", path.display());
583                     assert!(f.as_slice() == $exp);
584                     let f = format!("{}", path.filename_display());
585                     assert!(f.as_slice() == $expf);
586                 }
587             )
588         )
589
590         t!(b"foo", "foo", "foo");
591         t!(b"foo/bar", "foo/bar", "bar");
592         t!(b"/", "/", "");
593         t!(b"foo\xFF", "foo\uFFFD", "foo\uFFFD");
594         t!(b"foo\xFF/bar", "foo\uFFFD/bar", "bar");
595         t!(b"foo/\xFFbar", "foo/\uFFFDbar", "\uFFFDbar");
596         t!(b"\xFFfoo/bar\xFF", "\uFFFDfoo/bar\uFFFD", "bar\uFFFD");
597     }
598
599     #[test]
600     fn test_components() {
601         macro_rules! t(
602             (s: $path:expr, $op:ident, $exp:expr) => (
603                 {
604                     let path = Path::new($path);
605                     assert!(path.$op() == ($exp).as_bytes());
606                 }
607             );
608             (s: $path:expr, $op:ident, $exp:expr, opt) => (
609                 {
610                     let path = Path::new($path);
611                     let left = path.$op().map(|x| str::from_utf8(x).unwrap());
612                     assert!(left == $exp);
613                 }
614             );
615             (v: $path:expr, $op:ident, $exp:expr) => (
616                 {
617                     let arg = $path;
618                     let path = Path::new(arg);
619                     assert!(path.$op() == $exp);
620                 }
621             );
622         )
623
624         t!(v: b"a/b/c", filename, Some(b"c"));
625         t!(v: b"a/b/c\xFF", filename, Some(b"c\xFF"));
626         t!(v: b"a/b\xFF/c", filename, Some(b"c"));
627         t!(s: "a/b/c", filename, Some("c"), opt);
628         t!(s: "/a/b/c", filename, Some("c"), opt);
629         t!(s: "a", filename, Some("a"), opt);
630         t!(s: "/a", filename, Some("a"), opt);
631         t!(s: ".", filename, None, opt);
632         t!(s: "/", filename, None, opt);
633         t!(s: "..", filename, None, opt);
634         t!(s: "../..", filename, None, opt);
635
636         t!(v: b"a/b/c", dirname, b"a/b");
637         t!(v: b"a/b/c\xFF", dirname, b"a/b");
638         t!(v: b"a/b\xFF/c", dirname, b"a/b\xFF");
639         t!(s: "a/b/c", dirname, "a/b");
640         t!(s: "/a/b/c", dirname, "/a/b");
641         t!(s: "a", dirname, ".");
642         t!(s: "/a", dirname, "/");
643         t!(s: ".", dirname, ".");
644         t!(s: "/", dirname, "/");
645         t!(s: "..", dirname, "..");
646         t!(s: "../..", dirname, "../..");
647
648         t!(v: b"hi/there.txt", filestem, Some(b"there"));
649         t!(v: b"hi/there\x80.txt", filestem, Some(b"there\x80"));
650         t!(v: b"hi/there.t\x80xt", filestem, Some(b"there"));
651         t!(s: "hi/there.txt", filestem, Some("there"), opt);
652         t!(s: "hi/there", filestem, Some("there"), opt);
653         t!(s: "there.txt", filestem, Some("there"), opt);
654         t!(s: "there", filestem, Some("there"), opt);
655         t!(s: ".", filestem, None, opt);
656         t!(s: "/", filestem, None, opt);
657         t!(s: "foo/.bar", filestem, Some(".bar"), opt);
658         t!(s: ".bar", filestem, Some(".bar"), opt);
659         t!(s: "..bar", filestem, Some("."), opt);
660         t!(s: "hi/there..txt", filestem, Some("there."), opt);
661         t!(s: "..", filestem, None, opt);
662         t!(s: "../..", filestem, None, opt);
663
664         t!(v: b"hi/there.txt", extension, Some(b"txt"));
665         t!(v: b"hi/there\x80.txt", extension, Some(b"txt"));
666         t!(v: b"hi/there.t\x80xt", extension, Some(b"t\x80xt"));
667         t!(v: b"hi/there", extension, None);
668         t!(v: b"hi/there\x80", extension, None);
669         t!(s: "hi/there.txt", extension, Some("txt"), opt);
670         t!(s: "hi/there", extension, None, opt);
671         t!(s: "there.txt", extension, Some("txt"), opt);
672         t!(s: "there", extension, None, opt);
673         t!(s: ".", extension, None, opt);
674         t!(s: "/", extension, None, opt);
675         t!(s: "foo/.bar", extension, None, opt);
676         t!(s: ".bar", extension, None, opt);
677         t!(s: "..bar", extension, Some("bar"), opt);
678         t!(s: "hi/there..txt", extension, Some("txt"), opt);
679         t!(s: "..", extension, None, opt);
680         t!(s: "../..", extension, None, opt);
681     }
682
683     #[test]
684     fn test_push() {
685         macro_rules! t(
686             (s: $path:expr, $join:expr) => (
687                 {
688                     let path = $path;
689                     let join = $join;
690                     let mut p1 = Path::new(path);
691                     let p2 = p1.clone();
692                     p1.push(join);
693                     assert!(p1 == p2.join(join));
694                 }
695             )
696         )
697
698         t!(s: "a/b/c", "..");
699         t!(s: "/a/b/c", "d");
700         t!(s: "a/b", "c/d");
701         t!(s: "a/b", "/c/d");
702     }
703
704     #[test]
705     fn test_push_path() {
706         macro_rules! t(
707             (s: $path:expr, $push:expr, $exp:expr) => (
708                 {
709                     let mut p = Path::new($path);
710                     let push = Path::new($push);
711                     p.push(&push);
712                     assert!(p.as_str() == Some($exp));
713                 }
714             )
715         )
716
717         t!(s: "a/b/c", "d", "a/b/c/d");
718         t!(s: "/a/b/c", "d", "/a/b/c/d");
719         t!(s: "a/b", "c/d", "a/b/c/d");
720         t!(s: "a/b", "/c/d", "/c/d");
721         t!(s: "a/b", ".", "a/b");
722         t!(s: "a/b", "../c", "a/c");
723     }
724
725     #[test]
726     fn test_push_many() {
727         macro_rules! t(
728             (s: $path:expr, $push:expr, $exp:expr) => (
729                 {
730                     let mut p = Path::new($path);
731                     p.push_many(&$push);
732                     assert!(p.as_str() == Some($exp));
733                 }
734             );
735             (v: $path:expr, $push:expr, $exp:expr) => (
736                 {
737                     let mut p = Path::new($path);
738                     p.push_many(&$push);
739                     assert!(p.as_vec() == $exp);
740                 }
741             )
742         )
743
744         t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
745         t!(s: "a/b/c", ["d", "/e"], "/e");
746         t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
747         t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
748         t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
749         t!(v: b"a/b/c", [b"d", b"/e", b"f"], b"/e/f");
750         t!(v: b"a/b/c", [b"d".to_vec(), b"e".to_vec()], b"a/b/c/d/e");
751     }
752
753     #[test]
754     fn test_pop() {
755         macro_rules! t(
756             (s: $path:expr, $left:expr, $right:expr) => (
757                 {
758                     let mut p = Path::new($path);
759                     let result = p.pop();
760                     assert!(p.as_str() == Some($left));
761                     assert!(result == $right);
762                 }
763             );
764             (b: $path:expr, $left:expr, $right:expr) => (
765                 {
766                     let mut p = Path::new($path);
767                     let result = p.pop();
768                     assert!(p.as_vec() == $left);
769                     assert!(result == $right);
770                 }
771             )
772         )
773
774         t!(b: b"a/b/c", b"a/b", true);
775         t!(b: b"a", b".", true);
776         t!(b: b".", b".", false);
777         t!(b: b"/a", b"/", true);
778         t!(b: b"/", b"/", false);
779         t!(b: b"a/b/c\x80", b"a/b", true);
780         t!(b: b"a/b\x80/c", b"a/b\x80", true);
781         t!(b: b"\xFF", b".", true);
782         t!(b: b"/\xFF", b"/", true);
783         t!(s: "a/b/c", "a/b", true);
784         t!(s: "a", ".", true);
785         t!(s: ".", ".", false);
786         t!(s: "/a", "/", true);
787         t!(s: "/", "/", false);
788     }
789
790     #[test]
791     fn test_root_path() {
792         assert!(Path::new(b"a/b/c").root_path() == None);
793         assert!(Path::new(b"/a/b/c").root_path() == Some(Path::new("/")));
794     }
795
796     #[test]
797     fn test_join() {
798         t!(v: Path::new(b"a/b/c").join(b".."), b"a/b");
799         t!(v: Path::new(b"/a/b/c").join(b"d"), b"/a/b/c/d");
800         t!(v: Path::new(b"a/\x80/c").join(b"\xFF"), b"a/\x80/c/\xFF");
801         t!(s: Path::new("a/b/c").join(".."), "a/b");
802         t!(s: Path::new("/a/b/c").join("d"), "/a/b/c/d");
803         t!(s: Path::new("a/b").join("c/d"), "a/b/c/d");
804         t!(s: Path::new("a/b").join("/c/d"), "/c/d");
805         t!(s: Path::new(".").join("a/b"), "a/b");
806         t!(s: Path::new("/").join("a/b"), "/a/b");
807     }
808
809     #[test]
810     fn test_join_path() {
811         macro_rules! t(
812             (s: $path:expr, $join:expr, $exp:expr) => (
813                 {
814                     let path = Path::new($path);
815                     let join = Path::new($join);
816                     let res = path.join(&join);
817                     assert!(res.as_str() == Some($exp));
818                 }
819             )
820         )
821
822         t!(s: "a/b/c", "..", "a/b");
823         t!(s: "/a/b/c", "d", "/a/b/c/d");
824         t!(s: "a/b", "c/d", "a/b/c/d");
825         t!(s: "a/b", "/c/d", "/c/d");
826         t!(s: ".", "a/b", "a/b");
827         t!(s: "/", "a/b", "/a/b");
828     }
829
830     #[test]
831     fn test_join_many() {
832         macro_rules! t(
833             (s: $path:expr, $join:expr, $exp:expr) => (
834                 {
835                     let path = Path::new($path);
836                     let res = path.join_many(&$join);
837                     assert!(res.as_str() == Some($exp));
838                 }
839             );
840             (v: $path:expr, $join:expr, $exp:expr) => (
841                 {
842                     let path = Path::new($path);
843                     let res = path.join_many(&$join);
844                     assert!(res.as_vec() == $exp);
845                 }
846             )
847         )
848
849         t!(s: "a/b/c", ["d", "e"], "a/b/c/d/e");
850         t!(s: "a/b/c", ["..", "d"], "a/b/d");
851         t!(s: "a/b/c", ["d", "/e", "f"], "/e/f");
852         t!(s: "a/b/c", ["d".to_string(), "e".to_string()], "a/b/c/d/e");
853         t!(v: b"a/b/c", [b"d", b"e"], b"a/b/c/d/e");
854         t!(v: b"a/b/c", [b"d".to_vec(), b"e".to_vec()], b"a/b/c/d/e");
855     }
856
857     #[test]
858     fn test_with_helpers() {
859         let empty: &[u8] = &[];
860
861         t!(v: Path::new(b"a/b/c").with_filename(b"d"), b"a/b/d");
862         t!(v: Path::new(b"a/b/c\xFF").with_filename(b"\x80"), b"a/b/\x80");
863         t!(v: Path::new(b"/\xFF/foo").with_filename(b"\xCD"),
864               b"/\xFF/\xCD");
865         t!(s: Path::new("a/b/c").with_filename("d"), "a/b/d");
866         t!(s: Path::new(".").with_filename("foo"), "foo");
867         t!(s: Path::new("/a/b/c").with_filename("d"), "/a/b/d");
868         t!(s: Path::new("/").with_filename("foo"), "/foo");
869         t!(s: Path::new("/a").with_filename("foo"), "/foo");
870         t!(s: Path::new("foo").with_filename("bar"), "bar");
871         t!(s: Path::new("/").with_filename("foo/"), "/foo");
872         t!(s: Path::new("/a").with_filename("foo/"), "/foo");
873         t!(s: Path::new("a/b/c").with_filename(""), "a/b");
874         t!(s: Path::new("a/b/c").with_filename("."), "a/b");
875         t!(s: Path::new("a/b/c").with_filename(".."), "a");
876         t!(s: Path::new("/a").with_filename(""), "/");
877         t!(s: Path::new("foo").with_filename(""), ".");
878         t!(s: Path::new("a/b/c").with_filename("d/e"), "a/b/d/e");
879         t!(s: Path::new("a/b/c").with_filename("/d"), "a/b/d");
880         t!(s: Path::new("..").with_filename("foo"), "../foo");
881         t!(s: Path::new("../..").with_filename("foo"), "../../foo");
882         t!(s: Path::new("..").with_filename(""), "..");
883         t!(s: Path::new("../..").with_filename(""), "../..");
884
885         t!(v: Path::new(b"hi/there\x80.txt").with_extension(b"exe"),
886               b"hi/there\x80.exe");
887         t!(v: Path::new(b"hi/there.txt\x80").with_extension(b"\xFF"),
888               b"hi/there.\xFF");
889         t!(v: Path::new(b"hi/there\x80").with_extension(b"\xFF"),
890               b"hi/there\x80.\xFF");
891         t!(v: Path::new(b"hi/there.\xFF").with_extension(empty), b"hi/there");
892         t!(s: Path::new("hi/there.txt").with_extension("exe"), "hi/there.exe");
893         t!(s: Path::new("hi/there.txt").with_extension(""), "hi/there");
894         t!(s: Path::new("hi/there.txt").with_extension("."), "hi/there..");
895         t!(s: Path::new("hi/there.txt").with_extension(".."), "hi/there...");
896         t!(s: Path::new("hi/there").with_extension("txt"), "hi/there.txt");
897         t!(s: Path::new("hi/there").with_extension("."), "hi/there..");
898         t!(s: Path::new("hi/there").with_extension(".."), "hi/there...");
899         t!(s: Path::new("hi/there.").with_extension("txt"), "hi/there.txt");
900         t!(s: Path::new("hi/.foo").with_extension("txt"), "hi/.foo.txt");
901         t!(s: Path::new("hi/there.txt").with_extension(".foo"), "hi/there..foo");
902         t!(s: Path::new("/").with_extension("txt"), "/");
903         t!(s: Path::new("/").with_extension("."), "/");
904         t!(s: Path::new("/").with_extension(".."), "/");
905         t!(s: Path::new(".").with_extension("txt"), ".");
906     }
907
908     #[test]
909     fn test_setters() {
910         macro_rules! t(
911             (s: $path:expr, $set:ident, $with:ident, $arg:expr) => (
912                 {
913                     let path = $path;
914                     let arg = $arg;
915                     let mut p1 = Path::new(path);
916                     p1.$set(arg);
917                     let p2 = Path::new(path);
918                     assert!(p1 == p2.$with(arg));
919                 }
920             );
921             (v: $path:expr, $set:ident, $with:ident, $arg:expr) => (
922                 {
923                     let path = $path;
924                     let arg = $arg;
925                     let mut p1 = Path::new(path);
926                     p1.$set(arg);
927                     let p2 = Path::new(path);
928                     assert!(p1 == p2.$with(arg));
929                 }
930             )
931         )
932
933         t!(v: b"a/b/c", set_filename, with_filename, b"d");
934         t!(v: b"/", set_filename, with_filename, b"foo");
935         t!(v: b"\x80", set_filename, with_filename, b"\xFF");
936         t!(s: "a/b/c", set_filename, with_filename, "d");
937         t!(s: "/", set_filename, with_filename, "foo");
938         t!(s: ".", set_filename, with_filename, "foo");
939         t!(s: "a/b", set_filename, with_filename, "");
940         t!(s: "a", set_filename, with_filename, "");
941
942         t!(v: b"hi/there.txt", set_extension, with_extension, b"exe");
943         t!(v: b"hi/there.t\x80xt", set_extension, with_extension, b"exe\xFF");
944         t!(s: "hi/there.txt", set_extension, with_extension, "exe");
945         t!(s: "hi/there.", set_extension, with_extension, "txt");
946         t!(s: "hi/there", set_extension, with_extension, "txt");
947         t!(s: "hi/there.txt", set_extension, with_extension, "");
948         t!(s: "hi/there", set_extension, with_extension, "");
949         t!(s: ".", set_extension, with_extension, "txt");
950     }
951
952     #[test]
953     fn test_getters() {
954         macro_rules! t(
955             (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
956                 {
957                     let path = $path;
958                     let filename = $filename;
959                     assert!(path.filename_str() == filename,
960                             "{}.filename_str(): Expected `{}`, found {}",
961                             path.as_str().unwrap(), filename, path.filename_str());
962                     let dirname = $dirname;
963                     assert!(path.dirname_str() == dirname,
964                             "`{}`.dirname_str(): Expected `{}`, found `{}`",
965                             path.as_str().unwrap(), dirname, path.dirname_str());
966                     let filestem = $filestem;
967                     assert!(path.filestem_str() == filestem,
968                             "`{}`.filestem_str(): Expected `{}`, found `{}`",
969                             path.as_str().unwrap(), filestem, path.filestem_str());
970                     let ext = $ext;
971                     assert!(path.extension_str() == ext,
972                             "`{}`.extension_str(): Expected `{}`, found `{}`",
973                             path.as_str().unwrap(), ext, path.extension_str());
974                 }
975             );
976             (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => (
977                 {
978                     let path = $path;
979                     assert!(path.filename() == $filename);
980                     assert!(path.dirname() == $dirname);
981                     assert!(path.filestem() == $filestem);
982                     assert!(path.extension() == $ext);
983                 }
984             )
985         )
986
987         t!(v: Path::new(b"a/b/c"), Some(b"c"), b"a/b", Some(b"c"), None);
988         t!(v: Path::new(b"a/b/\xFF"), Some(b"\xFF"), b"a/b", Some(b"\xFF"), None);
989         t!(v: Path::new(b"hi/there.\xFF"), Some(b"there.\xFF"), b"hi",
990               Some(b"there"), Some(b"\xFF"));
991         t!(s: Path::new("a/b/c"), Some("c"), Some("a/b"), Some("c"), None);
992         t!(s: Path::new("."), None, Some("."), None, None);
993         t!(s: Path::new("/"), None, Some("/"), None, None);
994         t!(s: Path::new(".."), None, Some(".."), None, None);
995         t!(s: Path::new("../.."), None, Some("../.."), None, None);
996         t!(s: Path::new("hi/there.txt"), Some("there.txt"), Some("hi"),
997               Some("there"), Some("txt"));
998         t!(s: Path::new("hi/there"), Some("there"), Some("hi"), Some("there"), None);
999         t!(s: Path::new("hi/there."), Some("there."), Some("hi"),
1000               Some("there"), Some(""));
1001         t!(s: Path::new("hi/.there"), Some(".there"), Some("hi"), Some(".there"), None);
1002         t!(s: Path::new("hi/..there"), Some("..there"), Some("hi"),
1003               Some("."), Some("there"));
1004         t!(s: Path::new(b"a/b/\xFF"), None, Some("a/b"), None, None);
1005         t!(s: Path::new(b"a/b/\xFF.txt"), None, Some("a/b"), None, Some("txt"));
1006         t!(s: Path::new(b"a/b/c.\x80"), None, Some("a/b"), Some("c"), None);
1007         t!(s: Path::new(b"\xFF/b"), Some("b"), None, Some("b"), None);
1008     }
1009
1010     #[test]
1011     fn test_dir_path() {
1012         t!(v: Path::new(b"hi/there\x80").dir_path(), b"hi");
1013         t!(v: Path::new(b"hi\xFF/there").dir_path(), b"hi\xFF");
1014         t!(s: Path::new("hi/there").dir_path(), "hi");
1015         t!(s: Path::new("hi").dir_path(), ".");
1016         t!(s: Path::new("/hi").dir_path(), "/");
1017         t!(s: Path::new("/").dir_path(), "/");
1018         t!(s: Path::new("..").dir_path(), "..");
1019         t!(s: Path::new("../..").dir_path(), "../..");
1020     }
1021
1022     #[test]
1023     fn test_is_absolute() {
1024         macro_rules! t(
1025             (s: $path:expr, $abs:expr, $rel:expr) => (
1026                 {
1027                     let path = Path::new($path);
1028                     assert_eq!(path.is_absolute(), $abs);
1029                     assert_eq!(path.is_relative(), $rel);
1030                 }
1031             )
1032         )
1033         t!(s: "a/b/c", false, true);
1034         t!(s: "/a/b/c", true, false);
1035         t!(s: "a", false, true);
1036         t!(s: "/a", true, false);
1037         t!(s: ".", false, true);
1038         t!(s: "/", true, false);
1039         t!(s: "..", false, true);
1040         t!(s: "../..", false, true);
1041     }
1042
1043     #[test]
1044     fn test_is_ancestor_of() {
1045         macro_rules! t(
1046             (s: $path:expr, $dest:expr, $exp:expr) => (
1047                 {
1048                     let path = Path::new($path);
1049                     let dest = Path::new($dest);
1050                     assert_eq!(path.is_ancestor_of(&dest), $exp);
1051                 }
1052             )
1053         )
1054
1055         t!(s: "a/b/c", "a/b/c/d", true);
1056         t!(s: "a/b/c", "a/b/c", true);
1057         t!(s: "a/b/c", "a/b", false);
1058         t!(s: "/a/b/c", "/a/b/c", true);
1059         t!(s: "/a/b", "/a/b/c", true);
1060         t!(s: "/a/b/c/d", "/a/b/c", false);
1061         t!(s: "/a/b", "a/b/c", false);
1062         t!(s: "a/b", "/a/b/c", false);
1063         t!(s: "a/b/c", "a/b/d", false);
1064         t!(s: "../a/b/c", "a/b/c", false);
1065         t!(s: "a/b/c", "../a/b/c", false);
1066         t!(s: "a/b/c", "a/b/cd", false);
1067         t!(s: "a/b/cd", "a/b/c", false);
1068         t!(s: "../a/b", "../a/b/c", true);
1069         t!(s: ".", "a/b", true);
1070         t!(s: ".", ".", true);
1071         t!(s: "/", "/", true);
1072         t!(s: "/", "/a/b", true);
1073         t!(s: "..", "a/b", true);
1074         t!(s: "../..", "a/b", true);
1075     }
1076
1077     #[test]
1078     fn test_ends_with_path() {
1079         macro_rules! t(
1080             (s: $path:expr, $child:expr, $exp:expr) => (
1081                 {
1082                     let path = Path::new($path);
1083                     let child = Path::new($child);
1084                     assert_eq!(path.ends_with_path(&child), $exp);
1085                 }
1086             );
1087             (v: $path:expr, $child:expr, $exp:expr) => (
1088                 {
1089                     let path = Path::new($path);
1090                     let child = Path::new($child);
1091                     assert_eq!(path.ends_with_path(&child), $exp);
1092                 }
1093             )
1094         )
1095
1096         t!(s: "a/b/c", "c", true);
1097         t!(s: "a/b/c", "d", false);
1098         t!(s: "foo/bar/quux", "bar", false);
1099         t!(s: "foo/bar/quux", "barquux", false);
1100         t!(s: "a/b/c", "b/c", true);
1101         t!(s: "a/b/c", "a/b/c", true);
1102         t!(s: "a/b/c", "foo/a/b/c", false);
1103         t!(s: "/a/b/c", "a/b/c", true);
1104         t!(s: "/a/b/c", "/a/b/c", false); // child must be relative
1105         t!(s: "/a/b/c", "foo/a/b/c", false);
1106         t!(s: "a/b/c", "", false);
1107         t!(s: "", "", true);
1108         t!(s: "/a/b/c", "d/e/f", false);
1109         t!(s: "a/b/c", "a/b", false);
1110         t!(s: "a/b/c", "b", false);
1111         t!(v: b"a/b/c", b"b/c", true);
1112         t!(v: b"a/b/\xFF", b"\xFF", true);
1113         t!(v: b"a/b/\xFF", b"b/\xFF", true);
1114     }
1115
1116     #[test]
1117     fn test_path_relative_from() {
1118         macro_rules! t(
1119             (s: $path:expr, $other:expr, $exp:expr) => (
1120                 {
1121                     let path = Path::new($path);
1122                     let other = Path::new($other);
1123                     let res = path.path_relative_from(&other);
1124                     assert_eq!(res.as_ref().and_then(|x| x.as_str()), $exp);
1125                 }
1126             )
1127         )
1128
1129         t!(s: "a/b/c", "a/b", Some("c"));
1130         t!(s: "a/b/c", "a/b/d", Some("../c"));
1131         t!(s: "a/b/c", "a/b/c/d", Some(".."));
1132         t!(s: "a/b/c", "a/b/c", Some("."));
1133         t!(s: "a/b/c", "a/b/c/d/e", Some("../.."));
1134         t!(s: "a/b/c", "a/d/e", Some("../../b/c"));
1135         t!(s: "a/b/c", "d/e/f", Some("../../../a/b/c"));
1136         t!(s: "a/b/c", "/a/b/c", None);
1137         t!(s: "/a/b/c", "a/b/c", Some("/a/b/c"));
1138         t!(s: "/a/b/c", "/a/b/c/d", Some(".."));
1139         t!(s: "/a/b/c", "/a/b", Some("c"));
1140         t!(s: "/a/b/c", "/a/b/c/d/e", Some("../.."));
1141         t!(s: "/a/b/c", "/a/d/e", Some("../../b/c"));
1142         t!(s: "/a/b/c", "/d/e/f", Some("../../../a/b/c"));
1143         t!(s: "hi/there.txt", "hi/there", Some("../there.txt"));
1144         t!(s: ".", "a", Some(".."));
1145         t!(s: ".", "a/b", Some("../.."));
1146         t!(s: ".", ".", Some("."));
1147         t!(s: "a", ".", Some("a"));
1148         t!(s: "a/b", ".", Some("a/b"));
1149         t!(s: "..", ".", Some(".."));
1150         t!(s: "a/b/c", "a/b/c", Some("."));
1151         t!(s: "/a/b/c", "/a/b/c", Some("."));
1152         t!(s: "/", "/", Some("."));
1153         t!(s: "/", ".", Some("/"));
1154         t!(s: "../../a", "b", Some("../../../a"));
1155         t!(s: "a", "../../b", None);
1156         t!(s: "../../a", "../../b", Some("../a"));
1157         t!(s: "../../a", "../../a/b", Some(".."));
1158         t!(s: "../../a/b", "../../a", Some("b"));
1159     }
1160
1161     #[test]
1162     fn test_components_iter() {
1163         macro_rules! t(
1164             (s: $path:expr, $exp:expr) => (
1165                 {
1166                     let path = Path::new($path);
1167                     let comps = path.components().collect::<Vec<&[u8]>>();
1168                     let exp: &[&str] = &$exp;
1169                     let exps = exp.iter().map(|x| x.as_bytes()).collect::<Vec<&[u8]>>();
1170                     assert!(comps == exps, "components: Expected {}, found {}",
1171                             comps, exps);
1172                     let comps = path.components().rev().collect::<Vec<&[u8]>>();
1173                     let exps = exps.into_iter().rev().collect::<Vec<&[u8]>>();
1174                     assert!(comps == exps, "rev_components: Expected {}, found {}",
1175                             comps, exps);
1176                 }
1177             );
1178             (b: $arg:expr, [$($exp:expr),*]) => (
1179                 {
1180                     let path = Path::new($arg);
1181                     let comps = path.components().collect::<Vec<&[u8]>>();
1182                     let exp: &[&[u8]] = &[$($exp),*];
1183                     assert_eq!(comps.as_slice(), exp);
1184                     let comps = path.components().rev().collect::<Vec<&[u8]>>();
1185                     let exp = exp.iter().rev().map(|&x|x).collect::<Vec<&[u8]>>();
1186                     assert_eq!(comps, exp)
1187                 }
1188             )
1189         )
1190
1191         t!(b: b"a/b/c", [b"a", b"b", b"c"]);
1192         t!(b: b"/\xFF/a/\x80", [b"\xFF", b"a", b"\x80"]);
1193         t!(b: b"../../foo\xCDbar", [b"..", b"..", b"foo\xCDbar"]);
1194         t!(s: "a/b/c", ["a", "b", "c"]);
1195         t!(s: "a/b/d", ["a", "b", "d"]);
1196         t!(s: "a/b/cd", ["a", "b", "cd"]);
1197         t!(s: "/a/b/c", ["a", "b", "c"]);
1198         t!(s: "a", ["a"]);
1199         t!(s: "/a", ["a"]);
1200         t!(s: "/", []);
1201         t!(s: ".", ["."]);
1202         t!(s: "..", [".."]);
1203         t!(s: "../..", ["..", ".."]);
1204         t!(s: "../../foo", ["..", "..", "foo"]);
1205     }
1206
1207     #[test]
1208     fn test_str_components() {
1209         macro_rules! t(
1210             (b: $arg:expr, $exp:expr) => (
1211                 {
1212                     let path = Path::new($arg);
1213                     let comps = path.str_components().collect::<Vec<Option<&str>>>();
1214                     let exp: &[Option<&str>] = &$exp;
1215                     assert_eq!(comps.as_slice(), exp);
1216                     let comps = path.str_components().rev().collect::<Vec<Option<&str>>>();
1217                     let exp = exp.iter().rev().map(|&x|x).collect::<Vec<Option<&str>>>();
1218                     assert_eq!(comps, exp);
1219                 }
1220             )
1221         )
1222
1223         t!(b: b"a/b/c", [Some("a"), Some("b"), Some("c")]);
1224         t!(b: b"/\xFF/a/\x80", [None, Some("a"), None]);
1225         t!(b: b"../../foo\xCDbar", [Some(".."), Some(".."), None]);
1226         // str_components is a wrapper around components, so no need to do
1227         // the full set of tests
1228     }
1229 }
1230
1231 #[cfg(test)]
1232 mod bench {
1233     extern crate test;
1234     use self::test::Bencher;
1235     use super::*;
1236     use prelude::*;
1237
1238     #[bench]
1239     fn join_home_dir(b: &mut Bencher) {
1240         let posix_path = Path::new("/");
1241         b.iter(|| {
1242             posix_path.join("home");
1243         });
1244     }
1245
1246     #[bench]
1247     fn join_abs_path_home_dir(b: &mut Bencher) {
1248         let posix_path = Path::new("/");
1249         b.iter(|| {
1250             posix_path.join("/home");
1251         });
1252     }
1253
1254     #[bench]
1255     fn join_many_home_dir(b: &mut Bencher) {
1256         let posix_path = Path::new("/");
1257         b.iter(|| {
1258             posix_path.join_many(&["home"]);
1259         });
1260     }
1261
1262     #[bench]
1263     fn join_many_abs_path_home_dir(b: &mut Bencher) {
1264         let posix_path = Path::new("/");
1265         b.iter(|| {
1266             posix_path.join_many(&["/home"]);
1267         });
1268     }
1269
1270     #[bench]
1271     fn push_home_dir(b: &mut Bencher) {
1272         let mut posix_path = Path::new("/");
1273         b.iter(|| {
1274             posix_path.push("home");
1275         });
1276     }
1277
1278     #[bench]
1279     fn push_abs_path_home_dir(b: &mut Bencher) {
1280         let mut posix_path = Path::new("/");
1281         b.iter(|| {
1282             posix_path.push("/home");
1283         });
1284     }
1285
1286     #[bench]
1287     fn push_many_home_dir(b: &mut Bencher) {
1288         let mut posix_path = Path::new("/");
1289         b.iter(|| {
1290             posix_path.push_many(&["home"]);
1291         });
1292     }
1293
1294     #[bench]
1295     fn push_many_abs_path_home_dir(b: &mut Bencher) {
1296         let mut posix_path = Path::new("/");
1297         b.iter(|| {
1298             posix_path.push_many(&["/home"]);
1299         });
1300     }
1301
1302     #[bench]
1303     fn ends_with_path_home_dir(b: &mut Bencher) {
1304         let posix_home_path = Path::new("/home");
1305         b.iter(|| {
1306             posix_home_path.ends_with_path(&Path::new("home"));
1307         });
1308     }
1309
1310     #[bench]
1311     fn ends_with_path_missmatch_jome_home(b: &mut Bencher) {
1312         let posix_home_path = Path::new("/home");
1313         b.iter(|| {
1314             posix_home_path.ends_with_path(&Path::new("jome"));
1315         });
1316     }
1317
1318     #[bench]
1319     fn is_ancestor_of_path_with_10_dirs(b: &mut Bencher) {
1320         let path = Path::new("/home/1/2/3/4/5/6/7/8/9");
1321         let mut sub = path.clone();
1322         sub.pop();
1323         b.iter(|| {
1324             path.is_ancestor_of(&sub);
1325         });
1326     }
1327
1328     #[bench]
1329     fn path_relative_from_forward(b: &mut Bencher) {
1330         let path = Path::new("/a/b/c");
1331         let mut other = path.clone();
1332         other.pop();
1333         b.iter(|| {
1334             path.path_relative_from(&other);
1335         });
1336     }
1337
1338     #[bench]
1339     fn path_relative_from_same_level(b: &mut Bencher) {
1340         let path = Path::new("/a/b/c");
1341         let mut other = path.clone();
1342         other.pop();
1343         other.push("d");
1344         b.iter(|| {
1345             path.path_relative_from(&other);
1346         });
1347     }
1348
1349     #[bench]
1350     fn path_relative_from_backward(b: &mut Bencher) {
1351         let path = Path::new("/a/b");
1352         let mut other = path.clone();
1353         other.push("c");
1354         b.iter(|| {
1355             path.path_relative_from(&other);
1356         });
1357     }
1358 }