]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/error.rs
add inline attributes to stage 0 methods
[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     fn from(kind: ErrorKind) -> Error {
212         Error {
213             repr: Repr::Simple(kind)
214         }
215     }
216 }
217
218 impl Error {
219     /// Creates a new I/O error from a known kind of error as well as an
220     /// arbitrary error payload.
221     ///
222     /// This function is used to generically create I/O errors which do not
223     /// originate from the OS itself. The `error` argument is an arbitrary
224     /// payload which will be contained in this `Error`.
225     ///
226     /// # Examples
227     ///
228     /// ```
229     /// use std::io::{Error, ErrorKind};
230     ///
231     /// // errors can be created from strings
232     /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
233     ///
234     /// // errors can also be created from other errors
235     /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
236     /// ```
237     #[stable(feature = "rust1", since = "1.0.0")]
238     pub fn new<E>(kind: ErrorKind, error: E) -> Error
239         where E: Into<Box<error::Error+Send+Sync>>
240     {
241         Self::_new(kind, error.into())
242     }
243
244     fn _new(kind: ErrorKind, error: Box<error::Error+Send+Sync>) -> Error {
245         Error {
246             repr: Repr::Custom(Box::new(Custom {
247                 kind: kind,
248                 error: error,
249             }))
250         }
251     }
252
253     /// Returns an error representing the last OS error which occurred.
254     ///
255     /// This function reads the value of `errno` for the target platform (e.g.
256     /// `GetLastError` on Windows) and will return a corresponding instance of
257     /// `Error` for the error code.
258     ///
259     /// # Examples
260     ///
261     /// ```
262     /// use std::io::Error;
263     ///
264     /// println!("last OS error: {:?}", Error::last_os_error());
265     /// ```
266     #[stable(feature = "rust1", since = "1.0.0")]
267     pub fn last_os_error() -> Error {
268         Error::from_raw_os_error(sys::os::errno() as i32)
269     }
270
271     /// Creates a new instance of an `Error` from a particular OS error code.
272     ///
273     /// # Examples
274     ///
275     /// On Linux:
276     ///
277     /// ```
278     /// # if cfg!(target_os = "linux") {
279     /// use std::io;
280     ///
281     /// let error = io::Error::from_raw_os_error(98);
282     /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
283     /// # }
284     /// ```
285     ///
286     /// On Windows:
287     ///
288     /// ```
289     /// # if cfg!(windows) {
290     /// use std::io;
291     ///
292     /// let error = io::Error::from_raw_os_error(10048);
293     /// assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
294     /// # }
295     /// ```
296     #[stable(feature = "rust1", since = "1.0.0")]
297     pub fn from_raw_os_error(code: i32) -> Error {
298         Error { repr: Repr::Os(code) }
299     }
300
301     /// Returns the OS error that this error represents (if any).
302     ///
303     /// If this `Error` was constructed via `last_os_error` or
304     /// `from_raw_os_error`, then this function will return `Some`, otherwise
305     /// it will return `None`.
306     ///
307     /// # Examples
308     ///
309     /// ```
310     /// use std::io::{Error, ErrorKind};
311     ///
312     /// fn print_os_error(err: &Error) {
313     ///     if let Some(raw_os_err) = err.raw_os_error() {
314     ///         println!("raw OS error: {:?}", raw_os_err);
315     ///     } else {
316     ///         println!("Not an OS error");
317     ///     }
318     /// }
319     ///
320     /// fn main() {
321     ///     // Will print "raw OS error: ...".
322     ///     print_os_error(&Error::last_os_error());
323     ///     // Will print "Not an OS error".
324     ///     print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
325     /// }
326     /// ```
327     #[stable(feature = "rust1", since = "1.0.0")]
328     pub fn raw_os_error(&self) -> Option<i32> {
329         match self.repr {
330             Repr::Os(i) => Some(i),
331             Repr::Custom(..) => None,
332             Repr::Simple(..) => None,
333         }
334     }
335
336     /// Returns a reference to the inner error wrapped by this error (if any).
337     ///
338     /// If this `Error` was constructed via `new` then this function will
339     /// return `Some`, otherwise it will return `None`.
340     ///
341     /// # Examples
342     ///
343     /// ```
344     /// use std::io::{Error, ErrorKind};
345     ///
346     /// fn print_error(err: &Error) {
347     ///     if let Some(inner_err) = err.get_ref() {
348     ///         println!("Inner error: {:?}", inner_err);
349     ///     } else {
350     ///         println!("No inner error");
351     ///     }
352     /// }
353     ///
354     /// fn main() {
355     ///     // Will print "No inner error".
356     ///     print_error(&Error::last_os_error());
357     ///     // Will print "Inner error: ...".
358     ///     print_error(&Error::new(ErrorKind::Other, "oh no!"));
359     /// }
360     /// ```
361     #[stable(feature = "io_error_inner", since = "1.3.0")]
362     pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> {
363         match self.repr {
364             Repr::Os(..) => None,
365             Repr::Simple(..) => None,
366             Repr::Custom(ref c) => Some(&*c.error),
367         }
368     }
369
370     /// Returns a mutable reference to the inner error wrapped by this error
371     /// (if any).
372     ///
373     /// If this `Error` was constructed via `new` then this function will
374     /// return `Some`, otherwise it will return `None`.
375     ///
376     /// # Examples
377     ///
378     /// ```
379     /// use std::io::{Error, ErrorKind};
380     /// use std::{error, fmt};
381     /// use std::fmt::Display;
382     ///
383     /// #[derive(Debug)]
384     /// struct MyError {
385     ///     v: String,
386     /// }
387     ///
388     /// impl MyError {
389     ///     fn new() -> MyError {
390     ///         MyError {
391     ///             v: "oh no!".to_string()
392     ///         }
393     ///     }
394     ///
395     ///     fn change_message(&mut self, new_message: &str) {
396     ///         self.v = new_message.to_string();
397     ///     }
398     /// }
399     ///
400     /// impl error::Error for MyError {
401     ///     fn description(&self) -> &str { &self.v }
402     /// }
403     ///
404     /// impl Display for MyError {
405     ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
406     ///         write!(f, "MyError: {}", &self.v)
407     ///     }
408     /// }
409     ///
410     /// fn change_error(mut err: Error) -> Error {
411     ///     if let Some(inner_err) = err.get_mut() {
412     ///         inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
413     ///     }
414     ///     err
415     /// }
416     ///
417     /// fn print_error(err: &Error) {
418     ///     if let Some(inner_err) = err.get_ref() {
419     ///         println!("Inner error: {}", inner_err);
420     ///     } else {
421     ///         println!("No inner error");
422     ///     }
423     /// }
424     ///
425     /// fn main() {
426     ///     // Will print "No inner error".
427     ///     print_error(&change_error(Error::last_os_error()));
428     ///     // Will print "Inner error: ...".
429     ///     print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
430     /// }
431     /// ```
432     #[stable(feature = "io_error_inner", since = "1.3.0")]
433     pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> {
434         match self.repr {
435             Repr::Os(..) => None,
436             Repr::Simple(..) => None,
437             Repr::Custom(ref mut c) => Some(&mut *c.error),
438         }
439     }
440
441     /// Consumes the `Error`, returning its inner error (if any).
442     ///
443     /// If this `Error` was constructed via `new` then this function will
444     /// return `Some`, otherwise it will return `None`.
445     ///
446     /// # Examples
447     ///
448     /// ```
449     /// use std::io::{Error, ErrorKind};
450     ///
451     /// fn print_error(err: Error) {
452     ///     if let Some(inner_err) = err.into_inner() {
453     ///         println!("Inner error: {}", inner_err);
454     ///     } else {
455     ///         println!("No inner error");
456     ///     }
457     /// }
458     ///
459     /// fn main() {
460     ///     // Will print "No inner error".
461     ///     print_error(Error::last_os_error());
462     ///     // Will print "Inner error: ...".
463     ///     print_error(Error::new(ErrorKind::Other, "oh no!"));
464     /// }
465     /// ```
466     #[stable(feature = "io_error_inner", since = "1.3.0")]
467     pub fn into_inner(self) -> Option<Box<error::Error+Send+Sync>> {
468         match self.repr {
469             Repr::Os(..) => None,
470             Repr::Simple(..) => None,
471             Repr::Custom(c) => Some(c.error)
472         }
473     }
474
475     /// Returns the corresponding `ErrorKind` for this error.
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// use std::io::{Error, ErrorKind};
481     ///
482     /// fn print_error(err: Error) {
483     ///     println!("{:?}", err.kind());
484     /// }
485     ///
486     /// fn main() {
487     ///     // Will print "No inner error".
488     ///     print_error(Error::last_os_error());
489     ///     // Will print "Inner error: ...".
490     ///     print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
491     /// }
492     /// ```
493     #[stable(feature = "rust1", since = "1.0.0")]
494     pub fn kind(&self) -> ErrorKind {
495         match self.repr {
496             Repr::Os(code) => sys::decode_error_kind(code),
497             Repr::Custom(ref c) => c.kind,
498             Repr::Simple(kind) => kind,
499         }
500     }
501 }
502
503 impl fmt::Debug for Repr {
504     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
505         match *self {
506             Repr::Os(ref code) =>
507                 fmt.debug_struct("Os").field("code", code)
508                    .field("message", &sys::os::error_string(*code)).finish(),
509             Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
510             Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
511         }
512     }
513 }
514
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl fmt::Display for Error {
517     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
518         match self.repr {
519             Repr::Os(code) => {
520                 let detail = sys::os::error_string(code);
521                 write!(fmt, "{} (os error {})", detail, code)
522             }
523             Repr::Custom(ref c) => c.error.fmt(fmt),
524             Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
525         }
526     }
527 }
528
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl error::Error for Error {
531     fn description(&self) -> &str {
532         match self.repr {
533             Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
534             Repr::Custom(ref c) => c.error.description(),
535         }
536     }
537
538     fn cause(&self) -> Option<&error::Error> {
539         match self.repr {
540             Repr::Os(..) => None,
541             Repr::Simple(..) => None,
542             Repr::Custom(ref c) => c.error.cause(),
543         }
544     }
545 }
546
547 fn _assert_error_is_sync_send() {
548     fn _is_sync_send<T: Sync+Send>() {}
549     _is_sync_send::<Error>();
550 }
551
552 #[cfg(test)]
553 mod test {
554     use super::{Error, ErrorKind};
555     use error;
556     use fmt;
557     use sys::os::error_string;
558
559     #[test]
560     fn test_debug_error() {
561         let code = 6;
562         let msg = error_string(code);
563         let err = Error { repr: super::Repr::Os(code) };
564         let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
565         assert_eq!(format!("{:?}", err), expected);
566     }
567
568     #[test]
569     fn test_downcasting() {
570         #[derive(Debug)]
571         struct TestError;
572
573         impl fmt::Display for TestError {
574             fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result {
575                 Ok(())
576             }
577         }
578
579         impl error::Error for TestError {
580             fn description(&self) -> &str {
581                 "asdf"
582             }
583         }
584
585         // we have to call all of these UFCS style right now since method
586         // resolution won't implicitly drop the Send+Sync bounds
587         let mut err = Error::new(ErrorKind::Other, TestError);
588         assert!(err.get_ref().unwrap().is::<TestError>());
589         assert_eq!("asdf", err.get_ref().unwrap().description());
590         assert!(err.get_mut().unwrap().is::<TestError>());
591         let extracted = err.into_inner().unwrap();
592         extracted.downcast::<TestError>().unwrap();
593     }
594 }