mod.rs 25.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12 13 14 15 16 17 18 19 20 21 22
/*!

Cross-platform path support

This module implements support for two flavors of paths. `PosixPath` represents
a path on any unix-like system, whereas `WindowsPath` represents a path on
Windows. This module also exposes a typedef `Path` which is equal to the
appropriate platform-specific path variant.

Both `PosixPath` and `WindowsPath` implement a trait `GenericPath`, which
contains the set of methods that behave the same for both paths. They each also
implement some methods that could not be expressed in `GenericPath`, yet behave
23
identically for both path flavors, such as `.components()`.
24 25 26 27 28 29 30 31 32

The three main design goals of this module are 1) to avoid unnecessary
allocation, 2) to behave the same regardless of which flavor of path is being
used, and 3) to support paths that cannot be represented in UTF-8 (as Linux has
no restriction on paths beyond disallowing NUL).

## Usage

Usage of this module is fairly straightforward. Unless writing platform-specific
33
code, `Path` should be used to refer to the platform-native path.
34

35 36
Creation of a path is typically done with either `Path::new(some_str)` or
`Path::new(some_vec)`. This path can be modified with `.push()` and
37 38 39 40 41 42
`.pop()` (and other setters). The resulting Path can either be passed to another
API that expects a path, or can be turned into a &[u8] with `.as_vec()` or a
Option<&str> with `.as_str()`. Similarly, attributes of the path can be queried
with methods such as `.filename()`. There are also methods that return a new
path instead of modifying the receiver, such as `.join()` or `.dir_path()`.

K
Kevin Ballard 已提交
43
Paths are always kept in normalized form. This means that creating the path
44
`Path::new("a/b/../c")` will return the path `a/c`. Similarly any attempt
K
Kevin Ballard 已提交
45 46
to mutate the path will always leave it in normalized form.

47
When rendering a path to some form of output, there is a method `.display()`
48 49 50 51 52 53 54 55
which is compatible with the `format!()` parameter `{}`. This will render the
path as a string, replacing all non-utf8 sequences with the Replacement
Character (U+FFFD). As such it is not suitable for passing to any API that
actually operates on the path; it is only intended for display.

## Example

```rust
56
let mut path = Path::new("/tmp/path");
A
Alex Crichton 已提交
57
println!("path: {}", path.display());
58 59
path.set_filename("foo");
path.push("bar");
A
Alex Crichton 已提交
60 61
println!("new path: {}", path.display());
println!("path exists: {}", path.exists());
62 63 64
```

*/
65 66 67 68

use container::Container;
use c_str::CString;
use clone::Clone;
69
use fmt;
70
use iter::Iterator;
71 72
use option::{Option, None, Some};
use str;
73
use str::{OwnedStr, Str, StrSlice};
74
use to_str::ToStr;
75
use vec;
76
use vec::{CopyableVector, OwnedCopyableVector, OwnedVector, Vector};
77 78 79 80
use vec::{ImmutableEqVector, ImmutableVector};

/// Typedef for POSIX file paths.
/// See `posix::Path` for more info.
81
pub use PosixPath = self::posix::Path;
82

K
Kevin Ballard 已提交
83 84
/// Typedef for Windows file paths.
/// See `windows::Path` for more info.
85
pub use WindowsPath = self::windows::Path;
86 87 88

/// Typedef for the platform-native path type
#[cfg(unix)]
89
pub use Path = self::posix::Path;
K
Kevin Ballard 已提交
90 91
/// Typedef for the platform-native path type
#[cfg(windows)]
92
pub use Path = self::windows::Path;
93 94 95

/// Typedef for the platform-native component iterator
#[cfg(unix)]
P
Palmer Cox 已提交
96
pub use Components = self::posix::Components;
97 98
/// Typedef for the platform-native reverse component iterator
#[cfg(unix)]
P
Palmer Cox 已提交
99
pub use RevComponents = self::posix::RevComponents;
100 101
/// Typedef for the platform-native component iterator
#[cfg(windows)]
P
Palmer Cox 已提交
102
pub use Components = self::windows::Components;
103 104
/// Typedef for the platform-native reverse component iterator
#[cfg(windows)]
P
Palmer Cox 已提交
105
pub use RevComponents = self::windows::RevComponents;
106 107 108

