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