summary refs log tree commit diff
path: root/src/libstd/io/error.rs
diff options
context:
space:
mode:
authorAlex Crichton <alex@alexcrichton.com>2015-01-31 20:24:36 -0800
committerAlex Crichton <alex@alexcrichton.com>2015-02-03 12:51:12 -0800
commit5cf9905e257ddeeadaf493a705a230081a6c7da3 (patch)
treebd6a619395cc46871abdda33e3d6c87328fa585b /src/libstd/io/error.rs
parent7858cb432d3f2efc0374424cb2b51518f697c172 (diff)
downloadrust-5cf9905e257ddeeadaf493a705a230081a6c7da3.tar.gz
rust-5cf9905e257ddeeadaf493a705a230081a6c7da3.zip
std: Add `io` module again
This commit is an implementation of [RFC 576][rfc] which adds back the `std::io`
module to the standard library. No functionality in `std::old_io` has been
deprecated just yet, and the new `std::io` module is behind the same `io`
feature gate.

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

A good bit of functionality was copied over from `std::old_io`, but many tweaks
were required for the new method signatures. Behavior such as precisely when
buffered objects call to the underlying object may have been tweaked slightly in
the transition. All implementations were audited to use composition wherever
possible. For example the custom `pos` and `cap` cursors in `BufReader` were
removed in favor of just using `Cursor<Vec<u8>>`.

A few liberties were taken during this implementation which were not explicitly
spelled out in the RFC:

* The old `LineBufferedWriter` is now named `LineWriter`
* The internal representation of `Error` now favors OS error codes (a
  0-allocation path) and contains a `Box` for extra semantic data.
* The io prelude currently reexports `Seek` as `NewSeek` to prevent conflicts
  with the real prelude reexport of `old_io::Seek`
* The `chars` method was moved from `BufReadExt` to `ReadExt`.
* The `chars` iterator returns a custom error with a variant that explains that
  the data was not valid UTF-8.