/// Typedef for the platform-native str component iterator
#[cfg(unix)]
P
Palmer Cox 已提交
109
pub use StrComponents = self::posix::StrComponents;
110 111
/// Typedef for the platform-native reverse str component iterator
#[cfg(unix)]
P
Palmer Cox 已提交
112
pub use RevStrComponents = self::posix::RevStrComponents;
113 114
/// Typedef for the platform-native str component iterator
#[cfg(windows)]
P
Palmer Cox 已提交
115
pub use StrComponents = self::windows::StrComponents;
116 117
/// Typedef for the platform-native reverse str component iterator
#[cfg(windows)]
P
Palmer Cox 已提交
118
pub use RevStrComponents = self::windows::RevStrComponents;
119

120 121 122 123 124 125 126 127 128 129 130 131 132 133
/// Alias for the platform-native separator character.
#[cfg(unix)]
pub use SEP = self::posix::SEP;
/// Alias for the platform-native separator byte.
#[cfg(windows)]
pub use SEP = self::windows::SEP;

/// Alias for the platform-native separator character.
#[cfg(unix)]
pub use SEP_BYTE = self::posix::SEP_BYTE;
/// Alias for the platform-native separator byte.
#[cfg(windows)]
pub use SEP_BYTE = self::windows::SEP_BYTE;

134 135 136 137 138 139 140 141 142 143 144 145 146
/// Typedef for the platform-native separator char func
#[cfg(unix)]
pub use is_sep = self::posix::is_sep;
/// Typedef for the platform-native separator char func
#[cfg(windows)]
pub use is_sep = self::windows::is_sep;
/// Typedef for the platform-native separator byte func
#[cfg(unix)]
pub use is_sep_byte = self::posix::is_sep_byte;
/// Typedef for the platform-native separator byte func
#[cfg(windows)]
pub use is_sep_byte = self::windows::is_sep_byte;

147 148
pub mod posix;
pub mod windows;
149 150 151 152 153 154 155 156 157

// Condition that is raised when a NUL is found in a byte vector given to a Path function
condition! {
    // this should be a &[u8] but there's a lifetime issue
    null_byte: ~[u8] -> ~[u8];
}

/// A trait that represents the generic operations available on paths
pub trait GenericPath: Clone + GenericPathUnsafe {
158
    /// Creates a new Path from a byte vector or string.
159 160 161 162 163
    /// The resulting Path will always be normalized.
    ///
    /// # Failure
    ///
    /// Raises the `null_byte` condition if the path contains a NUL.
K
Kevin Ballard 已提交
164 165
    ///
    /// See individual Path impls for additional restrictions.
166
    #[inline]
167
    fn new<T: BytesContainer>(path: T) -> Self {
168 169
        if contains_nul(path.container_as_bytes()) {
            let path = self::null_byte::cond.raise(path.container_into_owned_bytes());
170
            assert!(!contains_nul(path));
171
            unsafe { GenericPathUnsafe::new_unchecked(path) }
172
        } else {
173
            unsafe { GenericPathUnsafe::new_unchecked(path) }
174 175 176
        }
    }

177
    /// Creates a new Path from a byte vector or string, if possible.
178 179
    /// The resulting Path will always be normalized.
    #[inline]
180
    fn new_opt<T: BytesContainer>(path: T) -> Option<Self> {
181
        if contains_nul(path.container_as_bytes()) {
182 183
            None
        } else {
184
            Some(unsafe { GenericPathUnsafe::new_unchecked(path) })
185 186 187
        }
    }

188 189 190 191
    /// Returns the path as a string, if possible.
    /// If the path is not representable in utf-8, this returns None.
    #[inline]
    fn as_str<'a>(&'a self) -> Option<&'a str> {
192
        str::from_utf8_opt(self.as_vec())
