]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/error.rs
std: Clean out deprecated APIs
[rust.git] / src / libstd / io / error.rs
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.
4 //
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.
10
11 use boxed::Box;
12 use convert::Into;
13 use error;
14 use fmt;
15 use marker::{Send, Sync};
16 use option::Option::{self, Some, None};
17 use result;
18 use sys;
19
20 /// A specialized [`Result`](../result/enum.Result.html) type for I/O
21 /// operations.
22 ///
23 /// This type is broadly used across `std::io` for any operation which may
24 /// produce an error.
25 ///
26 /// This typedef is generally used to avoid writing out `io::Error` directly and
27 /// is otherwise a direct mapping to `Result`.
28 ///
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`.
34 ///
35 /// # Examples
36 ///
37 /// A convenience function that bubbles an `io::Result` to its caller:
38 ///
39 /// ```
40 /// use std::io;
41 ///
42 /// fn get_string() -> io::Result<String> {
43 ///     let mut buffer = String::new();
44 ///
45 ///     try!(io::stdin().read_line(&mut buffer));
46 ///
47 ///     Ok(buffer)
48 /// }
49 /// ```
50 #[stable(feature = "rust1", since = "1.0.0")]
51 pub type Result<T> = result::Result<T, Error>;
52
53 /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
54 /// associated traits.
55 ///
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
58 /// `ErrorKind`.
59 #[derive(Debug)]
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub struct Error {
62     repr: Repr,
63 }
64
65 enum Repr {
66     Os(i32),
67     Custom(Box<Custom>),
68 }
69
70 #[derive(Debug)]
71 struct Custom {
72     kind: ErrorKind,
73     error: Box<error::Error+Send+Sync>,
74 }
75
76 /// A list specifying general categories of I/O error.
77 ///
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")]
82 #[allow(deprecated)]
83 pub enum ErrorKind {
84     /// An entity was not found, often a file.
85     #[stable(feature = "rust1", since = "1.0.0")]
86     NotFound,
87     /// The operation lacked the necessary privileges to complete.
88     #[stable(feature = "rust1", since = "1.0.0")]
89     PermissionDenied,
90     /// The connection was refused by the remote server.
91     #[stable(feature = "rust1", since = "1.0.0")]
92     ConnectionRefused,
93     /// The connection was reset by the remote server.
94     #[stable(feature = "rust1", since = "1.0.0")]
95     ConnectionReset,
96     /// The connection was aborted (terminated) by the remote server.
97     #[stable(feature = "rust1", since = "1.0.0")]
98     ConnectionAborted,
99     /// The network operation failed because it was not connected yet.
100     #[stable(feature = "rust1", since = "1.0.0")]
101     NotConnected,
102     /// A socket address could not be bound because the address is already in
103     /// use elsewhere.
104     #[stable(feature = "rust1", since = "1.0.0")]
105     AddrInUse,
106     /// A nonexistent interface was requested or the requested address was not
107     /// local.
108     #[stable(feature = "rust1", since = "1.0.0")]
109     AddrNotAvailable,
110     /// The operation failed because a pipe was closed.
111     #[stable(feature = "rust1", since = "1.0.0")]
112     BrokenPipe,
113     /// An entity already exists, often a file.
114     #[stable(feature = "rust1", since = "1.0.0")]
115     AlreadyExists,
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")]
119     WouldBlock,
120     /// A parameter was incorrect.
121     #[stable(feature = "rust1", since = "1.0.0")]
122     InvalidInput,
123     /// Data not valid for the operation were encountered.
124     ///
125     /// Unlike `InvalidInput`, this typically means that the operation
126     /// parameters were valid, however the error was caused by malformed
127     /// input data.
128     ///
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")]
132     InvalidData,
133     /// The I/O operation's timeout expired, causing it to be canceled.
134     #[stable(feature = "rust1", since = "1.0.0")]
135     TimedOut,
136     /// An error returned when an operation could not be completed because a
137     /// call to `write` returned `Ok(0)`.
138     ///
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
141     /// written.
142     #[stable(feature = "rust1", since = "1.0.0")]
143     WriteZero,
144     /// This operation was interrupted.
145     ///
146     /// Interrupted operations can typically be retried.
147     #[stable(feature = "rust1", since = "1.0.0")]
148     Interrupted,
149     /// Any I/O error not part of this list.
150     #[stable(feature = "rust1", since = "1.0.0")]
151     Other,
152
153     /// An error returned when an operation could not be completed because an
154     /// "end of file" was reached prematurely.
155     ///
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
158     /// read.
159     #[stable(feature = "read_exact", since = "1.6.0")]
160     UnexpectedEof,
161
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",
166                issue = "0")]
167     #[doc(hidden)]
168     __Nonexhaustive,
169 }
170
171 impl Error {
172     /// Creates a new I/O error from a known kind of error as well as an
173     /// arbitrary error payload.
174     ///
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`.
178     ///
179     /// # Examples
180     ///
181     /// ```
182     /// use std::io::{Error, ErrorKind};
183     ///
184     /// // errors can be created from strings
185     /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
186     ///
187     /// // errors can also be created from other errors
188     /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
189     /// ```
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>>
193     {
194         Self::_new(kind, error.into())
195     }
196
197     fn _new(kind: ErrorKind, error: Box<error::Error+Send+Sync>) -> Error {
198         Error {
199             repr: Repr::Custom(Box::new(Custom {
200                 kind: kind,
201                 error: error,
202             }))
203         }
204     }
205
206     /// Returns an error representing the last OS error which occurred.
207     ///
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)
214     }
215
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) }
220     }
221
222     /// Returns the OS error that this error represents (if any).
223     ///
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> {
229         match self.repr {
230             Repr::Os(i) => Some(i),
231             Repr::Custom(..) => None,
232         }
233     }
234
235     /// Returns a reference to the inner error wrapped by this error (if any).
236     ///
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)> {
241         match self.repr {
242             Repr::Os(..) => None,
243             Repr::Custom(ref c) => Some(&*c.error),
244         }
245     }
246
247     /// Returns a mutable reference to the inner error wrapped by this error
248     /// (if any).
249     ///
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)> {
254         match self.repr {
255             Repr::Os(..) => None,
256             Repr::Custom(ref mut c) => Some(&mut *c.error),
257         }
258     }
259
260     /// Consumes the `Error`, returning its inner error (if any).
261     ///
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>> {
266         match self.repr {
267             Repr::Os(..) => None,
268             Repr::Custom(c) => Some(c.error)
269         }
270     }
271
272     /// Returns the corresponding `ErrorKind` for this error.
273     #[stable(feature = "rust1", since = "1.0.0")]
274     pub fn kind(&self) -> ErrorKind {
275         match self.repr {
276             Repr::Os(code) => sys::decode_error_kind(code),
277             Repr::Custom(ref c) => c.kind,
278         }
279     }
280 }
281
282 impl fmt::Debug for Repr {
283     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
284         match *self {
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(),
289         }
290     }
291 }
292
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl fmt::Display for Error {
295     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
296         match self.repr {
297             Repr::Os(code) => {
298                 let detail = sys::os::error_string(code);
299                 write!(fmt, "{} (os error {})", detail, code)
300             }
301             Repr::Custom(ref c) => c.error.fmt(fmt),
302         }
303     }
304 }
305
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl error::Error for Error {
308     fn description(&self) -> &str {
309         match self.repr {
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!()
330             },
331             Repr::Custom(ref c) => c.error.description(),
332         }
333     }
334
335     fn cause(&self) -> Option<&error::Error> {
336         match self.repr {
337             Repr::Os(..) => None,
338             Repr::Custom(ref c) => c.error.cause(),
339         }
340     }
341 }
342
343 fn _assert_error_is_sync_send() {
344     fn _is_sync_send<T: Sync+Send>() {}
345     _is_sync_send::<Error>();
346 }
347
348 #[cfg(test)]
349 mod test {
350     use prelude::v1::*;
351     use super::{Error, ErrorKind};
352     use error;
353     use error::Error as error_Error;
354     use fmt;
355     use sys::os::error_string;
356
357     #[test]
358     fn test_debug_error() {
359         let code = 6;
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);
364     }
365
366     #[test]
367     fn test_downcasting() {
368         #[derive(Debug)]
369         struct TestError;
370
371         impl fmt::Display for TestError {
372             fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
373                 Ok(())
374             }
375         }
376
377         impl error::Error for TestError {
378             fn description(&self) -> &str {
379                 "asdf"
380             }
381         }
382
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();
391     }
392 }