]> git.lizzy.rs Git - rust.git/commitdiff
std: Add a new `fs` module
authorAlex Crichton <alex@alexcrichton.com>
Tue, 3 Feb 2015 05:39:14 +0000 (21:39 -0800)
committerAlex Crichton <alex@alexcrichton.com>
Tue, 10 Feb 2015 02:43:12 +0000 (18:43 -0800)
This commit is an implementation of [RFC 739][rfc] which adds a new `std::fs`
module to the standard library. This module provides much of the same
functionality as `std::old_io::fs` but it has many tweaked APIs as well as uses
the new `std::path` module.

[rfc]: https://github.com/rust-lang/rfcs/pull/739

15 files changed:
src/libstd/fs.rs [new file with mode: 0644]
src/libstd/io/prelude.rs
src/libstd/lib.rs
src/libstd/path.rs
src/libstd/sys/common/mod.rs
src/libstd/sys/unix/c.rs
src/libstd/sys/unix/ext.rs
src/libstd/sys/unix/fd.rs [new file with mode: 0644]
src/libstd/sys/unix/fs2.rs [new file with mode: 0644]
src/libstd/sys/unix/mod.rs
src/libstd/sys/windows/ext.rs
src/libstd/sys/windows/fs2.rs [new file with mode: 0644]
src/libstd/sys/windows/handle.rs
src/libstd/sys/windows/mod.rs
src/libstd/sys/windows/os.rs

diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs
new file mode 100644 (file)
index 0000000..45de678
--- /dev/null
@@ -0,0 +1,1501 @@
+// Copyright 2015 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.
+
+//! Filesystem manipulation operations
+//!
+//! This module contains basic methods to manipulate the contents of the local
+//! filesystem. All methods in this module represent cross-platform filesystem
+//! operations. Extra platform-specific functionality can be found in the
+//! extension traits of `std::os::$platform`.
+
+#![unstable(feature = "fs")]
+
+use core::prelude::*;
+
+use io::{self, Error, ErrorKind, SeekFrom, Seek, Read, Write};
+use path::{AsPath, Path, PathBuf};
+use sys::fs2 as fs_imp;
+use sys_common::{AsInnerMut, FromInner, AsInner};
+use vec::Vec;
+
+/// A reference to an open file on the filesystem.
+///
+/// An instance of a `File` can be read and/or written depending on what options
+/// it was opened with. Files also implement `Seek` to alter the logical cursor
+/// that the file contains internally.
+///
+/// # Example
+///
+/// ```no_run
+/// use std::io::prelude::*;
+/// use std::fs::File;
+///
+/// # fn foo() -> std::io::Result<()> {
+/// let mut f = try!(File::create("foo.txt"));
+/// try!(f.write_all(b"Hello, world!"));
+///
+/// let mut f = try!(File::open("foo.txt"));
+/// let mut s = String::new();
+/// try!(f.read_to_string(&mut s));
+/// assert_eq!(s, "Hello, world!");
+/// # Ok(())
+/// # }
+/// ```
+pub struct File {
+    inner: fs_imp::File,
+    path: PathBuf,
+}
+
+/// Metadata information about a file.
+///
+/// This structure is returned from the `metadata` function or method and
+/// represents known metadata about a file such as its permissions, size,
+/// modification times, etc.
+pub struct Metadata(fs_imp::FileAttr);
+
+/// Iterator over the entries in a directory.
+///
+/// This iterator is returned from the `read_dir` function of this module and
+/// will yield instances of `io::Result<DirEntry>`. Through a `DirEntry`
+/// information like the entry's path and possibly other metadata can be
+/// learned.
+pub struct ReadDir(fs_imp::ReadDir);
+
+/// Entries returned by the `ReadDir` iterator.
+///
+/// An instance of `DirEntry` represents an entry inside of a directory on the
+/// filesystem. Each entry can be inspected via methods to learn about the full
+/// path or possibly other metadata through per-platform extension traits.
+pub struct DirEntry(fs_imp::DirEntry);
+
+/// An iterator that recursively walks over the contents of a directory.
+pub struct WalkDir {
+    cur: Option<ReadDir>,
+    stack: Vec<io::Result<ReadDir>>,
+}
+
+/// Options and flags which can be used to configure how a file is opened.
+///
+/// This builder exposes the ability to configure how a `File` is opened and
+/// what operations are permitted on the open file. The `File::open` and
+/// `File::create` methods are aliases for commonly used options using this
+/// builder.
+#[derive(Clone)]
+pub struct OpenOptions(fs_imp::OpenOptions);
+
+/// Representation of the various permissions on a file.
+///
+/// This module only currently provides one bit of information, `readonly`,
+/// which is exposed on all currently supported platforms. Unix-specific
+/// functionality, such as mode bits, is available through the
+/// `os::unix::PermissionsExt` trait.
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct Permissions(fs_imp::FilePermissions);
+
+impl File {
+    /// Attempts to open a file in read-only mode.
+    ///
+    /// See the `OpenOptions::open` method for more details.
+    ///
+    /// # Errors
+    ///
+    /// This function will return an error if `path` does not already exist.
+    /// Other errors may also be returned according to `OpenOptions::open`.
+    pub fn open<P: AsPath + ?Sized>(path: &P) -> io::Result<File> {
+        OpenOptions::new().read(true).open(path)
+    }
+
+    /// Creates a open a file in write-only mode.
+    ///
+    /// This method will attempt to open a new file, truncating it if it already
+    /// exists.
+    ///
+    /// See the `OpenOptions::open` function for more details.
+    pub fn create<P: AsPath + ?Sized>(path: &P) -> io::Result<File> {
+        OpenOptions::new().write(true).create(true).truncate(true).open(path)
+    }
+
+    /// Returns the original path that was used to open this file.
+    pub fn path(&self) -> Option<&Path> {
+        Some(&self.path)
+    }
+
+    /// Attempt to sync all OS-internal metadata to disk.
+    ///
+    /// This function will attempt to ensure that all in-core data reaches the
+    /// filesystem before returning.
+    pub fn sync_all(&self) -> io::Result<()> {
+        self.inner.fsync()
+    }
+
+    /// This function is similar to `sync_all`, except that it may not
+    /// synchronize file metadata to the filesystem.
+    ///
+    /// This is intended for use cases that must synchronize content, but don't
+    /// need the metadata on disk. The goal of this method is to reduce disk
+    /// operations.
+    ///
+    /// Note that some platforms may simply implement this in terms of
+    /// `sync_all`.
+    pub fn sync_data(&self) -> io::Result<()> {
+        self.inner.datasync()
+    }
+
+    /// Truncates or extends the underlying file, updating the size of
+    /// this file to become `size`.
+    ///
+    /// If the `size` is less than the current file's size, then the file will
+    /// be shrunk. If it is greater than the current file's size, then the file
+    /// will be extended to `size` and have all of the intermediate data filled
+    /// in with 0s.
+    pub fn set_len(&self, size: u64) -> io::Result<()> {
+        self.inner.truncate(size)
+    }
+
+    /// Queries information about the underlying file.
+    pub fn metadata(&self) -> io::Result<Metadata> {
+        self.inner.file_attr().map(Metadata)
+    }
+}
+
+impl AsInner<fs_imp::File> for File {
+    fn as_inner(&self) -> &fs_imp::File { &self.inner }
+}
+impl Read for File {
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        self.inner.read(buf)
+    }
+}
+impl Write for File {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.inner.write(buf)
+    }
+    fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+}
+impl Seek for File {
+    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
+        self.inner.seek(pos)
+    }
+}
+impl<'a> Read for &'a File {
+    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
+        self.inner.read(buf)
+    }
+}
+impl<'a> Write for &'a File {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        self.inner.write(buf)
+    }
+    fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
+}
+impl<'a> Seek for &'a File {
+    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
+        self.inner.seek(pos)
+    }
+}
+
+impl OpenOptions {
+    /// Creates a blank net set of options ready for configuration.
+    ///
+    /// All options are initially set to `false`.
+    pub fn new() -> OpenOptions {
+        OpenOptions(fs_imp::OpenOptions::new())
+    }
+
+    /// Set the option for read access.
+    ///
+    /// This option, when true, will indicate that the file should be
+    /// `read`-able if opened.
+    pub fn read(&mut self, read: bool) -> &mut OpenOptions {
+        self.0.read(read); self
+    }
+
+    /// Set the option for write access.
+    ///
+    /// This option, when true, will indicate that the file should be
+    /// `write`-able if opened.
+    pub fn write(&mut self, write: bool) -> &mut OpenOptions {
+        self.0.write(write); self
+    }
+
+    /// Set the option for the append mode.
+    ///
+    /// This option, when true, means that writes will append to a file instead
+    /// of overwriting previous contents.
+    pub fn append(&mut self, append: bool) -> &mut OpenOptions {
+        self.0.append(append); self
+    }
+
+    /// Set the option for truncating a previous file.
+    ///
+    /// If a file is successfully opened with this option set it will truncate
+    /// the file to 0 length if it already exists.
+    pub fn truncate(&mut self, truncate: bool) -> &mut OpenOptions {
+        self.0.truncate(truncate); self
+    }
+
+    /// Set the option for creating a new file.
+    ///
+    /// This option indicates whether a new file will be created if the file
+    /// does not yet already exist.
+    pub fn create(&mut self, create: bool) -> &mut OpenOptions {
+        self.0.create(create); self
+    }
+
+    /// Open a file at `path` with the options specified by `self`.
+    ///
+    /// # Errors
+    ///
+    /// This function will return an error under a number of different
+    /// circumstances, to include but not limited to:
+    ///
+    /// * Opening a file that does not exist with read access.
+    /// * Attempting to open a file with access that the user lacks
+    ///   permissions for
+    /// * Filesystem-level errors (full disk, etc)
+    pub fn open<P: AsPath + ?Sized>(&self, path: &P) -> io::Result<File> {
+        let path = path.as_path();
+        let inner = try!(fs_imp::File::open(path, &self.0));
+
+        // On *BSD systems, we can open a directory as a file and read from
+        // it: fd=open("/tmp", O_RDONLY); read(fd, buf, N); due to an old
+        // tradition before the introduction of opendir(3).  We explicitly
+        // reject it because there are few use cases.
+        if cfg!(not(any(target_os = "linux", target_os = "android"))) &&
+           try!(inner.file_attr()).is_dir() {
+            Err(Error::new(ErrorKind::InvalidInput, "is a directory", None))
+        } else {
+            Ok(File { path: path.to_path_buf(), inner: inner })
+        }
+    }
+}
+impl AsInnerMut<fs_imp::OpenOptions> for OpenOptions {
+    fn as_inner_mut(&mut self) -> &mut fs_imp::OpenOptions { &mut self.0 }
+}
+
+impl Metadata {
+    /// Returns whether this metadata is for a directory.
+    pub fn is_dir(&self) -> bool { self.0.is_dir() }
+
+    /// Returns whether this metadata is for a regular file.
+    pub fn is_file(&self) -> bool { self.0.is_file() }
+
+    /// Returns the size of the file, in bytes, this metadata is for.
+    pub fn len(&self) -> u64 { self.0.size() }
+
+    /// Returns the permissions of the file this metadata is for.
+    pub fn permissions(&self) -> Permissions {
+        Permissions(self.0.perm())
+    }
+
+    /// Returns the most recent access time for a file.
+    ///
+    /// The return value is in milliseconds since the epoch.
+    pub fn accessed(&self) -> u64 { self.0.accessed() }
+
+    /// Returns the most recent modification time for a file.
+    ///
+    /// The return value is in milliseconds since the epoch.
+    pub fn modified(&self) -> u64 { self.0.modified() }
+}
+
+impl Permissions {
+    /// Returns whether these permissions describe a readonly file.
+    pub fn readonly(&self) -> bool { self.0.readonly() }
+
+    /// Modify the readonly flag for this set of permissions.
+    ///
+    /// This operation does **not** modify the filesystem. To modify the
+    /// filesystem use the `fs::set_permissions` function.
+    pub fn set_readonly(&mut self, readonly: bool) {
+        self.0.set_readonly(readonly)
+    }
+}
+
+impl FromInner<fs_imp::FilePermissions> for Permissions {
+    fn from_inner(f: fs_imp::FilePermissions) -> Permissions {
+        Permissions(f)
+    }
+}
+
+impl Iterator for ReadDir {
+    type Item = io::Result<DirEntry>;
+
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        self.0.next().map(|entry| entry.map(DirEntry))
+    }
+}
+
+impl DirEntry {
+    /// Returns the full path to the file that this entry represents.
+    ///
+    /// The full path is created by joining the original path to `read_dir` or
+    /// `walk_dir` with the filename of this entry.
+    pub fn path(&self) -> PathBuf { self.0.path() }
+}
+
+/// Remove a file from the underlying filesystem.
+///
+/// # Example
+///
+/// ```rust,no_run
+/// use std::fs;
+///
+/// fs::remove_file("/some/file/path.txt");
+/// ```
+///
+/// Note that, just because an unlink call was successful, it is not
+/// guaranteed that a file is immediately deleted (e.g. depending on
+/// platform, other open file descriptors may prevent immediate removal).
+///
+/// # Errors
+///
+/// This function will return an error if `path` points to a directory, if the
+/// user lacks permissions to remove the file, or if some other filesystem-level
+/// error occurs.
+pub fn remove_file<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    let path = path.as_path();
+    let e = match fs_imp::unlink(path) {
+        Ok(()) => return Ok(()),
+        Err(e) => e,
+    };
+    if !cfg!(windows) { return Err(e) }
+
+    // On unix, a readonly file can be successfully removed. On windows,
+    // however, it cannot. To keep the two platforms in line with
+    // respect to their behavior, catch this case on windows, attempt to
+    // change it to read-write, and then remove the file.
+    if e.kind() != ErrorKind::PermissionDenied { return Err(e) }
+
+    let attr = match metadata(path) { Ok(a) => a, Err(..) => return Err(e) };
+    let mut perms = attr.permissions();
+    if !perms.readonly() { return Err(e) }
+    perms.set_readonly(false);
+
+    if set_permissions(path, perms).is_err() { return Err(e) }
+    if fs_imp::unlink(path).is_ok() { return Ok(()) }
+
+    // Oops, try to put things back the way we found it
+    let _ = set_permissions(path, attr.permissions());
+    Err(e)
+}
+
+/// Given a path, query the file system to get information about a file,
+/// directory, etc.
+///
+/// This function will traverse soft links to query information about the
+/// destination file.
+///
+/// # Example
+///
+/// ```rust,no_run
+/// # fn foo() -> std::io::Result<()> {
+/// use std::fs;
+///
+/// let attr = try!(fs::metadata("/some/file/path.txt"));
+/// // inspect attr ...
+/// # Ok(())
+/// # }
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the user lacks the requisite
+/// permissions to perform a `metadata` call on the given `path` or if there
+/// is no entry in the filesystem at the provided path.
+pub fn metadata<P: AsPath + ?Sized>(path: &P) -> io::Result<Metadata> {
+    fs_imp::stat(path.as_path()).map(Metadata)
+}
+
+/// Rename a file or directory to a new name.
+///
+/// # Example
+///
+/// ```rust,no_run
+/// use std::fs;
+///
+/// fs::rename("foo", "bar");
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the provided `from` doesn't exist, if
+/// the process lacks permissions to view the contents, if `from` and `to`
+/// reside on separate filesystems, or if some other intermittent I/O error
+/// occurs.
+pub fn rename<P: AsPath + ?Sized, Q: AsPath + ?Sized>(from: &P, to: &Q)
+                                                      -> io::Result<()> {
+    fs_imp::rename(from.as_path(), to.as_path())
+}
+
+/// Copies the contents of one file to another. This function will also
+/// copy the permission bits of the original file to the destination file.
+///
+/// This function will **overwrite** the contents of `to`.
+///
+/// Note that if `from` and `to` both point to the same file, then the file
+/// will likely get truncated by this operation.
+///
+/// # Example
+///
+/// ```rust
+/// use std::fs;
+///
+/// fs::copy("foo.txt", "bar.txt");
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error in the following situations, but is not
+/// limited to just these cases:
+///
+/// * The `from` path is not a file
+/// * The `from` file does not exist
+/// * The current process does not have the permission rights to access
+///   `from` or write `to`
+pub fn copy<P: AsPath + ?Sized, Q: AsPath + ?Sized>(from: &P, to: &Q)
+                                                    -> io::Result<u64> {
+    let from = from.as_path();
+    if !from.is_file() {
+        return Err(Error::new(ErrorKind::MismatchedFileTypeForOperation,
+                              "the source path is not an existing file",
+                              None))
+    }
+
+    let mut reader = try!(File::open(from));
+    let mut writer = try!(File::create(to));
+    let perm = try!(reader.metadata()).permissions();
+
+    let ret = try!(io::copy(&mut reader, &mut writer));
+    try!(set_permissions(to, perm));
+    Ok(ret)
+}
+
+/// Creates a new hard link on the filesystem.
+///
+/// The `dst` path will be a link pointing to the `src` path. Note that systems
+/// often require these two paths to both be located on the same filesystem.
+pub fn hard_link<P: AsPath + ?Sized, Q: AsPath + ?Sized>(src: &P, dst: &Q)
+                                                         -> io::Result<()> {
+    fs_imp::link(src.as_path(), dst.as_path())
+}
+
+/// Creates a new soft link on the filesystem.
+///
+/// The `dst` path will be a soft link pointing to the `src` path.
+pub fn soft_link<P: AsPath + ?Sized, Q: AsPath + ?Sized>(src: &P, dst: &Q)
+                                                         -> io::Result<()> {
+    fs_imp::symlink(src.as_path(), dst.as_path())
+}
+
+/// Reads a soft link, returning the file that the link points to.
+///
+/// # Errors
+///
+/// This function will return an error on failure. Failure conditions include
+/// reading a file that does not exist or reading a file that is not a soft
+/// link.
+pub fn read_link<P: AsPath + ?Sized>(path: &P) -> io::Result<PathBuf> {
+    fs_imp::readlink(path.as_path())
+}
+
+/// Create a new, empty directory at the provided path
+///
+/// # Example
+///
+/// ```rust
+/// use std::fs;
+///
+/// fs::create_dir("/some/dir");
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the user lacks permissions to make a
+/// new directory at the provided `path`, or if the directory already exists.
+pub fn create_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    fs_imp::mkdir(path.as_path())
+}
+
+/// Recursively create a directory and all of its parent components if they
+/// are missing.
+///
+/// # Errors
+///
+/// This function will fail if any directory in the path specified by `path`
+/// does not already exist and it could not be created otherwise. The specific
+/// error conditions for when a directory is being created (after it is
+/// determined to not exist) are outlined by `fs::create_dir`.
+pub fn create_dir_all<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    let path = path.as_path();
+    if path.is_dir() { return Ok(()) }
+    match path.parent() {
+        Some(p) if p != path => try!(create_dir_all(p)),
+        _ => {}
+    }
+    create_dir(path)
+}
+
+/// Remove an existing, empty directory
+///
+/// # Example
+///
+/// ```rust
+/// use std::fs;
+///
+/// fs::remove_dir("/some/dir");
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the user lacks permissions to remove
+/// the directory at the provided `path`, or if the directory isn't empty.
+pub fn remove_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    fs_imp::rmdir(path.as_path())
+}
+
+/// Removes a directory at this path, after removing all its contents. Use
+/// carefully!
+///
+/// This function does **not** follow soft links and it will simply remove the
+/// soft link itself.
+///
+/// # Errors
+///
+/// See `file::remove_file` and `fs::remove_dir`
+pub fn remove_dir_all<P: AsPath + ?Sized>(path: &P) -> io::Result<()> {
+    let path = path.as_path();
+    for child in try!(read_dir(path)) {
+        let child = try!(child).path();
+        let stat = try!(lstat(&*child));
+        if stat.is_dir() {
+            try!(remove_dir_all(&*child));
+        } else {
+            try!(remove_file(&*child));
+        }
+    }
+    return remove_dir(path);
+
+    #[cfg(unix)]
+    fn lstat(path: &Path) -> io::Result<fs_imp::FileAttr> { fs_imp::lstat(path) }
+    #[cfg(windows)]
+    fn lstat(path: &Path) -> io::Result<fs_imp::FileAttr> { fs_imp::stat(path) }
+}
+
+/// Returns an iterator over the entries within a directory.
+///
+/// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
+/// be encountered after an iterator is initially constructed.
+///
+/// # Example
+///
+/// ```rust
+/// use std::io;
+/// use std::fs::{self, PathExt, DirEntry};
+/// use std::path::Path;
+///
+/// // one possible implementation of fs::walk_dir only visiting files
+/// fn visit_dirs(dir: &Path, cb: &mut FnMut(DirEntry)) -> io::Result<()> {
+///     if dir.is_dir() {
+///         for entry in try!(fs::read_dir(dir)) {
+///             let entry = try!(entry);
+///             if entry.path().is_dir() {
+///                 try!(visit_dirs(&entry.path(), cb));
+///             } else {
+///                 cb(entry);
+///             }
+///         }
+///     }
+///     Ok(())
+/// }
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the provided `path` doesn't exist, if
+/// the process lacks permissions to view the contents or if the `path` points
+/// at a non-directory file
+pub fn read_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<ReadDir> {
+    fs_imp::readdir(path.as_path()).map(ReadDir)
+}
+
+/// Returns an iterator that will recursively walk the directory structure
+/// rooted at `path`.
+///
+/// The path given will not be iterated over, and this will perform iteration in
+/// some top-down order.  The contents of unreadable subdirectories are ignored.
+///
+/// The iterator will yield instances of `io::Result<DirEntry>`. New errors may
+/// be encountered after an iterator is initially constructed.
+pub fn walk_dir<P: AsPath + ?Sized>(path: &P) -> io::Result<WalkDir> {
+    let start = try!(read_dir(path));
+    Ok(WalkDir { cur: Some(start), stack: Vec::new() })
+}
+
+impl Iterator for WalkDir {
+    type Item = io::Result<DirEntry>;
+
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        loop {
+            if let Some(ref mut cur) = self.cur {
+                match cur.next() {
+                    Some(Err(e)) => return Some(Err(e)),
+                    Some(Ok(next)) => {
+                        let path = next.path();
+                        if path.is_dir() {
+                            self.stack.push(read_dir(&*path));
+                        }
+                        return Some(Ok(next))
+                    }
+                    None => {}
+                }
+            }
+            self.cur = None;
+            match self.stack.pop() {
+                Some(Err(e)) => return Some(Err(e)),
+                Some(Ok(next)) => self.cur = Some(next),
+                None => return None,
+            }
+        }
+    }
+}
+
+/// Utility methods for paths.
+pub trait PathExt {
+    /// Get information on the file, directory, etc at this path.
+    ///
+    /// Consult the `fs::stat` documentation for more info.
+    ///
+    /// This call preserves identical runtime/error semantics with `file::stat`.
+    fn metadata(&self) -> io::Result<Metadata>;
+
+    /// Boolean value indicator whether the underlying file exists on the local
+    /// filesystem. Returns false in exactly the cases where `fs::stat` fails.
+    fn exists(&self) -> bool;
+
+    /// Whether the underlying implementation (be it a file path, or something
+    /// else) points at a "regular file" on the FS. Will return false for paths
+    /// to non-existent locations or directories or other non-regular files
+    /// (named pipes, etc). Follows links when making this determination.
+    fn is_file(&self) -> bool;
+
+    /// Whether the underlying implementation (be it a file path, or something
+    /// else) is pointing at a directory in the underlying FS. Will return
+    /// false for paths to non-existent locations or if the item is not a
+    /// directory (eg files, named pipes, etc). Follows links when making this
+    /// determination.
+    fn is_dir(&self) -> bool;
+}
+
+impl PathExt for Path {
+    fn metadata(&self) -> io::Result<Metadata> { metadata(self) }
+
+    fn exists(&self) -> bool { metadata(self).is_ok() }
+
+    fn is_file(&self) -> bool {
+        metadata(self).map(|s| s.is_file()).unwrap_or(false)
+    }
+    fn is_dir(&self) -> bool {
+        metadata(self).map(|s| s.is_dir()).unwrap_or(false)
+    }
+}
+
+/// Changes the timestamps for a file's last modification and access time.
+///
+/// The file at the path specified will have its last access time set to
+/// `atime` and its modification time set to `mtime`. The times specified should
+/// be in milliseconds.
+pub fn set_file_times<P: AsPath + ?Sized>(path: &P, accessed: u64,
+                                          modified: u64) -> io::Result<()> {
+    fs_imp::utimes(path.as_path(), accessed, modified)
+}
+
+/// Changes the permissions found on a file or a directory.
+///
+/// # Example
+///
+/// ```
+/// # fn foo() -> std::io::Result<()> {
+/// use std::fs;
+///
+/// let mut perms = try!(fs::metadata("foo.txt")).permissions();
+/// perms.set_readonly(true);
+/// try!(fs::set_permissions("foo.txt", perms));
+/// # Ok(())
+/// # }
+/// ```
+///
+/// # Errors
+///
+/// This function will return an error if the provided `path` doesn't exist, if
+/// the process lacks permissions to change the attributes of the file, or if
+/// some other I/O error is encountered.
+pub fn set_permissions<P: AsPath + ?Sized>(path: &P, perm: Permissions)
+                                           -> io::Result<()> {
+    fs_imp::set_perm(path.as_path(), perm.0)
+}
+
+#[cfg(test)]
+mod tests {
+    use prelude::v1::*;
+    use io::prelude::*;
+
+    use fs::{self, File, OpenOptions};
+    use io::{ErrorKind, SeekFrom};
+    use path::PathBuf;
+    use path::Path as Path2;
+    use os;
+    use rand::{self, StdRng, Rng};
+    use str;
+
+    macro_rules! check { ($e:expr) => (
+        match $e {
+            Ok(t) => t,
+            Err(e) => panic!("{} failed with: {}", stringify!($e), e),
+        }
+    ) }
+
+    macro_rules! error { ($e:expr, $s:expr) => (
+        match $e {
+            Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s),
+            Err(ref err) => assert!(err.to_string().contains($s.as_slice()),
+                                    format!("`{}` did not contain `{}`", err, $s))
+        }
+    ) }
+
+    pub struct TempDir(PathBuf);
+
+    impl TempDir {
+        fn join(&self, path: &str) -> PathBuf {
+            let TempDir(ref p) = *self;
+            p.join(path)
+        }
+
+        fn path<'a>(&'a self) -> &'a Path2 {
+            let TempDir(ref p) = *self;
+            p
+        }
+    }
+
+    impl Drop for TempDir {
+        fn drop(&mut self) {
+            // Gee, seeing how we're testing the fs module I sure hope that we
+            // at least implement this correctly!
+            let TempDir(ref p) = *self;
+            check!(fs::remove_dir_all(p));
+        }
+    }
+
+    pub fn tmpdir() -> TempDir {
+        let s = os::tmpdir();
+        let p = Path2::new(s.as_str().unwrap());
+        let ret = p.join(&format!("rust-{}", rand::random::<u32>()));
+        check!(fs::create_dir(&ret));
+        TempDir(ret)
+    }
+
+    #[test]
+    fn file_test_io_smoke_test() {
+        let message = "it's alright. have a good time";
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test.txt");
+        {
+            let mut write_stream = check!(File::create(filename));
+            check!(write_stream.write(message.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+            let mut read_buf = [0; 1028];
+            let read_str = match check!(read_stream.read(&mut read_buf)) {
+                -1|0 => panic!("shouldn't happen"),
+                n => str::from_utf8(&read_buf[..n]).unwrap().to_string()
+            };
+            assert_eq!(read_str.as_slice(), message);
+        }
+        check!(fs::remove_file(filename));
+    }
+
+    #[test]
+    fn invalid_path_raises() {
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_that_does_not_exist.txt");
+        let result = File::open(filename);
+
+        if cfg!(unix) {
+            error!(result, "o such file or directory");
+        }
+        // error!(result, "couldn't open path as file");
+        // error!(result, format!("path={}; mode=open; access=read", filename.display()));
+    }
+
+    #[test]
+    fn file_test_iounlinking_invalid_path_should_raise_condition() {
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_another_file_that_does_not_exist.txt");
+
+        let result = fs::remove_file(filename);
+
+        if cfg!(unix) {
+            error!(result, "o such file or directory");
+        }
+        // error!(result, "couldn't unlink path");
+        // error!(result, format!("path={}", filename.display()));
+    }
+
+    #[test]
+    fn file_test_io_non_positional_read() {
+        let message: &str = "ten-four";
+        let mut read_mem = [0; 8];
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test_positional.txt");
+        {
+            let mut rw_stream = check!(File::create(filename));
+            check!(rw_stream.write(message.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+            {
+                let read_buf = &mut read_mem[0..4];
+                check!(read_stream.read(read_buf));
+            }
+            {
+                let read_buf = &mut read_mem[4..8];
+                check!(read_stream.read(read_buf));
+            }
+        }
+        check!(fs::remove_file(filename));
+        let read_str = str::from_utf8(&read_mem).unwrap();
+        assert_eq!(read_str, message);
+    }
+
+    #[test]
+    fn file_test_io_seek_and_tell_smoke_test() {
+        let message = "ten-four";
+        let mut read_mem = [0; 4];
+        let set_cursor = 4 as u64;
+        let mut tell_pos_pre_read;
+        let mut tell_pos_post_read;
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test_seeking.txt");
+        {
+            let mut rw_stream = check!(File::create(filename));
+            check!(rw_stream.write(message.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+            check!(read_stream.seek(SeekFrom::Start(set_cursor)));
+            tell_pos_pre_read = check!(read_stream.seek(SeekFrom::Current(0)));
+            check!(read_stream.read(&mut read_mem));
+            tell_pos_post_read = check!(read_stream.seek(SeekFrom::Current(0)));
+        }
+        check!(fs::remove_file(filename));
+        let read_str = str::from_utf8(&read_mem).unwrap();
+        assert_eq!(read_str, &message[4..8]);
+        assert_eq!(tell_pos_pre_read, set_cursor);
+        assert_eq!(tell_pos_post_read, message.len() as u64);
+    }
+
+    #[test]
+    fn file_test_io_seek_and_write() {
+        let initial_msg =   "food-is-yummy";
+        let overwrite_msg =    "-the-bar!!";
+        let final_msg =     "foo-the-bar!!";
+        let seek_idx = 3;
+        let mut read_mem = [0; 13];
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test_seek_and_write.txt");
+        {
+            let mut rw_stream = check!(File::create(filename));
+            check!(rw_stream.write(initial_msg.as_bytes()));
+            check!(rw_stream.seek(SeekFrom::Start(seek_idx)));
+            check!(rw_stream.write(overwrite_msg.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+            check!(read_stream.read(&mut read_mem));
+        }
+        check!(fs::remove_file(filename));
+        let read_str = str::from_utf8(&read_mem).unwrap();
+        assert!(read_str == final_msg);
+    }
+
+    #[test]
+    fn file_test_io_seek_shakedown() {
+        //                   01234567890123
+        let initial_msg =   "qwer-asdf-zxcv";
+        let chunk_one: &str = "qwer";
+        let chunk_two: &str = "asdf";
+        let chunk_three: &str = "zxcv";
+        let mut read_mem = [0; 4];
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_rt_io_file_test_seek_shakedown.txt");
+        {
+            let mut rw_stream = check!(File::create(filename));
+            check!(rw_stream.write(initial_msg.as_bytes()));
+        }
+        {
+            let mut read_stream = check!(File::open(filename));
+
+            check!(read_stream.seek(SeekFrom::End(-4)));
+            check!(read_stream.read(&mut read_mem));
+            assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_three);
+
+            check!(read_stream.seek(SeekFrom::Current(-9)));
+            check!(read_stream.read(&mut read_mem));
+            assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_two);
+
+            check!(read_stream.seek(SeekFrom::Start(0)));
+            check!(read_stream.read(&mut read_mem));
+            assert_eq!(str::from_utf8(&read_mem).unwrap(), chunk_one);
+        }
+        check!(fs::remove_file(filename));
+    }
+
+    #[test]
+    fn file_test_stat_is_correct_on_is_file() {
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_stat_correct_on_is_file.txt");
+        {
+            let mut opts = OpenOptions::new();
+            let mut fs = check!(opts.read(true).write(true)
+                                    .create(true).open(filename));
+            let msg = "hw";
+            fs.write(msg.as_bytes()).unwrap();
+
+            let fstat_res = check!(fs.metadata());
+            assert!(fstat_res.is_file());
+        }
+        let stat_res_fn = check!(fs::metadata(filename));
+        assert!(stat_res_fn.is_file());
+        let stat_res_meth = check!(filename.metadata());
+        assert!(stat_res_meth.is_file());
+        check!(fs::remove_file(filename));
+    }
+
+    #[test]
+    fn file_test_stat_is_correct_on_is_dir() {
+        let tmpdir = tmpdir();
+        let filename = &tmpdir.join("file_stat_correct_on_is_dir");
+        check!(fs::create_dir(filename));
+        let stat_res_fn = check!(fs::metadata(filename));
+        assert!(stat_res_fn.is_dir());
+        let stat_res_meth = check!(filename.metadata());
+        assert!(stat_res_meth.is_dir());
+        check!(fs::remove_dir(filename));
+    }
+
+    #[test]
+    fn file_test_fileinfo_false_when_checking_is_file_on_a_directory() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("fileinfo_false_on_dir");
+        check!(fs::create_dir(dir));
+        assert!(dir.is_file() == false);
+        check!(fs::remove_dir(dir));
+    }
+
+    #[test]
+    fn file_test_fileinfo_check_exists_before_and_after_file_creation() {
+        let tmpdir = tmpdir();
+        let file = &tmpdir.join("fileinfo_check_exists_b_and_a.txt");
+        check!(check!(File::create(file)).write(b"foo"));
+        assert!(file.exists());
+        check!(fs::remove_file(file));
+        assert!(!file.exists());
+    }
+
+    #[test]
+    fn file_test_directoryinfo_check_exists_before_and_after_mkdir() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("before_and_after_dir");
+        assert!(!dir.exists());
+        check!(fs::create_dir(dir));
+        assert!(dir.exists());
+        assert!(dir.is_dir());
+        check!(fs::remove_dir(dir));
+        assert!(!dir.exists());
+    }
+
+    #[test]
+    fn file_test_directoryinfo_readdir() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("di_readdir");
+        check!(fs::create_dir(dir));
+        let prefix = "foo";
+        for n in range(0, 3) {
+            let f = dir.join(&format!("{}.txt", n));
+            let mut w = check!(File::create(&f));
+            let msg_str = format!("{}{}", prefix, n.to_string());
+            let msg = msg_str.as_bytes();
+            check!(w.write(msg));
+        }
+        let mut files = check!(fs::read_dir(dir));
+        let mut mem = [0u8; 4];
+        for f in files {
+            let f = f.unwrap().path();
+            {
+                let n = f.file_stem().unwrap();
+                check!(check!(File::open(&f)).read(&mut mem));
+                let read_str = str::from_utf8(&mem).unwrap();
+                let expected = format!("{}{}", prefix, n.to_str().unwrap());
+                assert_eq!(expected.as_slice(), read_str);
+            }
+            check!(fs::remove_file(&f));
+        }
+        check!(fs::remove_dir(dir));
+    }
+
+    #[test]
+    fn file_test_walk_dir() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("walk_dir");
+        check!(fs::create_dir(dir));
+
+        let dir1 = &dir.join("01/02/03");
+        check!(fs::create_dir_all(dir1));
+        check!(File::create(&dir1.join("04")));
+
+        let dir2 = &dir.join("11/12/13");
+        check!(fs::create_dir_all(dir2));
+        check!(File::create(&dir2.join("14")));
+
+        let mut files = check!(fs::walk_dir(dir));
+        let mut cur = [0u8; 2];
+        for f in files {
+            let f = f.unwrap().path();
+            let stem = f.file_stem().unwrap().to_str().unwrap();
+            let root = stem.as_bytes()[0] - b'0';
+            let name = stem.as_bytes()[1] - b'0';
+            assert!(cur[root as usize] < name);
+            cur[root as usize] = name;
+        }
+
+        check!(fs::remove_dir_all(dir));
+    }
+
+    #[test]
+    fn mkdir_path_already_exists_error() {
+        let tmpdir = tmpdir();
+        let dir = &tmpdir.join("mkdir_error_twice");
+        check!(fs::create_dir(dir));
+        let e = fs::create_dir(dir).err().unwrap();
+        assert_eq!(e.kind(), ErrorKind::PathAlreadyExists);
+    }
+
+    #[test]
+    fn recursive_mkdir() {
+        let tmpdir = tmpdir();
+        let dir = tmpdir.join("d1/d2");
+        check!(fs::create_dir_all(&dir));
+        assert!(dir.is_dir())
+    }
+
+    #[test]
+    fn recursive_mkdir_failure() {
+        let tmpdir = tmpdir();
+        let dir = tmpdir.join("d1");
+        let file = dir.join("f1");
+
+        check!(fs::create_dir_all(&dir));
+        check!(File::create(&file));
+
+        let result = fs::create_dir_all(&file);
+
+        assert!(result.is_err());
+        // error!(result, "couldn't recursively mkdir");
+        // error!(result, "couldn't create directory");
+        // error!(result, "mode=0700");
+        // error!(result, format!("path={}", file.display()));
+    }
+
+    #[test]
+    fn recursive_mkdir_slash() {
+        check!(fs::create_dir_all(&Path2::new("/")));
+    }
+
+    // FIXME(#12795) depends on lstat to work on windows
+    #[cfg(not(windows))]
+    #[test]
+    fn recursive_rmdir() {
+        let tmpdir = tmpdir();
+        let d1 = tmpdir.join("d1");
+        let dt = d1.join("t");
+        let dtt = dt.join("t");
+        let d2 = tmpdir.join("d2");
+        let canary = d2.join("do_not_delete");
+        check!(fs::create_dir_all(&dtt));
+        check!(fs::create_dir_all(&d2));
+        check!(check!(File::create(&canary)).write(b"foo"));
+        check!(fs::soft_link(&d2, &dt.join("d2")));
+        check!(fs::remove_dir_all(&d1));
+
+        assert!(!d1.is_dir());
+        assert!(canary.exists());
+    }
+
+    #[test]
+    fn unicode_path_is_dir() {
+        assert!(Path2::new(".").is_dir());
+        assert!(!Path2::new("test/stdtest/fs.rs").is_dir());
+
+        let tmpdir = tmpdir();
+
+        let mut dirpath = tmpdir.path().to_path_buf();
+        dirpath.push(&format!("test-가一ー你好"));
+        check!(fs::create_dir(&dirpath));
+        assert!(dirpath.is_dir());
+
+        let mut filepath = dirpath;
+        filepath.push("unicode-file-\u{ac00}\u{4e00}\u{30fc}\u{4f60}\u{597d}.rs");
+        check!(File::create(&filepath)); // ignore return; touch only
+        assert!(!filepath.is_dir());
+        assert!(filepath.exists());
+    }
+
+    #[test]
+    fn unicode_path_exists() {
+        assert!(Path2::new(".").exists());
+        assert!(!Path2::new("test/nonexistent-bogus-path").exists());
+
+        let tmpdir = tmpdir();
+        let unicode = tmpdir.path();
+        let unicode = unicode.join(&format!("test-각丁ー再见"));
+        check!(fs::create_dir(&unicode));
+        assert!(unicode.exists());
+        assert!(!Path2::new("test/unicode-bogus-path-각丁ー再见").exists());
+    }
+
+    #[test]
+    fn copy_file_does_not_exist() {
+        let from = Path2::new("test/nonexistent-bogus-path");
+        let to = Path2::new("test/other-bogus-path");
+
+        match fs::copy(&from, &to) {
+            Ok(..) => panic!(),
+            Err(..) => {
+                assert!(!from.exists());
+                assert!(!to.exists());
+            }
+        }
+    }
+
+    #[test]
+    fn copy_file_ok() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in.txt");
+        let out = tmpdir.join("out.txt");
+
+        check!(check!(File::create(&input)).write(b"hello"));
+        check!(fs::copy(&input, &out));
+        let mut v = Vec::new();
+        check!(check!(File::open(&out)).read_to_end(&mut v));
+        assert_eq!(v.as_slice(), b"hello");
+
+        assert_eq!(check!(input.metadata()).permissions(),
+                   check!(out.metadata()).permissions());
+    }
+
+    #[test]
+    fn copy_file_dst_dir() {
+        let tmpdir = tmpdir();
+        let out = tmpdir.join("out");
+
+        check!(File::create(&out));
+        match fs::copy(&*out, tmpdir.path()) {
+            Ok(..) => panic!(), Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn copy_file_dst_exists() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in");
+        let output = tmpdir.join("out");
+
+        check!(check!(File::create(&input)).write("foo".as_bytes()));
+        check!(check!(File::create(&output)).write("bar".as_bytes()));
+        check!(fs::copy(&input, &output));
+
+        let mut v = Vec::new();
+        check!(check!(File::open(&output)).read_to_end(&mut v));
+        assert_eq!(v, b"foo".to_vec());
+    }
+
+    #[test]
+    fn copy_file_src_dir() {
+        let tmpdir = tmpdir();
+        let out = tmpdir.join("out");
+
+        match fs::copy(tmpdir.path(), &out) {
+            Ok(..) => panic!(), Err(..) => {}
+        }
+        assert!(!out.exists());
+    }
+
+    #[test]
+    fn copy_file_preserves_perm_bits() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in.txt");
+        let out = tmpdir.join("out.txt");
+
+        let attr = check!(check!(File::create(&input)).metadata());
+        let mut p = attr.permissions();
+        p.set_readonly(true);
+        check!(fs::set_permissions(&input, p));
+        check!(fs::copy(&input, &out));
+        assert!(check!(out.metadata()).permissions().readonly());
+    }
+
+    #[cfg(not(windows))] // FIXME(#10264) operation not permitted?
+    #[test]
+    fn symlinks_work() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in.txt");
+        let out = tmpdir.join("out.txt");
+
+        check!(check!(File::create(&input)).write("foobar".as_bytes()));
+        check!(fs::soft_link(&input, &out));
+        // if cfg!(not(windows)) {
+        //     assert_eq!(check!(lstat(&out)).kind, FileType::Symlink);
+        //     assert_eq!(check!(out.lstat()).kind, FileType::Symlink);
+        // }
+        assert_eq!(check!(fs::metadata(&out)).len(),
+                   check!(fs::metadata(&input)).len());
+        let mut v = Vec::new();
+        check!(check!(File::open(&out)).read_to_end(&mut v));
+        assert_eq!(v, b"foobar".to_vec());
+    }
+
+    #[cfg(not(windows))] // apparently windows doesn't like symlinks
+    #[test]
+    fn symlink_noexist() {
+        let tmpdir = tmpdir();
+        // symlinks can point to things that don't exist
+        check!(fs::soft_link(&tmpdir.join("foo"), &tmpdir.join("bar")));
+        assert_eq!(check!(fs::read_link(&tmpdir.join("bar"))),
+                   tmpdir.join("foo"));
+    }
+
+    #[test]
+    fn readlink_not_symlink() {
+        let tmpdir = tmpdir();
+        match fs::read_link(tmpdir.path()) {
+            Ok(..) => panic!("wanted a failure"),
+            Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn links_work() {
+        let tmpdir = tmpdir();
+        let input = tmpdir.join("in.txt");
+        let out = tmpdir.join("out.txt");
+
+        check!(check!(File::create(&input)).write("foobar".as_bytes()));
+        check!(fs::hard_link(&input, &out));
+        assert_eq!(check!(fs::metadata(&out)).len(),
+                   check!(fs::metadata(&input)).len());
+        assert_eq!(check!(fs::metadata(&out)).len(),
+                   check!(input.metadata()).len());
+        let mut v = Vec::new();
+        check!(check!(File::open(&out)).read_to_end(&mut v));
+        assert_eq!(v, b"foobar".to_vec());
+
+        // can't link to yourself
+        match fs::hard_link(&input, &input) {
+            Ok(..) => panic!("wanted a failure"),
+            Err(..) => {}
+        }
+        // can't link to something that doesn't exist
+        match fs::hard_link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
+            Ok(..) => panic!("wanted a failure"),
+            Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn chmod_works() {
+        let tmpdir = tmpdir();
+        let file = tmpdir.join("in.txt");
+
+        check!(File::create(&file));
+        let attr = check!(fs::metadata(&file));
+        assert!(!attr.permissions().readonly());
+        let mut p = attr.permissions();
+        p.set_readonly(true);
+        check!(fs::set_permissions(&file, p.clone()));
+        let attr = check!(fs::metadata(&file));
+        assert!(attr.permissions().readonly());
+
+        match fs::set_permissions(&tmpdir.join("foo"), p) {
+            Ok(..) => panic!("wanted a panic"),
+            Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn sync_doesnt_kill_anything() {
+        let tmpdir = tmpdir();
+        let path = tmpdir.join("in.txt");
+
+        let mut file = check!(File::create(&path));
+        check!(file.sync_all());
+        check!(file.sync_data());
+        check!(file.write(b"foo"));
+        check!(file.sync_all());
+        check!(file.sync_data());
+    }
+
+    #[test]
+    fn truncate_works() {
+        let tmpdir = tmpdir();
+        let path = tmpdir.join("in.txt");
+
+        let mut file = check!(File::create(&path));
+        check!(file.write(b"foo"));
+        check!(file.sync_all());
+
+        // Do some simple things with truncation
+        assert_eq!(check!(file.metadata()).len(), 3);
+        check!(file.set_len(10));
+        assert_eq!(check!(file.metadata()).len(), 10);
+        check!(file.write(b"bar"));
+        check!(file.sync_all());
+        assert_eq!(check!(file.metadata()).len(), 10);
+
+        let mut v = Vec::new();
+        check!(check!(File::open(&path)).read_to_end(&mut v));
+        assert_eq!(v, b"foobar\0\0\0\0".to_vec());
+
+        // Truncate to a smaller length, don't seek, and then write something.
+        // Ensure that the intermediate zeroes are all filled in (we're seeked
+        // past the end of the file).
+        check!(file.set_len(2));
+        assert_eq!(check!(file.metadata()).len(), 2);
+        check!(file.write(b"wut"));
+        check!(file.sync_all());
+        assert_eq!(check!(file.metadata()).len(), 9);
+        let mut v = Vec::new();
+        check!(check!(File::open(&path)).read_to_end(&mut v));
+        assert_eq!(v, b"fo\0\0\0\0wut".to_vec());
+    }
+
+    #[test]
+    fn open_flavors() {
+        use fs::OpenOptions as OO;
+        fn c<T: Clone>(t: &T) -> T { t.clone() }
+
+        let tmpdir = tmpdir();
+
+        let mut r = OO::new(); r.read(true);
+        let mut w = OO::new(); w.write(true);
+        let mut rw = OO::new(); rw.write(true).read(true);
+
+        match r.open(&tmpdir.join("a")) {
+            Ok(..) => panic!(), Err(..) => {}
+        }
+
+        // Perform each one twice to make sure that it succeeds the second time
+        // (where the file exists)
+        check!(c(&w).create(true).open(&tmpdir.join("b")));
+        assert!(tmpdir.join("b").exists());
+        check!(c(&w).create(true).open(&tmpdir.join("b")));
+        check!(w.open(&tmpdir.join("b")));
+
+        check!(c(&rw).create(true).open(&tmpdir.join("c")));
+        assert!(tmpdir.join("c").exists());
+        check!(c(&rw).create(true).open(&tmpdir.join("c")));
+        check!(rw.open(&tmpdir.join("c")));
+
+        check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
+        assert!(tmpdir.join("d").exists());
+        check!(c(&w).append(true).create(true).open(&tmpdir.join("d")));
+        check!(c(&w).append(true).open(&tmpdir.join("d")));
+
+        check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
+        assert!(tmpdir.join("e").exists());
+        check!(c(&rw).append(true).create(true).open(&tmpdir.join("e")));
+        check!(c(&rw).append(true).open(&tmpdir.join("e")));
+
+        check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
+        assert!(tmpdir.join("f").exists());
+        check!(c(&w).truncate(true).create(true).open(&tmpdir.join("f")));
+        check!(c(&w).truncate(true).open(&tmpdir.join("f")));
+
+        check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
+        assert!(tmpdir.join("g").exists());
+        check!(c(&rw).truncate(true).create(true).open(&tmpdir.join("g")));
+        check!(c(&rw).truncate(true).open(&tmpdir.join("g")));
+
+        check!(check!(File::create(&tmpdir.join("h"))).write("foo".as_bytes()));
+        check!(r.open(&tmpdir.join("h")));
+        {
+            let mut f = check!(r.open(&tmpdir.join("h")));
+            assert!(f.write("wut".as_bytes()).is_err());
+        }
+        assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
+        {
+            let mut f = check!(c(&w).append(true).open(&tmpdir.join("h")));
+            check!(f.write("bar".as_bytes()));
+        }
+        assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 6);
+        {
+            let mut f = check!(c(&w).truncate(true).open(&tmpdir.join("h")));
+            check!(f.write("bar".as_bytes()));
+        }
+        assert_eq!(check!(fs::metadata(&tmpdir.join("h"))).len(), 3);
+    }
+
+    #[test]
+    fn utime() {
+        let tmpdir = tmpdir();
+        let path = tmpdir.join("a");
+        check!(File::create(&path));
+        // These numbers have to be bigger than the time in the day to account
+        // for timezones Windows in particular will fail in certain timezones
+        // with small enough values
+        check!(fs::set_file_times(&path, 100000, 200000));
+        assert_eq!(check!(path.metadata()).accessed(), 100000);
+        assert_eq!(check!(path.metadata()).modified(), 200000);
+    }
+
+    #[test]
+    fn utime_noexist() {
+        let tmpdir = tmpdir();
+
+        match fs::set_file_times(&tmpdir.join("a"), 100, 200) {
+            Ok(..) => panic!(),
+            Err(..) => {}
+        }
+    }
+
+    #[test]
+    fn binary_file() {
+        let mut bytes = [0; 1024];
+        StdRng::new().ok().unwrap().fill_bytes(&mut bytes);
+
+        let tmpdir = tmpdir();
+
+        check!(check!(File::create(&tmpdir.join("test"))).write(&bytes));
+        let mut v = Vec::new();
+        check!(check!(File::open(&tmpdir.join("test"))).read_to_end(&mut v));
+        assert!(v == bytes.as_slice());
+    }
+
+    #[test]
+    fn unlink_readonly() {
+        let tmpdir = tmpdir();
+        let path = tmpdir.join("file");
+        check!(File::create(&path));
+        let mut perm = check!(fs::metadata(&path)).permissions();
+        perm.set_readonly(true);
+        check!(fs::set_permissions(&path, perm));
+        check!(fs::remove_file(&path));
+    }
+}
index 475ada2ff84b891102ba96ada6868fb84b51fc0f..637b1950985fd79f2e9e5c278192aead8c048157 100644 (file)
@@ -22,6 +22,7 @@
 //! contained in this module.
 
 pub use super::{Read, ReadExt, Write, WriteExt, BufRead, BufReadExt};
+pub use fs::PathExt;
 
 // FIXME: pub use as `Seek` when the name isn't in the actual prelude any more
 pub use super::Seek as NewSeek;
index 14e779f9c4a8edad733e408b7baa5a97a17af2df..ad206502ba6a7f042e91d42ca109afa2e47aca72 100644 (file)
 pub mod fmt;
 pub mod old_io;
 pub mod io;
+pub mod fs;
 pub mod os;
 pub mod env;
 pub mod path;
index 3f4f1ec4c0db5f4afe33e516bf98a4ba02630952..540c425206c4909848eec362a7283138ba6b27b0 100755 (executable)
@@ -999,6 +999,12 @@ fn cmp(&self, other: &PathBuf) -> cmp::Ordering {
     }
 }
 
+impl AsOsStr for PathBuf {
+    fn as_os_str(&self) -> &OsStr {
+        &self.inner[]
+    }
+}
+
 /// A slice of a path (akin to `str`).
 ///
 /// This type supports a number of operations for inspecting a path, including
index 6f6b4c58717482522246ca8864b86d6855540871..80fa5f64597e95c8091a1032b56fa9fab45b8a33 100644 (file)
@@ -95,20 +95,30 @@ pub fn keep_going<F>(data: &[u8], mut f: F) -> i64 where
 }
 
 /// A trait for viewing representations from std types
+#[doc(hidden)]
 pub trait AsInner<Inner: ?Sized> {
     fn as_inner(&self) -> &Inner;
 }
 
+/// A trait for viewing representations from std types
+#[doc(hidden)]
+pub trait AsInnerMut<Inner: ?Sized> {
+    fn as_inner_mut(&mut self) -> &mut Inner;
+}
+
 /// A trait for extracting representations from std types
+#[doc(hidden)]
 pub trait IntoInner<Inner> {
     fn into_inner(self) -> Inner;
 }
 
 /// A trait for creating std types from internal representations
+#[doc(hidden)]
 pub trait FromInner<Inner> {
     fn from_inner(inner: Inner) -> Self;
 }
 
+#[doc(hidden)]
 pub trait ProcessConfig<K: BytesContainer, V: BytesContainer> {
     fn program(&self) -> &CString;
     fn args(&self) -> &[CString];
index 50a8e6b73e3866ff2b8d66879f97d3d9bbc20de7..9b6ea3218ca6aa12e3ec8fb69ca455552ee23b8e 100644 (file)
@@ -149,6 +149,9 @@ pub fn getpwuid_r(uid: libc::uid_t,
                       buf: *mut libc::c_char,
                       buflen: libc::size_t,
                       result: *mut *mut passwd) -> libc::c_int;
+
+    pub fn utimes(filename: *const libc::c_char,
+                  times: *const libc::timeval) -> libc::c_int;
 }
 
 #[cfg(any(target_os = "macos", target_os = "ios"))]
index 4a82b2807e7a3c914ab58c220fb694b1c04dc33c..689bbda83222997e9ff060974c49314327e41fe3 100644 (file)
 
 #![unstable(feature = "std_misc")]
 
-use vec::Vec;
-use sys::os_str::Buf;
-use sys_common::{AsInner, IntoInner, FromInner};
 use ffi::{OsStr, OsString};
+use fs::{Permissions, OpenOptions};
+use fs;
 use libc;
+use mem;
+use sys::os_str::Buf;
+use sys_common::{AsInner, AsInnerMut, IntoInner, FromInner};
+use vec::Vec;
 
 use old_io;
 
@@ -54,6 +57,12 @@ fn as_raw_fd(&self) -> Fd {
     }
 }
 