193 194 195 196 197
    }

    /// Returns the path as a byte vector
    fn as_vec<'a>(&'a self) -> &'a [u8];

198 199 200
    /// Converts the Path into an owned byte vector
    fn into_vec(self) -> ~[u8];

201 202 203 204
    /// Returns an object that implements `fmt::Default` for printing paths
    ///
    /// This will print the equivalent of `to_display_str()` when used with a {} format parameter.
    fn display<'a>(&'a self) -> Display<'a, Self> {
205
        Display{ path: self, filename: false }
206 207 208 209 210 211
    }

    /// Returns an object that implements `fmt::Default` for printing filenames
    ///
    /// This will print the equivalent of `to_filename_display_str()` when used with a {}
    /// format parameter. If there is no filename, nothing will be printed.
212 213
    fn filename_display<'a>(&'a self) -> Display<'a, Self> {
        Display{ path: self, filename: true }
214 215
    }

216 217 218 219 220 221 222
    /// Returns the directory component of `self`, as a byte vector (with no trailing separator).
    /// If `self` has no directory component, returns ['.'].
    fn dirname<'a>(&'a self) -> &'a [u8];
    /// Returns the directory component of `self`, as a string, if possible.
    /// See `dirname` for details.
    #[inline]
    fn dirname_str<'a>(&'a self) -> Option<&'a str> {
223
        str::from_utf8_opt(self.dirname())
224 225
    }
    /// Returns the file component of `self`, as a byte vector.
226 227 228
    /// If `self` represents the root of the file hierarchy, returns None.
    /// If `self` is "." or "..", returns None.
    fn filename<'a>(&'a self) -> Option<&'a [u8]>;
229 230 231 232
    /// Returns the file component of `self`, as a string, if possible.
    /// See `filename` for details.
    #[inline]
    fn filename_str<'a>(&'a self) -> Option<&'a str> {
233
        self.filename().and_then(str::from_utf8_opt)
234 235 236 237
    }
    /// Returns the stem of the filename of `self`, as a byte vector.
    /// The stem is the portion of the filename just before the last '.'.
    /// If there is no '.', the entire filename is returned.
238 239 240 241 242 243 244 245 246 247 248
    fn filestem<'a>(&'a self) -> Option<&'a [u8]> {
        match self.filename() {
            None => None,
            Some(name) => Some({
                let dot = '.' as u8;
                match name.rposition_elem(&dot) {
                    None | Some(0) => name,
                    Some(1) if name == bytes!("..") => name,
                    Some(pos) => name.slice_to(pos)
                }
            })
249 250 251 252 253 254
        }
    }
    /// Returns the stem of the filename of `self`, as a string, if possible.
    /// See `filestem` for details.
    #[inline]
    fn filestem_str<'a>(&'a self) -> Option<&'a str> {
255
        self.filestem().and_then(str::from_utf8_opt)
256 257 258 259 260 261
    }
    /// Returns the extension of the filename of `self`, as an optional byte vector.
    /// The extension is the portion of the filename just after the last '.'.
    /// If there is no extension, None is returned.
    /// If the filename ends in '.', the empty vector is returned.
    fn extension<'a>(&'a self) -> Option<&'a [u8]> {
262 263 264 265 266 267 268 269 270 271
        match self.filename() {
            None => None,
            Some(name) => {
                let dot = '.' as u8;
                match name.rposition_elem(&dot) {
                    None | Some(0) => None,
                    Some(1) if name == bytes!("..") => None,
                    Some(pos) => Some(name.slice_from(pos+1))
                }
            }
272 273 274 275 276 277
        }
    }
    /// Returns the extension of the filename of `self`, as a string, if possible.
    /// See `extension` for details.
    #[inline]
    fn extension_str<'a>(&'a self) -> Option<&'a str> {
278
        self.extension().and_then(str::from_utf8_opt)
279 280
    }

281
    /// Replaces the filename portion of the path with the given byte vector or string.
282 283 284 285 286 287
    /// If the replacement name is [], this is equivalent to popping the path.
    ///
    /// # Failure
    ///
    /// Raises the `null_byte` condition if the filename contains a NUL.
    #[inline]
