]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/error.rs
trans-scheduler: Let main thread take over for other worker.
[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 error;
12 use fmt;
13 use result;
14 use sys;
15 use convert::From;
16
17 /// A specialized [`Result`](../result/enum.Result.html) type for I/O
18 /// operations.
19 ///
20 /// This type is broadly used across `std::io` for any operation which may
21 /// produce an error.
22 ///
23 /// This typedef is generally used to avoid writing out `io::Error` directly and
24 /// is otherwise a direct mapping to `Result`.
25 ///
26 /// While usual Rust style is to import types directly, aliases of `Result`
27 /// often are not, to make it easier to distinguish between them. `Result` is
28 /// generally assumed to be `std::result::Result`, and so users of this alias
29 /// will generally use `io::Result` instead of shadowing the prelude's import
30 /// of `std::result::Result`.
31 ///
32 /// # Examples
33 ///
34 /// A convenience function that bubbles an `io::Result` to its caller:
35 ///
36 /// ```
37 /// use std::io;
38 ///
39 /// fn get_string() -> io::Result<String> {
40 ///     let mut buffer = String::new();
41 ///
42 ///     io::stdin().read_line(&mut buffer)?;
43 ///
44 ///     Ok(buffer)
45 /// }
46 /// ```
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub type Result<T> = result::Result<T, Error>;
49
50 /// The error type for I/O operations of the `Read`, `Write`, `Seek`, and
51 /// associated traits.
52 ///
53 /// Errors mostly originate from the underlying OS, but custom instances of
54 /// `Error` can be created with crafted error messages and a particular value of
55 /// [`ErrorKind`].
56 ///
57 /// [`ErrorKind`]: enum.ErrorKind.html
58 #[derive(Debug)]
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub struct Error {
61     repr: Repr,
62 }
63
64 enum Repr {
65     Os(i32),
66     Simple(ErrorKind),
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 ///
81 /// It is used with the [`io::Error`] type.
82 ///
83 /// [`io::Error`]: struct.Error.html
84 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
85 #[stable(feature = "rust1", since = "1.0.0")]
86 #[allow(deprecated)]
87 pub enum ErrorKind {
88     /// An entity was not found, often a file.
89     #[stable(feature = "rust1", since = "1.0.0")]
90     NotFound,
91     /// The operation lacked the necessary privileges to complete.
92     #[stable(feature = "rust1", since = "1.0.0")]
93     PermissionDenied,
94     /// The connection was refused by the remote server.
95     #[stable(feature = "rust1", since = "1.0.0")]
96     ConnectionRefused,
97     /// The connection was reset by the remote server.
98     #[stable(feature = "rust1", since = "1.0.0")]
99     ConnectionReset,
100     /// The connection was aborted (terminated) by the remote server.
101     #[stable(feature = "rust1", since = "1.0.0")]
102     ConnectionAborted,
103     /// The network operation failed because it was not connected yet.
104     #[stable(feature = "rust1", since = "1.0.0")]
105     NotConnected,
106     /// A socket address could not be bound because the address is already in
107     /// use elsewhere.
108     #[stable(feature = "rust1", since = "1.0.0")]
109     AddrInUse,
110     /// A nonexistent interface was requested or the requested address was not
111     /// local.
112     #[stable(feature = "rust1", since = "1.0.0")]
113     AddrNotAvailable,
114     /// The operation failed because a pipe was closed.
115     #[stable(feature = "rust1", since = "1.0.0")]
116     BrokenPipe,
117     /// An entity already exists, often a file.
118     #[stable(feature = "rust1", since = "1.0.0")]
119     AlreadyExists,
120     /// The operation needs to block to complete, but the blocking operation was
121     /// requested to not occur.
122     #[stable(feature = "rust1", since = "1.0.0")]
123     WouldBlock,
124     /// A parameter was incorrect.
125     #[stable(feature = "rust1", since = "1.0.0")]
126     InvalidInput,
127     /// Data not valid for the operation were encountered.
128     ///
129     /// Unlike [`InvalidInput`], this typically means that the operation
130     /// parameters were valid, however the error was caused by malformed
131     /// input data.
132     ///
133     /// For example, a function that reads a file into a string will error with
134     /// `InvalidData` if the file's contents are not valid UTF-8.
135     ///
136     /// [`InvalidInput`]: #variant.InvalidInput
137     #[stable(feature = "io_invalid_data", since = "1.2.0")]
138     InvalidData,
139     /// The I/O operation's timeout expired, causing it to be canceled.
140     #[stable(feature = "rust1", since = "1.0.0")]
141     TimedOut,
142     /// An error returned when an operation could not be completed because a
143     /// call to [`write`] returned [`Ok(0)`].
144     ///
145     /// This typically means that an operation could only succeed if it wrote a
146     /// particular number of bytes but only a smaller number of bytes could be
147     /// written.
148     ///
149     /// [`write`]: ../../std/io/trait.Write.html#tymethod.write
150     /// [`Ok(0)`]: ../../std/io/type.Result.html
151     #[stable(feature = "rust1", since = "1.0.0")]
152     WriteZero,
153     /// This operation was interrupted.
154     ///
155     /// Interrupted operations can typically be retried.
156     #[stable(feature = "rust1", since = "1.0.0")]
157     Interrupted,
158     /// Any I/O error not part of this list.
159     #[stable(feature = "rust1", since = "1.0.0")]
160     Other,
161
162     /// An error returned when an operation could not be completed because an
163     /// "end of file" was reached prematurely.
164     ///
165     /// This typically means that an operation could only succeed if it read a
166     /// particular number of bytes but only a smaller number of bytes could be
167     /// read.
168     #[stable(feature = "read_exact", since = "1.6.0")]
169     UnexpectedEof,
170
171     /// A marker variant that tells the compiler that users of this enum cannot
172     /// match it exhaustively.
173     #[unstable(feature = "io_error_internals",
174                reason = "better expressed through extensible enums that this \
175                          enum cannot be exhaustively matched against",
176                issue = "0")]
177     #[doc(hidden)]
178     __Nonexhaustive,
179 }
180
181 impl ErrorKind {
182     fn as_str(&self) -> &'static str {
183         match *self {
184             ErrorKind::NotFound => "entity not found",
185             ErrorKind::PermissionDenied => "permission denied",
186             ErrorKind::ConnectionRefused => "connection refused",
187             ErrorKind::ConnectionReset => "connection reset",
188             ErrorKind::ConnectionAborted => "connection aborted",
189             ErrorKind::NotConnected => "not connected",
190             ErrorKind::AddrInUse => "address in use",
191             ErrorKind::AddrNotAvailable => "address not available",
192             ErrorKind::BrokenPipe => "broken pipe",
193             ErrorKind::AlreadyExists => "entity already exists",
194             ErrorKind::WouldBlock => "operation would block",
195             ErrorKind::InvalidInput => "invalid input parameter",
196             ErrorKind::InvalidData => "invalid data",
197             ErrorKind::TimedOut => "timed out",
198             ErrorKind::WriteZero => "write zero",
199             ErrorKind::Interrupted => "operation interrupted",
200             ErrorKind::Other => "other os error",
201             ErrorKind::UnexpectedEof => "unexpected end of file",
202             ErrorKind::__Nonexhaustive => unreachable!()
203         }
204     }
205 }
206
207 /// Intended for use for errors not exposed to the user, where allocating onto
208 /// the heap (for normal construction via Error::new) is too costly.
209 #[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
210 impl From<ErrorKind> for Error {
211     #[inline]
212     fn from(kind: ErrorKind) -> Error {
213         Error {
214             repr: Repr::Simple(kind)
215         }
216     }
217 }
218
219 impl Error {
220     /// Creates a new I/O error from a known kind of error as well as an
221     /// arbitrary error payload.
222     ///
223     /// This function is used to generically create I/O errors which do not
224     /// originate from the OS itself. The `error` argument is an arbitrary
225     /// payload which will be contained in this `Error`.
226     ///
227     /// # Examples
228     ///
229     /// ```
230     /// use std::io::{Error, ErrorKind};
231     ///
232     /// // errors can be created from strings
233     /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
234     ///
235     /// // errors can also be created from other errors
236     /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
237     /// ```
238     #[stable(feature = "rust1", since = "1.0.0")]
239     pub fn new<E>(kind: ErrorKind, error: E) -> Error
240         where E: Into<Box<error::Error+Send+Sync>>
241     {
242         Self::_new(kind, error.into())
243     }
244
245     fn _new(kind: ErrorKind, error: Box<error::Error+Send+Sync>) -> Error {
246         Error {
247             repr: Repr::Custom(Box::new(Custom {
248                 kind: kind,
249                 error: error,
250             }))
251         }
252     }
253
254     /// Returns an error representing the last OS error which occurred.
255     ///
256     /// This function reads the value of `errno` for the target platform (e.g.
257     /// `GetLastError` on Windows) and will return a corresponding instance of
258     /// `Error` for the error code.
259     ///
260     /// # Examples
261     ///
262     /// ```
263     /// use std::io::Error;
264     ///
265     /// println!("last OS error: {:?}", Error::last_os_error());
266     /// ```
267     #[stable(feature = "rust1", since = "1.0.0")]
268     pub fn last_os_error() -> Error {
269         Error::from_raw_os_error(sys::os::errno() as i32)
270     }
271
272     /// Creates a new instance of an `Error` from a particular OS error code.
273     ///
274     /// # Examples
275     ///
276     /// On Linux:
277     ///
278     /// ```
279     /// # if cfg!(target_os = "linux") {
280     /// use std::io;
281     ///
282     /// let error = io::Error::from_raw_os_error(98);
283     /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
284     /// # }
285     /// ```
286     ///
287     /// On Windows:
288     ///
289     /// ```
290     /// # if cfg!(windows) {
291     /// use std::io;
292     ///
293     /// let error = io::Error::from_raw_os_error(10048);
294     /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
295     /// # }
296     /// ```
297     #[stable(feature = "rust1", since = "1.0.0")]
298     pub fn from_raw_os_error(code: i32) -> Error {
299         Error { repr: Repr::Os(code) }
300     }
301
302     /// Returns the OS error that this error represents (if any).
303     ///
304     /// If this `Error` was constructed via `last_os_error` or
305     /// `from_raw_os_error`, then this function will return `Some`, otherwise
306     /// it will return `None`.
307     ///
308     /// # Examples
309     ///
310     /// ```
311     /// use std::io::{Error, ErrorKind};
312     ///
313     /// fn print_os_error(err: &Error) {
314     ///     if let Some(raw_os_err) = err.raw_os_error() {
315     ///         println!("raw OS error: {:?}", raw_os_err);
316     ///     } else {
317     ///         println!("Not an OS error");
318     ///     }
319     /// }
320     ///
321     /// fn main() {
322     ///     // Will print "raw OS error: ...".
323     ///     print_os_error(&Error::last_os_error());
324     ///     // Will print "Not an OS error".
325     ///     print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
326     /// }
327     /// ```
328     #[stable(feature = "rust1", since = "1.0.0")]
329     pub fn raw_os_error(&self) -> Option<i32> {
330         match self.repr {
331             Repr::Os(i) => Some(i),
332             Repr::Custom(..) => None,
333             Repr::Simple(..) => None,
334         }
335     }
336
337     /// Returns a reference to the inner error wrapped by this error (if any).
338     ///
339     /// If this `Error` was constructed via `new` then this function will
340     /// return `Some`, otherwise it will return `None`.
341     ///
342     /// # Examples
343     ///
344     /// ```
345     /// use std::io::{Error, ErrorKind};
346     ///
347     /// fn print_error(err: &Error) {
348     ///     if let Some(inner_err) = err.get_ref() {
349     ///         println!("Inner error: {:?}", inner_err);
350     ///     } else {
351     ///         println!("No inner error");
352     ///     }
353     /// }
354     ///
355     /// fn main() {
356     ///     // Will print "No inner error".
357     ///     print_error(&Error::last_os_error());
358     ///     // Will print "Inner error: ...".
359     ///     print_error(&Error::new(ErrorKind::Other, "oh no!"));
360     /// }
361     /// ```
362     #[stable(feature = "io_error_inner", since = "1.3.0")]
363     pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> {
364         match self.repr {
365             Repr::Os(..) => None,
366             Repr::Simple(..) => None,
367             Repr::Custom(ref c) => Some(&*c.error),
368         }
369     }
370
371     /// Returns a mutable reference to the inner error wrapped by this error
372     /// (if any).
373     ///
374     /// If this `Error` was constructed via `new` then this function will
375     /// return `Some`, otherwise it will return `None`.
376     ///
377     /// # Examples
378     ///
379     /// ```
380     /// use std::io::{Error, ErrorKind};
381     /// use std::{error, fmt};
382     /// use std::fmt::Display;
383     ///
384     /// #[derive(Debug)]
385     /// struct MyError {
386     ///     v: String,
387     /// }
388     ///
389     /// impl MyError {
390     ///     fn new() -> MyError {
391     ///         MyError {
392     ///             v: "oh no!".to_string()
393     ///         }
394     ///     }
395     ///
396     ///     fn change_message(&mut self, new_message: &str) {
397     ///         self.v = new_message.to_string();
398     ///     }
399     /// }
400     ///
401     /// impl error::Error for MyError {
402     ///     fn description(&self) -> &str { &self.v }
403     /// }
404     ///
405     /// impl Display for MyError {
406     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
407     ///         write!(f, "MyError: {}", &self.v)
408     ///     }
409     /// }
410     ///
411     /// fn change_error(mut err: Error) -> Error {
412     ///     if let Some(inner_err) = err.get_mut() {
413     ///         inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
414     ///     }
415     ///     err
416     /// }
417     ///
418     /// fn print_error(err: &Error) {
419     ///     if let Some(inner_err) = err.get_ref() {
420     ///         println!("Inner error: {}", inner_err);
421     ///     } else {
422     ///         println!("No inner error");
423     ///     }
424     /// }
425     ///
426     /// fn main() {
427     ///     // Will print "No inner error".
428     ///     print_error(&change_error(Error::last_os_error()));
429     ///     // Will print "Inner error: ...".
430     ///     print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
431     /// }
432     /// ```
433     #[stable(feature = "io_error_inner", since = "1.3.0")]
434     pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> {
435         match self.repr {
436             Repr::Os(..) => None,
437             Repr::Simple(..) => None,
438             Repr::Custom(ref mut c) => Some(&mut *c.error),
439         }
440     }
441
442     /// Consumes the `Error`, returning its inner error (if any).
443     ///
444     /// If this `Error` was constructed via `new` then this function will
445     /// return `Some`, otherwise it will return `None`.
446     ///
447     /// # Examples
448     ///
449     /// ```
450     /// use std::io::{Error, ErrorKind};
451     ///
452     /// fn print_error(err: Error) {
453     ///     if let Some(inner_err) = err.into_inner() {
454     ///         println!("Inner error: {}", inner_err);
455     ///     } else {
456     ///         println!("No inner error");
457     ///     }
458     /// }
459     ///
460     /// fn main() {
461     ///     // Will print "No inner error".
462     ///     print_error(Error::last_os_error());
463     ///     // Will print "Inner error: ...".
464     ///     print_error(Error::new(ErrorKind::Other, "oh no!"));
465     /// }
466     /// ```
467     #[stable(feature = "io_error_inner", since = "1.3.0")]
468     pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> {
469         match self.repr {
470             Repr::Os(..) => None,
471             Repr::Simple(..) => None,
472             Repr::Custom(c) => Some(c.error)
473         }
474     }
475
476     /// Returns the corresponding `ErrorKind` for this error.
477     ///
478     /// # Examples
479     ///
480     /// ```
481     /// use std::io::{Error, ErrorKind};
482     ///
483     /// fn print_error(err: Error) {
484     ///     println!("{:?}", err.kind());
485     /// }
486     ///
487     /// fn main() {
488     ///     // Will print "No inner error".
489     ///     print_error(Error::last_os_error());
490     ///     // Will print "Inner error: ...".
491     ///     print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
492     /// }
493     /// ```
494     #[stable(feature = "rust1", since = "1.0.0")]
495     pub fn kind(&self) -> ErrorKind {
496         match self.repr {
497             Repr::Os(code) => sys::decode_error_kind(code),
498             Repr::Custom(ref c) => c.kind,
499             Repr::Simple(kind) => kind,
500         }
501     }
502 }
503
504 impl fmt::Debug for Repr {
505     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
506         match *self {
507             Repr::Os(ref code) =>
508                 fmt.debug_struct("Os").field("code", code)
509                    .field("message", &sys::os::error_string(*code)).finish(),
510             Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
511             Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
512         }
513     }
514 }
515
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl fmt::Display for Error {
518     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
519         match self.repr {
520             Repr::Os(code) => {
521                 let detail = sys::os::error_string(code);
522                 write!(fmt, "{} (os error {})", detail, code)
523             }
524             Repr::Custom(ref c) => c.error.fmt(fmt),
525             Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
526         }
527     }
528 }
529
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl error::Error for Error {
532     fn description(&self) -> &str {
533         match self.repr {
534             Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
535             Repr::Custom(ref c) => c.error.description(),
536         }
537     }
538
539     fn cause(&self) -> Option<&error::Error> {
540         match self.repr {
541             Repr::Os(..) => None,
542             Repr::Simple(..) => None,
543             Repr::Custom(ref c) => c.error.cause(),
544         }
545     }
546 }
547
548 fn _assert_error_is_sync_send() {
549     fn _is_sync_send<T: Sync+Send>() {}
550     _is_sync_send::<Error>();
551 }
552
553 #[cfg(test)]
554 mod test {
555     use super::{Error, ErrorKind};
556     use error;
557     use fmt;
558     use sys::os::error_string;
559
560     #[test]
561     fn test_debug_error() {
562         let code = 6;
563         let msg = error_string(code);
564         let err = Error { repr: super::Repr::Os(code) };
565         let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
566         assert_eq!(format!("{:?}", err), expected);
567     }
568
569     #[test]
570     fn test_downcasting() {
571         #[derive(Debug)]
572         struct TestError;
573
574         impl fmt::Display for TestError {
575             fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
576                 Ok(())
577             }
578         }
579
580         impl error::Error for TestError {
581             fn description(&self) -> &str {
582                 "asdf"
583             }
584         }
585
586         // we have to call all of these UFCS style right now since method
587         // resolution won't implicitly drop the Send+Sync bounds
588         let mut err = Error::new(ErrorKind::Other, TestError);
589         assert!(err.get_ref().unwrap().is::<TestError>());
590         assert_eq!("asdf", err.get_ref().unwrap().description());
591         assert!(err.get_mut().unwrap().is::<TestError>());
592         let extracted = err.into_inner().unwrap();
593         extracted.downcast::<TestError>().unwrap();
594     }
595 }