+impl AsRawFd for fs::File {
+    fn as_raw_fd(&self) -> Fd {
+        self.as_inner().fd().raw()
+    }
+}
+
 impl AsRawFd for old_io::pipe::PipeStream {
     fn as_raw_fd(&self) -> Fd {
         self.as_inner().fd()
@@ -123,18 +132,49 @@ fn into_vec(self) -> Vec<u8> {
 
 // Unix-specific extensions to `OsStr`.
 pub trait OsStrExt {
+    fn from_byte_slice(slice: &[u8]) -> &OsStr;
     fn as_byte_slice(&self) -> &[u8];
 }
 
 impl OsStrExt for OsStr {
+    fn from_byte_slice(slice: &[u8]) -> &OsStr {
+        unsafe { mem::transmute(slice) }
+    }
     fn as_byte_slice(&self) -> &[u8] {
         &self.as_inner().inner
     }
 }
 
+// Unix-specific extensions to `Permissions`
+pub trait PermissionsExt {
+    fn set_mode(&mut self, mode: i32);
+}
+
+impl PermissionsExt for Permissions {
+    fn set_mode(&mut self, mode: i32) {
+        *self = FromInner::from_inner(FromInner::from_inner(mode));
+    }
+}
+
+// Unix-specific extensions to `OpenOptions`
+pub trait OpenOptionsExt {
+    /// Set the mode bits that a new file will be created with.
+    ///
+    /// If a new file is created as part of a `File::open_opts` call then this
+    /// specified `mode` will be used as the permission bits for the new file.
+    fn mode(&mut self, mode: i32) -> &mut Self;
+}
+
+impl OpenOptionsExt for OpenOptions {
+    fn mode(&mut self, mode: i32) -> &mut OpenOptions {
+        self.as_inner_mut().mode(mode); self
+    }
+}
+
 /// A prelude for conveniently writing platform-specific code.
 ///
 /// Includes all extension traits, and some important type definitions.
 pub mod prelude {
-    pub use super::{Fd, AsRawFd};
+    #[doc(no_inline)]
+    pub use super::{Fd, AsRawFd, OsStrExt, OsStringExt, PermissionsExt};
 }
diff --git a/src/libstd/sys/unix/fd.rs b/src/libstd/sys/unix/fd.rs
new file mode 100644 (file)
index 0000000..f0943de
--- /dev/null
@@ -0,0 +1,70 @@
+// Copyright 2015 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.
+
+use core::prelude::*;
+use io::prelude::*;
+
+use io;
+use libc::{self, c_int, size_t, c_void};
+use mem;
+use sys::cvt;
+
+pub type fd_t = c_int;
+
+pub struct FileDesc {
+    fd: c_int,
+}
+
+impl FileDesc {
+    pub fn new(fd: c_int) -> FileDesc {
+        FileDesc { fd: fd }
+    }
+
+    pub fn raw(&self) -> c_int { self.fd }
+
+    /// Extract the actual filedescriptor without closing it.
+    pub fn into_raw(self) -> c_int {
+        let fd = self.fd;
+        unsafe { mem::forget(self) };
+        fd
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        let ret = try!(cvt(unsafe {
+            libc::read(self.fd,
+                       buf.as_mut_ptr() as *mut c_void,
+                       buf.len() as size_t)
+        }));
+        Ok(ret as usize)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        let ret = try!(cvt(unsafe {
+            libc::write(self.fd,
+                        buf.as_ptr() as *const c_void,
+                        buf.len() as size_t)
+        }));
+        Ok(ret as usize)
+    }
+}
+
+impl Drop for FileDesc {
+    fn drop(&mut self) {
+        // closing stdio file handles makes no sense, so never do it. Also, note
+        // that errors are ignored when closing a file descriptor. The reason
+        // for this is that if an error occurs we don't actually know if the
+        // file descriptor was closed or not, and if we retried (for something
+        // like EINTR), we might close another valid file descriptor (opened
+        // after we closed ours.
+        if self.fd > libc::STDERR_FILENO {
+            let _ = unsafe { libc::close(self.fd) };
+        }
+    }
+}
diff --git a/src/libstd/sys/unix/fs2.rs b/src/libstd/sys/unix/fs2.rs
new file mode 100644 (file)
index 0000000..070b324
--- /dev/null
@@ -0,0 +1,378 @@
+// Copyright 2013-2014 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.
+
+use core::prelude::*;
+use io::prelude::*;
+use os::unix::prelude::*;
+
+use ffi::{self, CString, OsString, AsOsStr, OsStr};
+use io::{self, Error, Seek, SeekFrom};
+use libc::{self, c_int, c_void, size_t, off_t, c_char, mode_t};
+use mem;
+use path::{Path, PathBuf};
+use ptr;
+use rc::Rc;
+use sys::fd::FileDesc;
+use sys::{c, cvt, cvt_r};
+use sys_common::FromInner;
+use vec::Vec;
+
+pub struct File(FileDesc);
+
+pub struct FileAttr {
+    stat: libc::stat,
+}
+
+pub struct ReadDir {
+    dirp: *mut libc::DIR,
+    root: Rc<PathBuf>,
+}
+
+pub struct DirEntry {
+    buf: Vec<u8>,
+    dirent: *mut libc::dirent_t,
+    root: Rc<PathBuf>,
+}
+
+#[derive(Clone)]
+pub struct OpenOptions {
+    flags: c_int,
+    read: bool,
+    write: bool,
+    mode: mode_t,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct FilePermissions { mode: mode_t }
+
+impl FileAttr {
+    pub fn is_dir(&self) -> bool {
+        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
+    }
+    pub fn is_file(&self) -> bool {
+        (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
+    }
+    pub fn size(&self) -> u64 { self.stat.st_size as u64 }
+    pub fn perm(&self) -> FilePermissions {
+        FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
+    }
+
+    pub fn accessed(&self) -> u64 {
+        self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
+    }
+    pub fn modified(&self) -> u64 {
+        self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
+    }
+
+    // times are in milliseconds (currently)
+    fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
+        secs * 1000 + nsecs / 1000000
+    }
+}
+
+impl FilePermissions {
+    pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
+    pub fn set_readonly(&mut self, readonly: bool) {
+        if readonly {
+            self.mode &= !0o222;
+        } else {
+            self.mode |= 0o222;
+        }
+    }
+}
+
+impl FromInner<i32> for FilePermissions {
+    fn from_inner(mode: i32) -> FilePermissions {
+        FilePermissions { mode: mode as mode_t }
+    }
+}
+
+impl Iterator for ReadDir {
+    type Item = io::Result<DirEntry>;
+
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        extern {
+            fn rust_dirent_t_size() -> c_int;
+        }
+
+        let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
+            rust_dirent_t_size() as usize
+        });
+        let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
+
+        let mut entry_ptr = ptr::null_mut();
+        loop {
+            if unsafe { libc::readdir_r(self.dirp, ptr, &mut entry_ptr) != 0 } {
+                return Some(Err(Error::last_os_error()))
+            }
+            if entry_ptr.is_null() {
+                return None
+            }
+
+            let entry = DirEntry {
+                buf: buf,
+                dirent: entry_ptr,
+                root: self.root.clone()
+            };
+            if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
+                buf = entry.buf;
+            } else {
+                return Some(Ok(entry))
+            }
+        }
+    }
+}
+
+impl Drop for ReadDir {
+    fn drop(&mut self) {
+        let r = unsafe { libc::closedir(self.dirp) };
+        debug_assert_eq!(r, 0);
+    }
+}
+
+impl DirEntry {
+    pub fn path(&self) -> PathBuf {
+        self.root.join(<OsStr as OsStrExt>::from_byte_slice(self.name_bytes()))
+    }
+
+    fn name_bytes(&self) -> &[u8] {
+        extern {
+            fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
+        }
+        unsafe {
+            let ptr = rust_list_dir_val(self.dirent);
+            ffi::c_str_to_bytes(mem::copy_lifetime(self, &ptr))
+        }
+    }
+}
+
+impl OpenOptions {
+    pub fn new() -> OpenOptions {
+        OpenOptions {
+            flags: 0,
+            read: false,
+            write: false,
+            mode: libc::S_IRUSR | libc::S_IWUSR,
+        }
+    }
+
+    pub fn read(&mut self, read: bool) {
+        self.read = read;
+    }
+
+    pub fn write(&mut self, write: bool) {
+        self.write = write;
+    }
+
+    pub fn append(&mut self, append: bool) {
+        self.flag(libc::O_APPEND, append);
+    }
+
+    pub fn truncate(&mut self, truncate: bool) {
+        self.flag(libc::O_TRUNC, truncate);
+    }
+
+    pub fn create(&mut self, create: bool) {
+        self.flag(libc::O_CREAT, create);
+    }
+
+    pub fn mode(&mut self, mode: i32) {
+        self.mode = mode as mode_t;
+    }
+
+    fn flag(&mut self, bit: c_int, on: bool) {
+        if on {
+            self.flags |= bit;
+        } else {
+            self.flags &= !bit;
+        }
+    }
+}
+
+impl File {
+    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
+        let flags = opts.flags | match (opts.read, opts.write) {
+            (true, true) => libc::O_RDWR,
+            (false, true) => libc::O_WRONLY,
+            (true, false) |
+            (false, false) => libc::O_RDONLY,
+        };
+        let path = cstr(path);
+        let fd = try!(cvt_r(|| unsafe {
+            libc::open(path.as_ptr(), flags, opts.mode)
+        }));
+        Ok(File(FileDesc::new(fd)))
+    }
+
+    pub fn file_attr(&self) -> io::Result<FileAttr> {
+        let mut stat: libc::stat = unsafe { mem::zeroed() };
+        try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
+        Ok(FileAttr { stat: stat })
+    }
+
+    pub fn fsync(&self) -> io::Result<()> {
+        try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
+        Ok(())
+    }
+
+    pub fn datasync(&self) -> io::Result<()> {
+        try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
+        return Ok(());
+
+        #[cfg(any(target_os = "macos", target_os = "ios"))]
+        unsafe fn os_datasync(fd: c_int) -> c_int {
+            libc::fcntl(fd, libc::F_FULLFSYNC)
+        }
+        #[cfg(target_os = "linux")]
+        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
+        #[cfg(not(any(target_os = "macos",
+                      target_os = "ios",
+                      target_os = "linux")))]
+        unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
+    }
+
+    pub fn truncate(&self, size: u64) -> io::Result<()> {
+        try!(cvt_r(|| unsafe {
+            libc::ftruncate(self.0.raw(), size as libc::off_t)
+        }));
+        Ok(())
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        self.0.read(buf)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        self.0.write(buf)
+    }
+
+    pub fn flush(&self) -> io::Result<()> { Ok(()) }
+
+    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
+        let (whence, pos) = match pos {
+            SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
+            SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
+            SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
+        };
+        let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
+        Ok(n as u64)
+    }
+
+    pub fn fd(&self) -> &FileDesc { &self.0 }
+}
+
+fn cstr(path: &Path) -> CString {
+    CString::from_slice(path.as_os_str().as_byte_slice())
+}
+
+pub fn mkdir(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
+    Ok(())
+}
+
+pub fn readdir(p: &Path) -> io::Result<ReadDir> {
+    let root = Rc::new(p.to_path_buf());
+    let p = cstr(p);
+    unsafe {
+        let ptr = libc::opendir(p.as_ptr());
+        if ptr.is_null() {
+            Err(Error::last_os_error())
+        } else {
+            Ok(ReadDir { dirp: ptr, root: root })
+        }
+    }
+}
+
+pub fn unlink(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
+    let old = cstr(old);
+    let new = cstr(new);
+    try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
+    Ok(())
+}
+
+pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
+    Ok(())
+}
+
+pub fn rmdir(p: &Path) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn chown(p: &Path, uid: isize, gid: isize) -> io::Result<()> {
+    let p = cstr(p);
+    try!(cvt_r(|| unsafe {
+        libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
+    }));
+    Ok(())
+}
+
+pub fn readlink(p: &Path) -> io::Result<PathBuf> {
+    let c_path = cstr(p);
+    let p = c_path.as_ptr();
+    let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
+    if len < 0 {
+        len = 1024; // FIXME: read PATH_MAX from C ffi?
+    }
+    let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
+    unsafe {
+        let n = try!(cvt({
+            libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
+        }));
+        buf.set_len(n as usize);
+    }
+    let s: OsString = OsStringExt::from_vec(buf);
+    Ok(PathBuf::new(&s))
+}
+
+pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = cstr(src);
+    let dst = cstr(dst);
+    try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
+    Ok(())
+}
+
+pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = cstr(src);
+    let dst = cstr(dst);
+    try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
+    Ok(())
+}
+
+pub fn stat(p: &Path) -> io::Result<FileAttr> {
+    let p = cstr(p);
+    let mut stat: libc::stat = unsafe { mem::zeroed() };
+    try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
+    Ok(FileAttr { stat: stat })
+}
+
+pub fn lstat(p: &Path) -> io::Result<FileAttr> {
+    let p = cstr(p);
+    let mut stat: libc::stat = unsafe { mem::zeroed() };
+    try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
+    Ok(FileAttr { stat: stat })
+}
+
+pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
+    let p = cstr(p);
+    let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
+    try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));
+    Ok(())
+}
index 427cf21ac70a9cc86021597c2b5570a755fa0875..b5a24278a206edf8a9194c6860c1ef49c85648cc 100644 (file)
@@ -23,6 +23,7 @@
 use num::{Int, SignedInt};
 use num;
 use old_io::{self, IoResult, IoError};