288 289 290
    fn set_filename<T: BytesContainer>(&mut self, filename: T) {
        if contains_nul(filename.container_as_bytes()) {
            let filename = self::null_byte::cond.raise(filename.container_into_owned_bytes());
291 292 293 294 295 296
            assert!(!contains_nul(filename));
            unsafe { self.set_filename_unchecked(filename) }
        } else {
            unsafe { self.set_filename_unchecked(filename) }
        }
    }
297
    /// Replaces the extension with the given byte vector or string.
298
    /// If there is no extension in `self`, this adds one.
299
    /// If the argument is [] or "", this removes the extension.
300 301 302 303 304
    /// If `self` has no filename, this is a no-op.
    ///
    /// # Failure
    ///
    /// Raises the `null_byte` condition if the extension contains a NUL.
305
    fn set_extension<T: BytesContainer>(&mut self, extension: T) {
306 307
        // borrowck causes problems here too
        let val = {
308 309 310 311 312 313
            match self.filename() {
                None => None,
                Some(name) => {
                    let dot = '.' as u8;
                    match name.rposition_elem(&dot) {
                        None | Some(0) => {
314
                            if extension.container_as_bytes().is_empty() {
315
                                None
316
                            } else {
317
                                let mut v;
318 319
                                if contains_nul(extension.container_as_bytes()) {
                                    let ext = extension.container_into_owned_bytes();
320 321 322 323 324 325 326
                                    let extension = self::null_byte::cond.raise(ext);
                                    assert!(!contains_nul(extension));
                                    v = vec::with_capacity(name.len() + extension.len() + 1);
                                    v.push_all(name);
                                    v.push(dot);
                                    v.push_all(extension);
                                } else {
327
                                    let extension = extension.container_as_bytes();
328 329 330 331 332 333
                                    v = vec::with_capacity(name.len() + extension.len() + 1);
                                    v.push_all(name);
                                    v.push(dot);
                                    v.push_all(extension);
                                }
                                Some(v)
334 335
                            }
                        }
336
                        Some(idx) => {
337
                            if extension.container_as_bytes().is_empty() {
338
                                Some(name.slice_to(idx).to_owned())
339
                            } else {
340
                                let mut v;
341 342
                                if contains_nul(extension.container_as_bytes()) {
                                    let ext = extension.container_into_owned_bytes();
343 344 345 346 347 348
                                    let extension = self::null_byte::cond.raise(ext);
                                    assert!(!contains_nul(extension));
                                    v = vec::with_capacity(idx + extension.len() + 1);
                                    v.push_all(name.slice_to(idx+1));
                                    v.push_all(extension);
                                } else {
349
                                    let extension = extension.container_as_bytes();
350 351 352 353 354
                                    v = vec::with_capacity(idx + extension.len() + 1);
                                    v.push_all(name.slice_to(idx+1));
                                    v.push_all(extension);
                                }
                                Some(v)
355 356 357 358
                            }
                        }
                    }
                }
359
            }
360 361 362 363 364 365 366
        };
        match val {
            None => (),
            Some(v) => unsafe { self.set_filename_unchecked(v) }
        }
    }

367 368
    /// Returns a new Path constructed by replacing the filename with the given
    /// byte vector or string.
369 370 371 372 373 374
    /// See `set_filename` for details.
    ///
    /// # Failure
    ///
    /// Raises the `null_byte` condition if the filename contains a NUL.
    #[inline]
375
    fn with_filename<T: BytesContainer>(&self, filename: T) -> Self {
376 377 378 379
        let mut p = self.clone();
        p.set_filename(filename);
        p
    }
380 381
    /// Returns a new Path constructed by setting the extension to the given
    /// byte vector or string.
382 383 384 385 386 387
    /// See `set_extension` for details.
    ///
    /// # Failure
    ///
    /// Raises the `null_byte` condition if the extension contains a NUL.
    #[inline]
