1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 use marker::{Send, Sync};
16 use option::Option::{self, Some, None};
20 /// A specialized [`Result`](../result/enum.Result.html) type for I/O
23 /// This type is broadly used across `std::io` for any operation which may
26 /// This typedef is generally used to avoid writing out `io::Error` directly and
27 /// is otherwise a direct mapping to `Result`.
29 /// While usual Rust style is to import types directly, aliases of `Result`
30 /// often are not, to make it easier to distinguish between them. `Result` is
31 /// generally assumed to be `std::result::Result`, and so users of this alias
32 /// will generally use `io::Result` instead of shadowing the prelude's import
33 /// of `std::result::Result`.
37 /// A convenience function that bubbles an `io::Result` to its caller:
42 /// fn get_string() -> io::Result<String> {
43 /// let mut buffer = String::new();
45 /// try!(io::stdin().read_line(&mut buffer));
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub type Result<T> = result::Result<T, Error>;
53 /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
54 /// associated traits.
56 /// Errors mostly originate from the underlying OS, but custom instances of
57 /// `Error` can be created with crafted error messages and a particular value of
60 #[stable(feature = "rust1", since = "1.0.0")]
73 error: Box<error::Error+Send+Sync>,
76 /// A list specifying general categories of I/O error.
78 /// This list is intended to grow over time and it is not recommended to
79 /// exhaustively match against it.
80 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
81 #[stable(feature = "rust1", since = "1.0.0")]
84 /// An entity was not found, often a file.
85 #[stable(feature = "rust1", since = "1.0.0")]
87 /// The operation lacked the necessary privileges to complete.
88 #[stable(feature = "rust1", since = "1.0.0")]
90 /// The connection was refused by the remote server.
91 #[stable(feature = "rust1", since = "1.0.0")]
93 /// The connection was reset by the remote server.
94 #[stable(feature = "rust1", since = "1.0.0")]
96 /// The connection was aborted (terminated) by the remote server.
97 #[stable(feature = "rust1", since = "1.0.0")]
99 /// The network operation failed because it was not connected yet.
100 #[stable(feature = "rust1", since = "1.0.0")]
102 /// A socket address could not be bound because the address is already in
104 #[stable(feature = "rust1", since = "1.0.0")]
106 /// A nonexistent interface was requested or the requested address was not
108 #[stable(feature = "rust1", since = "1.0.0")]
110 /// The operation failed because a pipe was closed.
111 #[stable(feature = "rust1", since = "1.0.0")]
113 /// An entity already exists, often a file.
114 #[stable(feature = "rust1", since = "1.0.0")]
116 /// The operation needs to block to complete, but the blocking operation was
117 /// requested to not occur.
118 #[stable(feature = "rust1", since = "1.0.0")]
120 /// A parameter was incorrect.
121 #[stable(feature = "rust1", since = "1.0.0")]
123 /// Data not valid for the operation were encountered.
125 /// Unlike `InvalidInput`, this typically means that the operation
126 /// parameters were valid, however the error was caused by malformed
129 /// For example, a function that reads a file into a string will error with
130 /// `InvalidData` if the file's contents are not valid UTF-8.
131 #[stable(feature = "io_invalid_data", since = "1.2.0")]
133 /// The I/O operation's timeout expired, causing it to be canceled.
134 #[stable(feature = "rust1", since = "1.0.0")]
136 /// An error returned when an operation could not be completed because a
137 /// call to `write` returned `Ok(0)`.
139 /// This typically means that an operation could only succeed if it wrote a
140 /// particular number of bytes but only a smaller number of bytes could be
142 #[stable(feature = "rust1", since = "1.0.0")]
144 /// This operation was interrupted.
146 /// Interrupted operations can typically be retried.
147 #[stable(feature = "rust1", since = "1.0.0")]
149 /// Any I/O error not part of this list.
150 #[stable(feature = "rust1", since = "1.0.0")]
153 /// An error returned when an operation could not be completed because an
154 /// "end of file" was reached prematurely.
156 /// This typically means that an operation could only succeed if it read a
157 /// particular number of bytes but only a smaller number of bytes could be
159 #[stable(feature = "read_exact", since = "1.6.0")]
162 /// Any I/O error not part of this list.
163 #[unstable(feature = "io_error_internals",
164 reason = "better expressed through extensible enums that this \
165 enum cannot be exhaustively matched against",
172 /// Creates a new I/O error from a known kind of error as well as an
173 /// arbitrary error payload.
175 /// This function is used to generically create I/O errors which do not
176 /// originate from the OS itself. The `error` argument is an arbitrary
177 /// payload which will be contained in this `Error`.
182 /// use std::io::{Error, ErrorKind};
184 /// // errors can be created from strings
185 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
187 /// // errors can also be created from other errors
188 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub fn new<E>(kind: ErrorKind, error: E) -> Error
192 where E: Into<Box<error::Error+Send+Sync>>
194 Self::_new(kind, error.into())
197 fn _new(kind: ErrorKind, error: Box<error::Error+Send+Sync>) -> Error {
199 repr: Repr::Custom(Box::new(Custom {
206 /// Returns an error representing the last OS error which occurred.
208 /// This function reads the value of `errno` for the target platform (e.g.
209 /// `GetLastError` on Windows) and will return a corresponding instance of
210 /// `Error` for the error code.
211 #[stable(feature = "rust1", since = "1.0.0")]
212 pub fn last_os_error() -> Error {
213 Error::from_raw_os_error(sys::os::errno() as i32)
216 /// Creates a new instance of an `Error` from a particular OS error code.
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn from_raw_os_error(code: i32) -> Error {
219 Error { repr: Repr::Os(code) }
222 /// Returns the OS error that this error represents (if any).
224 /// If this `Error` was constructed via `last_os_error` or
225 /// `from_raw_os_error`, then this function will return `Some`, otherwise
226 /// it will return `None`.
227 #[stable(feature = "rust1", since = "1.0.0")]
228 pub fn raw_os_error(&self) -> Option<i32> {
230 Repr::Os(i) => Some(i),
231 Repr::Custom(..) => None,
235 /// Returns a reference to the inner error wrapped by this error (if any).
237 /// If this `Error` was constructed via `new` then this function will
238 /// return `Some`, otherwise it will return `None`.
239 #[stable(feature = "io_error_inner", since = "1.3.0")]
240 pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> {
242 Repr::Os(..) => None,
243 Repr::Custom(ref c) => Some(&*c.error),
247 /// Returns a mutable reference to the inner error wrapped by this error
250 /// If this `Error` was constructed via `new` then this function will
251 /// return `Some`, otherwise it will return `None`.
252 #[stable(feature = "io_error_inner", since = "1.3.0")]
253 pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> {
255 Repr::Os(..) => None,
256 Repr::Custom(ref mut c) => Some(&mut *c.error),
260 /// Consumes the `Error`, returning its inner error (if any).
262 /// If this `Error` was constructed via `new` then this function will
263 /// return `Some`, otherwise it will return `None`.
264 #[stable(feature = "io_error_inner", since = "1.3.0")]
265 pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> {
267 Repr::Os(..) => None,
268 Repr::Custom(c) => Some(c.error)
272 /// Returns the corresponding `ErrorKind` for this error.
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub fn kind(&self) -> ErrorKind {
276 Repr::Os(code) => sys::decode_error_kind(code),
277 Repr::Custom(ref c) => c.kind,
282 impl fmt::Debug for Repr {
283 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
285 Repr::Os(ref code) =>
286 fmt.debug_struct("Os").field("code", code)
287 .field("message", &sys::os::error_string(*code)).finish(),
288 Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl fmt::Display for Error {
295 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
298 let detail = sys::os::error_string(code);
299 write!(fmt, "{} (os error {})", detail, code)
301 Repr::Custom(ref c) => c.error.fmt(fmt),
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl error::Error for Error {
308 fn description(&self) -> &str {
310 Repr::Os(..) => match self.kind() {
311 ErrorKind::NotFound => "entity not found",
312 ErrorKind::PermissionDenied => "permission denied",
313 ErrorKind::ConnectionRefused => "connection refused",
314 ErrorKind::ConnectionReset => "connection reset",
315 ErrorKind::ConnectionAborted => "connection aborted",
316 ErrorKind::NotConnected => "not connected",
317 ErrorKind::AddrInUse => "address in use",
318 ErrorKind::AddrNotAvailable => "address not available",
319 ErrorKind::BrokenPipe => "broken pipe",
320 ErrorKind::AlreadyExists => "entity already exists",
321 ErrorKind::WouldBlock => "operation would block",
322 ErrorKind::InvalidInput => "invalid input parameter",
323 ErrorKind::InvalidData => "invalid data",
324 ErrorKind::TimedOut => "timed out",
325 ErrorKind::WriteZero => "write zero",
326 ErrorKind::Interrupted => "operation interrupted",
327 ErrorKind::Other => "other os error",
328 ErrorKind::UnexpectedEof => "unexpected end of file",
329 ErrorKind::__Nonexhaustive => unreachable!()
331 Repr::Custom(ref c) => c.error.description(),
335 fn cause(&self) -> Option<&error::Error> {
337 Repr::Os(..) => None,
338 Repr::Custom(ref c) => c.error.cause(),
343 fn _assert_error_is_sync_send() {
344 fn _is_sync_send<T: Sync+Send>() {}
345 _is_sync_send::<Error>();
351 use super::{Error, ErrorKind};
353 use error::Error as error_Error;
355 use sys::os::error_string;
358 fn test_debug_error() {
360 let msg = error_string(code);
361 let err = Error { repr: super::Repr::Os(code) };
362 let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
363 assert_eq!(format!("{:?}", err), expected);
367 fn test_downcasting() {
371 impl fmt::Display for TestError {
372 fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
377 impl error::Error for TestError {
378 fn description(&self) -> &str {
383 // we have to call all of these UFCS style right now since method
384 // resolution won't implicitly drop the Send+Sync bounds
385 let mut err = Error::new(ErrorKind::Other, TestError);
386 assert!(err.get_ref().unwrap().is::<TestError>());
387 assert_eq!("asdf", err.get_ref().unwrap().description());
388 assert!(err.get_mut().unwrap().is::<TestError>());
389 let extracted = err.into_inner().unwrap();
390 extracted.downcast::<TestError>().unwrap();