Diffstat (limited to 'src/libstd/io/error.rs')
-rw-r--r--src/libstd/io/error.rs183
1 files changed, 183 insertions, 0 deletions
diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs
new file mode 100644
index 00000000000..9f3cd8c8b15
--- /dev/null
+++ b/src/libstd/io/error.rs
@@ -0,0 +1,183 @@
+// 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 boxed::Box;
+use clone::Clone;
+use error::Error as StdError;
+use fmt;
+use option::Option::{self, Some, None};
+use result;
+use string::String;
+use sys;
+
+/// A type for results generated by I/O related functions where the `Err` type
+/// is hard-wired to `io::Error`.
+///
+/// This typedef is generally used to avoid writing out `io::Error` directly and
+/// is otherwise a direct mapping to `std::result::Result`.
+pub type Result<T> = result::Result<T, Error>;
+
+/// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
+/// associated traits.
+///
+/// Errors mostly originate from the underlying OS, but custom instances of
+/// `Error` can be created with crafted error messages and a particular value of
+/// `ErrorKind`.
+#[derive(PartialEq, Eq, Clone, Debug)]
+pub struct Error {
+    repr: Repr,
+}
+
+#[derive(PartialEq, Eq, Clone, Debug)]
+enum Repr {
+    Os(i32),
+    Custom(Box<Custom>),
+}
+
+#[derive(PartialEq, Eq, Clone, Debug)]
+struct Custom {
+    kind: ErrorKind,
+    desc: &'static str,
+    detail: Option<String>
+}
+
+/// A list specifying general categories of I/O error.
+#[derive(Copy, PartialEq, Eq, Clone, Debug)]
+pub enum ErrorKind {
+    /// The file was not found.
+    FileNotFound,
+    /// The file permissions disallowed access to this file.
+    PermissionDenied,
+    /// The connection was refused by the remote server.
+    ConnectionRefused,
+    /// The connection was reset by the remote server.
+    ConnectionReset,
+    /// The connection was aborted (terminated) by the remote server.
+    ConnectionAborted,
+    /// The network operation failed because it was not connected yet.
+    NotConnected,
+    /// The operation failed because a pipe was closed.
+    BrokenPipe,
+    /// A file already existed with that name.
+    PathAlreadyExists,
+    /// No file exists at that location.
+    PathDoesntExist,
+    /// The path did not specify the type of file that this operation required.
+    /// For example, attempting to copy a directory with the `fs::copy()`
+    /// operation will fail with this error.
+    MismatchedFileTypeForOperation,
+    /// The operation temporarily failed (for example, because a signal was
+    /// received), and retrying may succeed.
+    ResourceUnavailable,
+    /// A parameter was incorrect in a way that caused an I/O error not part of
+    /// this list.
+    InvalidInput,
+    /// The I/O operation's timeout expired, causing it to be canceled.
+    TimedOut,
+    /// An error returned when an operation could not be completed because a
+    /// call to `write` returned `Ok(0)`.
+    ///
+    /// This typically means that an operation could only succeed if it wrote a
+    /// particular number of bytes but only a smaller number of bytes could be
+    /// written.
+    WriteZero,
+    /// This operation was interrupted
+    Interrupted,
+    /// Any I/O error not part of this list.
+    Other,
+}
+
+impl Error {
+    /// Creates a new custom error from a specified kind/description/detail.
+    pub fn new(kind: ErrorKind,
+               description: &'static str,
+               detail: Option<String>) -> Error {
+        Error {
+            repr: Repr::Custom(Box::new(Custom {
+                kind: kind,
+                desc: description,
+                detail: detail,
+            }))
+        }
+    }
+
+    /// Returns an error representing the last OS error which occurred.
+    ///
+    /// This function reads the value of `errno` for the target platform (e.g.
+    /// `GetLastError` on Windows) and will return a corresponding instance of
+    /// `Error` for the error code.
+    pub fn last_os_error() -> Error {
+        Error::from_os_error(sys::os::errno() as i32)
+    }
+
+    /// Creates a new instance of an `Error` from a particular OS error code.
+    pub fn from_os_error(code: i32) -> Error {
+        Error { repr: Repr::Os(code) }
+    }
+
+    /// Return the corresponding `ErrorKind` for this error.
+    pub fn kind(&self) -> ErrorKind {
+        match self.repr {
+            Repr::Os(code) => sys::decode_error_kind(code),
+            Repr::Custom(ref c) => c.kind,
+        }
+    }
+
+    /// Returns a short description for this error message
+    pub fn description(&self) -> &str {
+        match self.repr {
+            Repr::Os(..) => "os error",
+            Repr::Custom(ref c) => c.desc,
+        }
+    }
+
+    /// Returns a detailed error message for this error (if one is available)
+    pub fn detail(&self) -> Option<String> {
+        match self.repr {
+            Repr::Os(code) => Some(sys::os::error_string(code)),
+            Repr::Custom(ref s) => s.detail.clone(),
+        }
+    }
+}
+
+impl fmt::Display for Error {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        match self.repr {
+            Repr::Os(code) => {
+                let detail = sys::os::error_string(code);
+                write!(fmt, "{} (os error {})", detail, code)
+            }
+            Repr::Custom(ref c) => {
+                match **c {
+                    Custom {
+                        kind: ErrorKind::Other,
+                        desc: "unknown error",
+                        detail: Some(ref detail)
+                    } => {
+                        write!(fmt, "{}", detail)
+                    }
+                    Custom { detail: None, desc, .. } =>
+                        write!(fmt, "{}", desc),
+                    Custom { detail: Some(ref detail), desc, .. } =>
+                        write!(fmt, "{} ({})", desc, detail)
+                }
+            }
+        }
+    }
+}
+
+impl StdError for Error {
+    fn description(&self) -> &str {
+        match self.repr {
+            Repr::Os(..) => "os error",
+            Repr::Custom(ref c) => c.desc,
+        }
+    }
+}