388
    fn with_extension<T: BytesContainer>(&self, extension: T) -> Self {
389 390 391 392 393 394 395 396
        let mut p = self.clone();
        p.set_extension(extension);
        p
    }

    /// Returns the directory component of `self`, as a Path.
    /// If `self` represents the root of the filesystem hierarchy, returns `self`.
    fn dir_path(&self) -> Self {
K
Kevin Ballard 已提交
397
        // self.dirname() returns a NUL-free vector
398
        unsafe { GenericPathUnsafe::new_unchecked(self.dirname()) }
399 400
    }

401 402 403 404 405
    /// Returns a Path that represents the filesystem root that `self` is rooted in.
    ///
    /// If `self` is not absolute, or vol-relative in the case of Windows, this returns None.
    fn root_path(&self) -> Option<Self>;

406
    /// Pushes a path (as a byte vector or string) onto `self`.
407 408 409 410 411 412
    /// If the argument represents an absolute path, it replaces `self`.
    ///
    /// # Failure
    ///
    /// Raises the `null_byte` condition if the path contains a NUL.
    #[inline]
413 414 415
    fn push<T: BytesContainer>(&mut self, path: T) {
        if contains_nul(path.container_as_bytes()) {
            let path = self::null_byte::cond.raise(path.container_into_owned_bytes());
416 417 418 419 420 421
            assert!(!contains_nul(path));
            unsafe { self.push_unchecked(path) }
        } else {
            unsafe { self.push_unchecked(path) }
        }
    }
422
    /// Pushes multiple paths (as byte vectors or strings) onto `self`.
423 424
    /// See `push` for details.
    #[inline]
425 426 427 428 429 430 431 432 433 434
    fn push_many<T: BytesContainer>(&mut self, paths: &[T]) {
        let t: Option<T> = None;
        if BytesContainer::is_str(t) {
            for p in paths.iter() {
                self.push(p.container_as_str())
            }
        } else {
            for p in paths.iter() {
                self.push(p.container_as_bytes())
            }
435 436
        }
    }
K
Kevin Ballard 已提交
437 438 439 440
    /// Removes the last path component from the receiver.
    /// Returns `true` if the receiver was modified, or `false` if it already
    /// represented the root of the file hierarchy.
    fn pop(&mut self) -> bool;
441

442 443
    /// Returns a new Path constructed by joining `self` with the given path
    /// (as a byte vector or string).
444 445 446 447 448 449
    /// If the given path is absolute, the new Path will represent just that.
    ///
    /// # Failure
    ///
    /// Raises the `null_byte` condition if the path contains a NUL.
    #[inline]
450
    fn join<T: BytesContainer>(&self, path: T) -> Self {
451 452 453 454
        let mut p = self.clone();
        p.push(path);
        p
    }
455 456
    /// Returns a new Path constructed by joining `self` with the given paths
    /// (as byte vectors or strings).
457 458
    /// See `join` for details.
    #[inline]
459
    fn join_many<T: BytesContainer>(&self, paths: &[T]) -> Self {
460 461 462 463
        let mut p = self.clone();
        p.push_many(paths);
        p
    }
464 465

    /// Returns whether `self` represents an absolute path.
K
Kevin Ballard 已提交
466 467
    /// An absolute path is defined as one that, when joined to another path, will
    /// yield back the same absolute path.
468 469
    fn is_absolute(&self) -> bool;

470 471 472 473 474 475 476 477
    /// Returns whether `self` represents a relative path.
    /// Typically this is the inverse of `is_absolute`.
    /// But for Windows paths, it also means the path is not volume-relative or
    /// relative to the current working directory.
    fn is_relative(&self) -> bool {
        !self.is_absolute()
    }

478 479 480 481 482 483 484 485 486 487
    /// Returns whether `self` is equal to, or is an ancestor of, the given path.
    /// If both paths are relative, they are compared as though they are relative
    /// to the same parent path.
    fn is_ancestor_of(&self, other: &Self) -> bool;

    /// Returns the Path that, were it joined to `base`, would yield `self`.
    /// If no such path exists, None is returned.
    /// If `self` is absolute and `base` is relative, or on Windows if both
    /// paths refer to separate drives, an absolute path is returned.
    fn path_relative_from(&self, base: &Self) -> Option<Self>;
