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 #[allow(missing_docs)]
154 #[unstable(feature = "read_exact_old", reason = "recently added",
156 #[rustc_deprecated(since = "1.6.0", reason = "renamed to UnexpectedEof")]
159 /// An error returned when an operation could not be completed because an
160 /// "end of file" was reached prematurely.
162 /// This typically means that an operation could only succeed if it read a
163 /// particular number of bytes but only a smaller number of bytes could be
165 #[stable(feature = "read_exact", since = "1.6.0")]
168 /// Any I/O error not part of this list.
169 #[unstable(feature = "io_error_internals",
170 reason
= "better expressed through extensible enums that this \
171 enum cannot be exhaustively matched against",
178 /// Creates a new I/O error from a known kind of error as well as an
179 /// arbitrary error payload.
181 /// This function is used to generically create I/O errors which do not
182 /// originate from the OS itself. The `error` argument is an arbitrary
183 /// payload which will be contained in this `Error`.
188 /// use std::io::{Error, ErrorKind};
190 /// // errors can be created from strings
191 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
193 /// // errors can also be created from other errors
194 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub fn new
<E
>(kind
: ErrorKind
, error
: E
) -> Error
198 where E
: Into
<Box
<error
::Error
+Send
+Sync
>>
200 Self::_new(kind
, error
.into())
203 fn _new(kind
: ErrorKind
, error
: Box
<error
::Error
+Send
+Sync
>) -> Error
{
205 repr
: Repr
::Custom(Box
::new(Custom
{
212 /// Returns an error representing the last OS error which occurred.
214 /// This function reads the value of `errno` for the target platform (e.g.
215 /// `GetLastError` on Windows) and will return a corresponding instance of
216 /// `Error` for the error code.
217 #[stable(feature = "rust1", since = "1.0.0")]
218 pub fn last_os_error() -> Error
{
219 Error
::from_raw_os_error(sys
::os
::errno() as i32)
222 /// Creates a new instance of an `Error` from a particular OS error code.
223 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn from_raw_os_error(code
: i32) -> Error
{
225 Error { repr: Repr::Os(code) }
228 /// Returns the OS error that this error represents (if any).
230 /// If this `Error` was constructed via `last_os_error` or
231 /// `from_raw_os_error`, then this function will return `Some`, otherwise
232 /// it will return `None`.
233 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn raw_os_error(&self) -> Option
<i32> {
236 Repr
::Os(i
) => Some(i
),
237 Repr
::Custom(..) => None
,
241 /// Returns a reference to the inner error wrapped by this error (if any).
243 /// If this `Error` was constructed via `new` then this function will
244 /// return `Some`, otherwise it will return `None`.
245 #[stable(feature = "io_error_inner", since = "1.3.0")]
246 pub fn get_ref(&self) -> Option
<&(error
::Error
+Send
+Sync
+'
static)> {
248 Repr
::Os(..) => None
,
249 Repr
::Custom(ref c
) => Some(&*c
.error
),
253 /// Returns a mutable reference to the inner error wrapped by this error
256 /// If this `Error` was constructed via `new` then this function will
257 /// return `Some`, otherwise it will return `None`.
258 #[stable(feature = "io_error_inner", since = "1.3.0")]
259 pub fn get_mut(&mut self) -> Option
<&mut (error
::Error
+Send
+Sync
+'
static)> {
261 Repr
::Os(..) => None
,
262 Repr
::Custom(ref mut c
) => Some(&mut *c
.error
),
266 /// Consumes the `Error`, returning its inner error (if any).
268 /// If this `Error` was constructed via `new` then this function will
269 /// return `Some`, otherwise it will return `None`.
270 #[stable(feature = "io_error_inner", since = "1.3.0")]
271 pub fn into_inner(self) -> Option
<Box
<error
::Error
+Send
+Sync
>> {
273 Repr
::Os(..) => None
,
274 Repr
::Custom(c
) => Some(c
.error
)
278 /// Returns the corresponding `ErrorKind` for this error.
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn kind(&self) -> ErrorKind
{
282 Repr
::Os(code
) => sys
::decode_error_kind(code
),
283 Repr
::Custom(ref c
) => c
.kind
,
288 impl fmt
::Debug
for Repr
{
289 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
291 Repr
::Os(ref code
) =>
292 fmt
.debug_struct("Os").field("code", code
)
293 .field("message", &sys
::os
::error_string(*code
)).finish(),
294 Repr
::Custom(ref c
) => fmt
.debug_tuple("Custom").field(c
).finish(),
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl fmt
::Display
for Error
{
301 fn fmt(&self, fmt
: &mut fmt
::Formatter
) -> fmt
::Result
{
304 let detail
= sys
::os
::error_string(code
);
305 write
!(fmt
, "{} (os error {})", detail
, code
)
307 Repr
::Custom(ref c
) => c
.error
.fmt(fmt
),
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl error
::Error
for Error
{
314 #[allow(deprecated)] // remove with UnexpectedEOF
315 fn description(&self) -> &str {
317 Repr
::Os(..) => match self.kind() {
318 ErrorKind
::NotFound
=> "entity not found",
319 ErrorKind
::PermissionDenied
=> "permission denied",
320 ErrorKind
::ConnectionRefused
=> "connection refused",
321 ErrorKind
::ConnectionReset
=> "connection reset",
322 ErrorKind
::ConnectionAborted
=> "connection aborted",
323 ErrorKind
::NotConnected
=> "not connected",
324 ErrorKind
::AddrInUse
=> "address in use",
325 ErrorKind
::AddrNotAvailable
=> "address not available",
326 ErrorKind
::BrokenPipe
=> "broken pipe",
327 ErrorKind
::AlreadyExists
=> "entity already exists",
328 ErrorKind
::WouldBlock
=> "operation would block",
329 ErrorKind
::InvalidInput
=> "invalid input parameter",
330 ErrorKind
::InvalidData
=> "invalid data",
331 ErrorKind
::TimedOut
=> "timed out",
332 ErrorKind
::WriteZero
=> "write zero",
333 ErrorKind
::Interrupted
=> "operation interrupted",
334 ErrorKind
::Other
=> "other os error",
335 ErrorKind
::UnexpectedEOF
=> "unexpected end of file",
336 ErrorKind
::UnexpectedEof
=> "unexpected end of file",
337 ErrorKind
::__Nonexhaustive
=> unreachable
!()
339 Repr
::Custom(ref c
) => c
.error
.description(),
343 fn cause(&self) -> Option
<&error
::Error
> {
345 Repr
::Os(..) => None
,
346 Repr
::Custom(ref c
) => c
.error
.cause(),
351 fn _assert_error_is_sync_send() {
352 fn _is_sync_send
<T
: Sync
+Send
>() {}
353 _is_sync_send
::<Error
>();
359 use super::{Error, ErrorKind}
;
361 use error
::Error
as error_Error
;
363 use sys
::os
::error_string
;
366 fn test_debug_error() {
368 let msg
= error_string(code
);
369 let err
= Error { repr: super::Repr::Os(code) }
;
370 let expected
= format
!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code
, msg
);
371 assert_eq
!(format
!("{:?}", err
), expected
);
375 fn test_downcasting() {
379 impl fmt
::Display
for TestError
{
380 fn fmt(&self, _
: &mut fmt
::Formatter
) -> fmt
::Result
{
385 impl error
::Error
for TestError
{
386 fn description(&self) -> &str {
391 // we have to call all of these UFCS style right now since method
392 // resolution won't implicitly drop the Send+Sync bounds
393 let mut err
= Error
::new(ErrorKind
::Other
, TestError
);
394 assert
!(err
.get_ref().unwrap().is
::<TestError
>());
395 assert_eq
!("asdf", err
.get_ref().unwrap().description());
396 assert
!(err
.get_mut().unwrap().is
::<TestError
>());
397 let extracted
= err
.into_inner().unwrap();
398 extracted
.downcast
::<TestError
>().unwrap();