+use io;
 use str;
 use sys_common::mkerr_libc;
 
@@ -39,9 +40,11 @@ macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
 
 pub mod backtrace;
 pub mod c;
-pub mod ext;
 pub mod condvar;
-pub mod fs;
+pub mod ext;
+pub mod fd;
+pub mod fs;  // support for std::old_io
+pub mod fs2; // support for std::fs
 pub mod helper_signal;
 pub mod mutex;
 pub mod os;
@@ -176,6 +179,26 @@ pub fn retry<T, F> (mut f: F) -> T where
     }
 }
 
+pub fn cvt<T: SignedInt>(t: T) -> io::Result<T> {
+    let one: T = Int::one();
+    if t == -one {
+        Err(io::Error::last_os_error())
+    } else {
+        Ok(t)
+    }
+}
+
+pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
+    where T: SignedInt, F: FnMut() -> T
+{
+    loop {
+        match cvt(f()) {
+            Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
+            other => return other,
+        }
+    }
+}
+
 pub fn ms_to_timeval(ms: u64) -> libc::timeval {
     libc::timeval {
         tv_sec: (ms / 1000) as libc::time_t,
index a3bbf5c5fe795d5c3c3c42abef13178884d90369..dc874c2c7913ce6bf9cc72339fa69d7f7bcdb8a7 100644 (file)
 
 pub use sys_common::wtf8::{Wtf8Buf, EncodeWide};
 
-use sys::os_str::Buf;
-use sys_common::{AsInner, FromInner};
 use ffi::{OsStr, OsString};
+use fs::{self, OpenOptions};
 use libc;
+use sys::os_str::Buf;
+use sys_common::{AsInner, FromInner, AsInnerMut};
 
 use old_io;
 
@@ -43,6 +44,12 @@ fn as_raw_handle(&self) -> Handle {
     }
 }
 
+impl AsRawHandle for fs::File {
+    fn as_raw_handle(&self) -> Handle {
+        self.as_inner().handle().raw()
+    }
+}
+
 impl AsRawHandle for old_io::pipe::PipeStream {
     fn as_raw_handle(&self) -> Handle {
         self.as_inner().handle()
@@ -122,9 +129,57 @@ fn encode_wide(&self) -> EncodeWide {
     }
 }
 
+// Windows-specific extensions to `OpenOptions`
+pub trait OpenOptionsExt {
+    /// Override the `dwDesiredAccess` argument to the call to `CreateFile` with
+    /// the specified value.
+    fn desired_access(&mut self, access: i32) -> &mut Self;
+
+    /// Override the `dwCreationDisposition` argument to the call to
+    /// `CreateFile` with the specified value.
+    ///
+    /// This will override any values of the standard `create` flags, for
+    /// example.
+    fn creation_disposition(&mut self, val: i32) -> &mut Self;
+
+    /// Override the `dwFlagsAndAttributes` argument to the call to
+    /// `CreateFile` with the specified value.
+    ///
+    /// This will override any values of the standard flags on the `OpenOptions`
+    /// structure.
+    fn flags_and_attributes(&mut self, val: i32) -> &mut Self;
+
+    /// Override the `dwShareMode` argument to the call to `CreateFile` with the
+    /// specified value.
+    ///
+    /// This will override any values of the standard flags on the `OpenOptions`
+    /// structure.
+    fn share_mode(&mut self, val: i32) -> &mut Self;
+}
+
+impl OpenOptionsExt for OpenOptions {
+    fn desired_access(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().desired_access(access); self
+    }
+    fn creation_disposition(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().creation_disposition(access); self
+    }
+    fn flags_and_attributes(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().flags_and_attributes(access); self
+    }
+    fn share_mode(&mut self, access: i32) -> &mut OpenOptions {
+        self.as_inner_mut().share_mode(access); self
+    }
+}
+
 /// A prelude for conveniently writing platform-specific code.
 ///
 /// Includes all extension traits, and some important type definitions.
 pub mod prelude {
-    pub use super::{Socket, Handle, AsRawSocket, AsRawHandle, OsStrExt, OsStringExt};
+    #[doc(no_inline)]
+    pub use super::{Socket, Handle, AsRawSocket, AsRawHandle};
+    #[doc(no_inline)]
+    pub use super::{OsStrExt, OsStringExt};
+    #[doc(no_inline)]
+    pub use super::OpenOptionsExt;
 }
diff --git a/src/libstd/sys/windows/fs2.rs b/src/libstd/sys/windows/fs2.rs
new file mode 100644 (file)
index 0000000..74bb509
--- /dev/null
@@ -0,0 +1,428 @@
+// Copyright 2014 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.
+
+use core::prelude::*;
+use io::prelude::*;
+use os::windows::prelude::*;
+
+use default::Default;
+use ffi::{OsString, AsOsStr};
+use io::{self, Error, SeekFrom};
+use libc::{self, HANDLE};
+use mem;
+use path::{Path, PathBuf};
+use ptr;
+use sys::handle::Handle as RawHandle;
+use sys::{c, cvt};
+use vec::Vec;
+
+pub struct File { handle: RawHandle }
+pub struct FileAttr { data: c::WIN32_FILE_ATTRIBUTE_DATA }
+
+pub struct ReadDir {
+    handle: libc::HANDLE,
+    root: PathBuf,
+    first: Option<libc::WIN32_FIND_DATAW>,
+}
+
+pub struct DirEntry { path: PathBuf }
+
+#[derive(Clone, Default)]
+pub struct OpenOptions {
+    create: bool,
+    append: bool,
+    read: bool,
+    write: bool,
+    truncate: bool,
+    desired_access: Option<libc::DWORD>,
+    share_mode: Option<libc::DWORD>,
+    creation_disposition: Option<libc::DWORD>,
+    flags_and_attributes: Option<libc::DWORD>,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct FilePermissions { attrs: libc::DWORD }
+
+impl Iterator for ReadDir {
+    type Item = io::Result<DirEntry>;
+    fn next(&mut self) -> Option<io::Result<DirEntry>> {
+        if let Some(first) = self.first.take() {
+            if let Some(e) = DirEntry::new(&self.root, &first) {
+                return Some(Ok(e));
+            }
+        }
+        unsafe {
+            let mut wfd = mem::zeroed();
+            loop {
+                if libc::FindNextFileW(self.handle, &mut wfd) == 0 {
+                    if libc::GetLastError() ==
+                        c::ERROR_NO_MORE_FILES as libc::DWORD {
+                        return None
+                    } else {
+                        return Some(Err(Error::last_os_error()))
+                    }
+                }
+                if let Some(e) = DirEntry::new(&self.root, &wfd) {
+                    return Some(Ok(e))
+                }
+            }
+        }
+    }
+}
+
+impl Drop for ReadDir {
+    fn drop(&mut self) {
+        let r = unsafe { libc::FindClose(self.handle) };
+        debug_assert!(r != 0);
+    }
+}
+
+impl DirEntry {
+    fn new(root: &Path, wfd: &libc::WIN32_FIND_DATAW) -> Option<DirEntry> {
+        match &wfd.cFileName[0..3] {
+            // check for '.' and '..'
+            [46, 0, ..] |
+            [46, 46, 0, ..] => return None,
+            _ => {}
+        }
+
+        let filename = super::truncate_utf16_at_nul(&wfd.cFileName);
+        let filename: OsString = OsStringExt::from_wide(filename);
+        Some(DirEntry { path: root.join(&filename) })
+    }
+
+    pub fn path(&self) -> PathBuf {
+        self.path.clone()
+    }
+}
+
+impl OpenOptions {
+    pub fn new() -> OpenOptions { Default::default() }
+    pub fn read(&mut self, read: bool) { self.read = read; }
+    pub fn write(&mut self, write: bool) { self.write = write; }
+    pub fn append(&mut self, append: bool) { self.append = append; }
+    pub fn create(&mut self, create: bool) { self.create = create; }
+    pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
+    pub fn creation_disposition(&mut self, val: i32) {
+        self.creation_disposition = Some(val as libc::DWORD);
+    }
+    pub fn flags_and_attributes(&mut self, val: i32) {
+        self.flags_and_attributes = Some(val as libc::DWORD);
+    }
+    pub fn desired_access(&mut self, val: i32) {
+        self.desired_access = Some(val as libc::DWORD);
+    }
+    pub fn share_mode(&mut self, val: i32) {
+        self.share_mode = Some(val as libc::DWORD);
+    }
+
+    fn get_desired_access(&self) -> libc::DWORD {
+        self.desired_access.unwrap_or({
+            let mut base = if self.read {libc::FILE_GENERIC_READ} else {0} |
+                           if self.write {libc::FILE_GENERIC_WRITE} else {0};
+            if self.append {
+                base &= !libc::FILE_WRITE_DATA;
+                base |= libc::FILE_APPEND_DATA;
+            }
+            base
+        })
+    }
+
+    fn get_share_mode(&self) -> libc::DWORD {
+        // libuv has a good comment about this, but the basic idea is that
+        // we try to emulate unix semantics by enabling all sharing by
+        // allowing things such as deleting a file while it's still open.
+        self.share_mode.unwrap_or(libc::FILE_SHARE_READ |
+                                  libc::FILE_SHARE_WRITE |
+                                  libc::FILE_SHARE_DELETE)
+    }
+
+    fn get_creation_disposition(&self) -> libc::DWORD {
+        self.creation_disposition.unwrap_or({
+            match (self.create, self.truncate) {
+                (true, true) => libc::CREATE_ALWAYS,
+                (true, false) => libc::OPEN_ALWAYS,
+                (false, false) => libc::OPEN_EXISTING,
+                (false, true) => {
+                    if self.write && !self.append {
+                        libc::CREATE_ALWAYS
+                    } else {
+                        libc::TRUNCATE_EXISTING
+                    }
+                }
+            }
+        })
+    }
+
+    fn get_flags_and_attributes(&self) -> libc::DWORD {
+        self.flags_and_attributes.unwrap_or(libc::FILE_ATTRIBUTE_NORMAL)
+    }
+}
+
+impl File {
+    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
+        let path = to_utf16(path);
+        let handle = unsafe {
+            libc::CreateFileW(path.as_ptr(),
+                              opts.get_desired_access(),
+                              opts.get_share_mode(),
+                              ptr::null_mut(),
+                              opts.get_creation_disposition(),
+                              opts.get_flags_and_attributes(),
+                              ptr::null_mut())
+        };
+        if handle == libc::INVALID_HANDLE_VALUE {
+            Err(Error::last_os_error())
+        } else {
+            Ok(File { handle: RawHandle::new(handle) })
+        }
+    }
+
+    pub fn fsync(&self) -> io::Result<()> {
+        try!(cvt(unsafe { libc::FlushFileBuffers(self.handle.raw()) }));
+        Ok(())
+    }
+
+    pub fn datasync(&self) -> io::Result<()> { self.fsync() }
+
+    pub fn truncate(&self, size: u64) -> io::Result<()> {
+        let mut info = c::FILE_END_OF_FILE_INFO {
+            EndOfFile: size as libc::LARGE_INTEGER,
+        };
+        let size = mem::size_of_val(&info);
+        try!(cvt(unsafe {
+            c::SetFileInformationByHandle(self.handle.raw(),
+                                          c::FileEndOfFileInfo,
+                                          &mut info as *mut _ as *mut _,
+                                          size as libc::DWORD)
+        }));
+        Ok(())
+    }
+
+    pub fn file_attr(&self) -> io::Result<FileAttr> {
+        unsafe {
+            let mut info: c::BY_HANDLE_FILE_INFORMATION = mem::zeroed();
+            try!(cvt(c::GetFileInformationByHandle(self.handle.raw(),
+                                                   &mut info)));
+            Ok(FileAttr {
+                data: c::WIN32_FILE_ATTRIBUTE_DATA {
+                    dwFileAttributes: info.dwFileAttributes,
+                    ftCreationTime: info.ftCreationTime,
+                    ftLastAccessTime: info.ftLastAccessTime,
+                    ftLastWriteTime: info.ftLastWriteTime,
+                    nFileSizeHigh: info.nFileSizeHigh,
+                    nFileSizeLow: info.nFileSizeLow,
+                }
+            })
+        }
+    }
+
+    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
+        let mut read = 0;
+        try!(cvt(unsafe {
+            libc::ReadFile(self.handle.raw(),
+                           buf.as_ptr() as libc::LPVOID,
+                           buf.len() as libc::DWORD,
+                           &mut read,
+                           ptr::null_mut())
+        }));
+        Ok(read as usize)
+    }
+
+    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
+        let mut amt = 0;
+        try!(cvt(unsafe {
+            libc::WriteFile(self.handle.raw(),
+                            buf.as_ptr() as libc::LPVOID,
+                            buf.len() as libc::DWORD,
+                            &mut amt,
+                            ptr::null_mut())
+        }));
+        Ok(amt as usize)
+    }
+
+    pub fn flush(&self) -> io::Result<()> { Ok(()) }
+
+    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
+        let (whence, pos) = match pos {
+            SeekFrom::Start(n) => (libc::FILE_BEGIN, n as i64),
+            SeekFrom::End(n) => (libc::FILE_END, n),
+            SeekFrom::Current(n) => (libc::FILE_CURRENT, n),
+        };
+        let pos = pos as libc::LARGE_INTEGER;
+        let mut newpos = 0;
+        try!(cvt(unsafe {
+            libc::SetFilePointerEx(self.handle.raw(), pos,
+                                   &mut newpos, whence)
+        }));
+        Ok(newpos as u64)
+    }
+
+    pub fn handle(&self) -> &RawHandle { &self.handle }
+}
+
+pub fn to_utf16(s: &Path) -> Vec<u16> {
+    s.as_os_str().encode_wide().chain(Some(0).into_iter()).collect()
+}
+
+impl FileAttr {
+    pub fn is_dir(&self) -> bool {
+        self.data.dwFileAttributes & c::FILE_ATTRIBUTE_DIRECTORY != 0
+    }
+    pub fn is_file(&self) -> bool {
+        !self.is_dir()
+    }
+    pub fn size(&self) -> u64 {
+        ((self.data.nFileSizeHigh as u64) << 32) | (self.data.nFileSizeLow as u64)
+    }
+    pub fn perm(&self) -> FilePermissions {
+        FilePermissions { attrs: self.data.dwFileAttributes }
+    }
+
+    pub fn accessed(&self) -> u64 { self.to_ms(&self.data.ftLastAccessTime) }
+    pub fn modified(&self) -> u64 { self.to_ms(&self.data.ftLastWriteTime) }
+
+    fn to_ms(&self, ft: &libc::FILETIME) -> u64 {
+        // FILETIME is in 100ns intervals and there are 10000 intervals in a
+        // millisecond.
+        let bits = (ft.dwLowDateTime as u64) | ((ft.dwHighDateTime as u64) << 32);
+        bits / 10000
+    }
+}
+
+impl FilePermissions {
+    pub fn readonly(&self) -> bool {
+        self.attrs & c::FILE_ATTRIBUTE_READONLY != 0
+    }
+
+    pub fn set_readonly(&mut self, readonly: bool) {
+        if readonly {
+            self.attrs |= c::FILE_ATTRIBUTE_READONLY;
+        } else {
+            self.attrs &= !c::FILE_ATTRIBUTE_READONLY;
+        }
+    }
+}
+
+pub fn mkdir(p: &Path) -> io::Result<()> {
+    let p = to_utf16(p);
+    try!(cvt(unsafe {
+        libc::CreateDirectoryW(p.as_ptr(), ptr::null_mut())
+    }));
+    Ok(())
+}
+
+pub fn readdir(p: &Path) -> io::Result<ReadDir> {
+    let root = p.to_path_buf();
+    let star = p.join("*");
+    let path = to_utf16(&star);
+
+    unsafe {
+        let mut wfd = mem::zeroed();
+        let find_handle = libc::FindFirstFileW(path.as_ptr(), &mut wfd);
+        if find_handle != libc::INVALID_HANDLE_VALUE {
+            Ok(ReadDir { handle: find_handle, root: root, first: Some(wfd) })
+        } else {
+            Err(Error::last_os_error())
+        }
+    }
+}
+
+pub fn unlink(p: &Path) -> io::Result<()> {
+    let p_utf16 = to_utf16(p);
+    try!(cvt(unsafe { libc::DeleteFileW(p_utf16.as_ptr()) }));
+    Ok(())
+}
+
+pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
+    let old = to_utf16(old);
+    let new = to_utf16(new);
+    try!(cvt(unsafe {
+        libc::MoveFileExW(old.as_ptr(), new.as_ptr(),
+                          libc::MOVEFILE_REPLACE_EXISTING)
+    }));
+    Ok(())
+}
+
+pub fn rmdir(p: &Path) -> io::Result<()> {
+    let p = to_utf16(p);
+    try!(cvt(unsafe { c::RemoveDirectoryW(p.as_ptr()) }));
+    Ok(())
+}
+
+pub fn readlink(p: &Path) -> io::Result<PathBuf> {
+    use sys::c::compat::kernel32::GetFinalPathNameByHandleW;
+    let mut opts = OpenOptions::new();
+    opts.read(true);
+    let file = try!(File::open(p, &opts));;
+
+    // Specify (sz - 1) because the documentation states that it's the size
+    // without the null pointer
+    //
+    // FIXME: I have a feeling that this reads intermediate symlinks as well.
+    let ret: OsString = try!(super::fill_utf16_buf_new(|buf, sz| unsafe {
+        GetFinalPathNameByHandleW(file.handle.raw(),
+                                  buf as *const u16,
+                                  sz - 1,
+                                  libc::VOLUME_NAME_DOS)
+    }, |s| OsStringExt::from_wide(s)));
+    Ok(PathBuf::new(&ret))
+}
+
+pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
+    use sys::c::compat::kernel32::CreateSymbolicLinkW;
+    let src = to_utf16(src);
+    let dst = to_utf16(dst);
+    try!(cvt(unsafe {
+        CreateSymbolicLinkW(dst.as_ptr(), src.as_ptr(), 0) as libc::BOOL
+    }));
+    Ok(())
+}
+
+pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
+    let src = to_utf16(src);
+    let dst = to_utf16(dst);
+    try!(cvt(unsafe {
+        libc::CreateHardLinkW(dst.as_ptr(), src.as_ptr(), ptr::null_mut())
+    }));
+    Ok(())
+}
+
+pub fn stat(p: &Path) -> io::Result<FileAttr> {
+    let p = to_utf16(p);
+    unsafe {
+        let mut attr: FileAttr = mem::zeroed();
+        try!(cvt(c::GetFileAttributesExW(p.as_ptr(),
+                                         c::GetFileExInfoStandard,
+                                         &mut attr.data as *mut _ as *mut _)));
+        Ok(attr)
+    }
+}
+
+pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
+    let p = to_utf16(p);
+    unsafe {
+        try!(cvt(c::SetFileAttributesW(p.as_ptr(), perm.attrs)));
+        Ok(())
+    }
+}
+
+pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
+    let atime = super::ms_to_filetime(atime);
+    let mtime = super::ms_to_filetime(mtime);
+
+    let mut o = OpenOptions::new();
+    o.write(true);
+    let f = try!(File::open(p, &o));
+    try!(cvt(unsafe {
+        c::SetFileTime(f.handle.raw(), 0 as *const _, &atime, &mtime)
+    }));
+    Ok(())
+}
index 6737eeef12532604554536076e75b641197bdd69..52aa5fb036a9acc338291bdf136f9028b1e12547 100644 (file)
@@ -21,6 +21,7 @@ impl Handle {
     pub fn new(handle: HANDLE) -> Handle {
         Handle(handle)
     }
+    pub fn raw(&self) -> HANDLE { self.0 }
 }
 
 impl Drop for Handle {
index f1af70e2cf7d1eb341bc87ff5bee89d0133bbca1..140bdb1450102f945b69d246360088224336d219 100644 (file)
 use prelude::v1::*;
 
 use ffi::OsStr;
-use io::ErrorKind;
+use io::{self, ErrorKind};
 use libc;
 use mem;
 use old_io::{self, IoResult, IoError};
+use num::Int;
 use os::windows::OsStrExt;
 use sync::{Once, ONCE_INIT};
 
@@ -38,6 +39,7 @@ macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
 pub mod condvar;
 pub mod ext;
 pub mod fs;
+pub mod fs2;
 pub mod handle;
 pub mod helper_signal;
 pub mod mutex;
@@ -248,7 +250,7 @@ fn to_utf16_os(s: &OsStr) -> Vec<u16> {
 // Once the syscall has completed (errors bail out early) the second closure is
 // yielded the data which has been read from the syscall. The return value
 // from this closure is then the return value of the function.
-fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
+fn fill_utf16_buf_base<F1, F2, T>(mut f1: F1, f2: F2) -> Result<T, ()>
     where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
           F2: FnOnce(&[u16]) -> T
 {
@@ -280,7 +282,7 @@ fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
             c::SetLastError(0);
             let k = match f1(buf.as_mut_ptr(), n as libc::DWORD) {
                 0 if libc::GetLastError() == 0 => 0,
-                0 => return Err(IoError::last_error()),
+                0 => return Err(()),
                 n => n,
             } as usize;
             if k == n && libc::GetLastError() ==
@@ -295,6 +297,20 @@ fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> IoResult<T>
     }
 }
 
+fn fill_utf16_buf<F1, F2, T>(f1: F1, f2: F2) -> IoResult<T>
+    where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
+          F2: FnOnce(&[u16]) -> T
+{
+    fill_utf16_buf_base(f1, f2).map_err(|()| IoError::last_error())
+}
+
+fn fill_utf16_buf_new<F1, F2, T>(f1: F1, f2: F2) -> io::Result<T>
+    where F1: FnMut(*mut u16, libc::DWORD) -> libc::DWORD,
+          F2: FnOnce(&[u16]) -> T
+{
+    fill_utf16_buf_base(f1, f2).map_err(|()| io::Error::last_os_error())
+}
+
 fn os2path(s: &[u16]) -> Path {
     // FIXME: this should not be a panicking conversion (aka path reform)
     Path::new(String::from_utf16(s).unwrap())
@@ -307,3 +323,21 @@ pub fn truncate_utf16_at_nul<'a>(v: &'a [u16]) -> &'a [u16] {
         None => v
     }
 }
+
+fn cvt<I: Int>(i: I) -> io::Result<I> {
+    if i == Int::zero() {
+        Err(io::Error::last_os_error())
+    } else {
+        Ok(i)
+    }
+}
+
+fn ms_to_filetime(ms: u64) -> libc::FILETIME {
+    // A FILETIME is a count of 100 nanosecond intervals, so we multiply by
+    // 10000 b/c there are 10000 intervals in 1 ms
+    let ms = ms * 10000;
+    libc::FILETIME {
+        dwLowDateTime: ms as u32,
+        dwHighDateTime: (ms >> 32) as u32,
+    }
+}
index c71e2d057c35117af1cea05e2506f25fdf2f075a..36c12deacaa32865a010ba027cbcae9de2bc0840 100644 (file)
@@ -191,7 +191,7 @@ fn next(&mut self) -> Option<Path> {
     }
 }
 
-#[derive(Show)]
+#[derive(Debug)]
 pub struct JoinPathsError;
 
 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>