488

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    /// Returns whether the relative path `child` is a suffix of `self`.
    fn ends_with_path(&self, child: &Self) -> bool;
}

/// A trait that represents something bytes-like (e.g. a &[u8] or a &str)
pub trait BytesContainer {
    /// Returns a &[u8] representing the receiver
    fn container_as_bytes<'a>(&'a self) -> &'a [u8];
    /// Consumes the receiver and converts it into ~[u8]
    #[inline]
    fn container_into_owned_bytes(self) -> ~[u8] {
        self.container_as_bytes().to_owned()
    }
    /// Returns the receiver interpreted as a utf-8 string
    ///
    /// # Failure
    ///
    /// Raises `str::null_byte` if not utf-8
    #[inline]
    fn container_as_str<'a>(&'a self) -> &'a str {
509
        str::from_utf8(self.container_as_bytes())
510 511 512 513
    }
    /// Returns the receiver interpreted as a utf-8 string, if possible
    #[inline]
    fn container_as_str_opt<'a>(&'a self) -> Option<&'a str> {
514
        str::from_utf8_opt(self.container_as_bytes())
515
    }
516
    /// Returns whether .container_as_str() is guaranteed to not fail
517 518 519
    // FIXME (#8888): Remove unused arg once ::<for T> works
    #[inline]
    fn is_str(_: Option<Self>) -> bool { false }
520 521 522 523
}

/// A trait that represents the unsafe operations on GenericPaths
pub trait GenericPathUnsafe {
524
    /// Creates a new Path without checking for null bytes.
525
    /// The resulting Path will always be normalized.
526
    unsafe fn new_unchecked<T: BytesContainer>(path: T) -> Self;
527

528 529
    /// Replaces the filename portion of the path without checking for null
    /// bytes.
530
    /// See `set_filename` for details.
531
    unsafe fn set_filename_unchecked<T: BytesContainer>(&mut self, filename: T);
K
Kevin Ballard 已提交
532

533
    /// Pushes a path onto `self` without checking for null bytes.
534
    /// See `push` for details.
535
    unsafe fn push_unchecked<T: BytesContainer>(&mut self, path: T);
536 537
}

538
/// Helper struct for printing paths with format!()
E
Erik Price 已提交
539 540
pub struct Display<'a, P> {
    priv path: &'a P,
541
    priv filename: bool
542 543
}

E
Erik Price 已提交
544
impl<'a, P: GenericPath> fmt::Default for Display<'a, P> {
545
    fn fmt(d: &Display<P>, f: &mut fmt::Formatter) {
546
        d.with_str(|s| f.pad(s))
547 548 549
    }
}

E
Erik Price 已提交
550
impl<'a, P: GenericPath> ToStr for Display<'a, P> {
551 552 553 554 555
    /// Returns the path as a string
    ///
    /// If the path is not UTF-8, invalid sequences with be replaced with the
    /// unicode replacement char. This involves allocation.
    fn to_str(&self) -> ~str {
556 557 558 559 560 561 562 563
        if self.filename {
            match self.path.filename() {
                None => ~"",
                Some(v) => from_utf8_with_replacement(v)
            }
        } else {
            from_utf8_with_replacement(self.path.as_vec())
        }
564 565 566
    }
}

E
Erik Price 已提交
567
impl<'a, P: GenericPath> Display<'a, P> {
568 569 570 571 572
    /// Provides the path as a string to a closure
    ///
    /// If the path is not UTF-8, invalid sequences will be replaced with the
    /// unicode replacement char. This involves allocation.
    #[inline]
573
    pub fn with_str<T>(&self, f: |&str| -> T) -> T {
574 575 576
        let opt = if self.filename { self.path.filename_str() }
                  else { self.path.as_str() };
        match opt {
577 578 579 580 581
            Some(s) => f(s),
            None => {
                let s = self.to_str();
                f(s.as_slice())
            }
582 583 584 585
        }
    }
}

E
Erik Price 已提交
586
impl<'a> BytesContainer for &'a str {
587 588 589 590 591 592 593 594 595 596 597 598 599
    #[inline]
    fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
        self.as_bytes()
    }
    #[inline]
    fn container_as_str<'a>(&'a self) -> &'a str {
        *self
    }
    #[inline]
    fn container_as_str_opt<'a>(&'a self) -> Option<&'a str> {
        Some(*self)
    }
    #[inline]
E
Erik Price 已提交
600
    fn is_str(_: Option<&'a str>) -> bool { true }
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
}

impl BytesContainer for ~str {
    #[inline]
    fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
        self.as_bytes()
    }
    #[inline]
    fn container_into_owned_bytes(self) -> ~[u8] {
        self.into_bytes()
    }
    #[inline]
    fn container_as_str<'a>(&'a self) -> &'a str {
        self.as_slice()
    }
    #[inline]
    fn container_as_str_opt<'a>(&'a self) -> Option<&'a str> {
        Some(self.as_slice())
    }
    #[inline]
    fn is_str(_: Option<~str>) -> bool { true }
}

impl BytesContainer for @str {
    #[inline]
    fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
        self.as_bytes()
    }
    #[inline]
    fn container_as_str<'a>(&'a self) -> &'a str {
        self.as_slice()
    }
    #[inline]
    fn container_as_str_opt<'a>(&'a self) -> Option<&'a str> {
        Some(self.as_slice())
    }
    #[inline]
    fn is_str(_: Option<@str>) -> bool { true }
}

E
Erik Price 已提交
641
impl<'a> BytesContainer for &'a [u8] {
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
    #[inline]
    fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
        *self
    }
}

impl BytesContainer for ~[u8] {
    #[inline]
    fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
        self.as_slice()
    }
    #[inline]
    fn container_into_owned_bytes(self) -> ~[u8] {
        self
    }
}

impl BytesContainer for @[u8] {
    #[inline]
    fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
        self.as_slice()
    }
}

666 667 668 669 670 671 672 673
impl BytesContainer for CString {
    #[inline]
    fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
        let s = self.as_bytes();
        s.slice_to(s.len()-1)
    }
}

674 675 676 677
#[inline(always)]
fn contains_nul(v: &[u8]) -> bool {
    v.iter().any(|&x| x == 0)
}
K
Kevin Ballard 已提交
678

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
#[inline(always)]
fn from_utf8_with_replacement(mut v: &[u8]) -> ~str {
    // FIXME (#9516): Don't decode utf-8 manually here once we have a good way to do it in str
    // This is a truly horrifically bad implementation, done as a functionality stopgap until
    // we have a proper utf-8 decoder. I don't really want to write one here.
    static REPLACEMENT_CHAR: char = '\uFFFD';

    let mut s = str::with_capacity(v.len());
    while !v.is_empty() {
        let w = str::utf8_char_width(v[0]);
        if w == 0u {
            s.push_char(REPLACEMENT_CHAR);
            v = v.slice_from(1);
        } else if v.len() < w || !str::is_utf8(v.slice_to(w)) {
            s.push_char(REPLACEMENT_CHAR);
            v = v.slice_from(1);
        } else {
            s.push_str(unsafe { ::cast::transmute(v.slice_to(w)) });
            v = v.slice_from(w);
        }
    }
    s
}
#[cfg(test)]
mod tests {
704
    use prelude::*;
705 706 707 708
    use super::{GenericPath, PosixPath, WindowsPath};
    use c_str::ToCStr;

    #[test]
709
    fn test_cstring() {
710
        let input = "/foo/bar/baz";
711
        let path: PosixPath = PosixPath::new(input.to_c_str());
712 713
        assert_eq!(path.as_vec(), input.as_bytes());

714
        let input = r"\foo\bar\baz";
715
        let path: WindowsPath = WindowsPath::new(input.to_c_str());
716
        assert_eq!(path.as_str().unwrap(), input.as_slice());
717 718
    }
}