]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/error.rs
Rollup merge of #93497 - willcrichton:rustdoc-scrape-test, r=GuillaumeGomez
[rust.git] / library / std / src / io / error.rs
1 #[cfg(test)]
2 mod tests;
3
4 #[cfg(target_pointer_width = "64")]
5 mod repr_bitpacked;
6 #[cfg(target_pointer_width = "64")]
7 use repr_bitpacked::Repr;
8
9 #[cfg(not(target_pointer_width = "64"))]
10 mod repr_unpacked;
11 #[cfg(not(target_pointer_width = "64"))]
12 use repr_unpacked::Repr;
13
14 use crate::convert::From;
15 use crate::error;
16 use crate::fmt;
17 use crate::result;
18 use crate::sys;
19
20 /// A specialized [`Result`] type for I/O operations.
21 ///
22 /// This type is broadly used across [`std::io`] for any operation which may
23 /// produce an error.
24 ///
25 /// This typedef is generally used to avoid writing out [`io::Error`] directly and
26 /// is otherwise a direct mapping to [`Result`].
27 ///
28 /// While usual Rust style is to import types directly, aliases of [`Result`]
29 /// often are not, to make it easier to distinguish between them. [`Result`] is
30 /// generally assumed to be [`std::result::Result`][`Result`], and so users of this alias
31 /// will generally use `io::Result` instead of shadowing the [prelude]'s import
32 /// of [`std::result::Result`][`Result`].
33 ///
34 /// [`std::io`]: crate::io
35 /// [`io::Error`]: Error
36 /// [`Result`]: crate::result::Result
37 /// [prelude]: crate::prelude
38 ///
39 /// # Examples
40 ///
41 /// A convenience function that bubbles an `io::Result` to its caller:
42 ///
43 /// ```
44 /// use std::io;
45 ///
46 /// fn get_string() -> io::Result<String> {
47 ///     let mut buffer = String::new();
48 ///
49 ///     io::stdin().read_line(&mut buffer)?;
50 ///
51 ///     Ok(buffer)
52 /// }
53 /// ```
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub type Result<T> = result::Result<T, Error>;
56
57 /// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and
58 /// associated traits.
59 ///
60 /// Errors mostly originate from the underlying OS, but custom instances of
61 /// `Error` can be created with crafted error messages and a particular value of
62 /// [`ErrorKind`].
63 ///
64 /// [`Read`]: crate::io::Read
65 /// [`Write`]: crate::io::Write
66 /// [`Seek`]: crate::io::Seek
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub struct Error {
69     repr: Repr,
70 }
71
72 #[stable(feature = "rust1", since = "1.0.0")]
73 impl fmt::Debug for Error {
74     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75         fmt::Debug::fmt(&self.repr, f)
76     }
77 }
78
79 // Only derive debug in tests, to make sure it
80 // doesn't accidentally get printed.
81 #[cfg_attr(test, derive(Debug))]
82 enum ErrorData<C> {
83     Os(i32),
84     Simple(ErrorKind),
85     SimpleMessage(&'static SimpleMessage),
86     Custom(C),
87 }
88
89 // `#[repr(align(4))]` is probably redundant, it should have that value or
90 // higher already. We include it just because repr_bitpacked.rs's encoding
91 // requires an alignment >= 4 (note that `#[repr(align)]` will not reduce the
92 // alignment required by the struct, only increase it).
93 //
94 // If we add more variants to ErrorData, this can be increased to 8, but it
95 // should probably be behind `#[cfg_attr(target_pointer_width = "64", ...)]` or
96 // whatever cfg we're using to enable the `repr_bitpacked` code, since only the
97 // that version needs the alignment, and 8 is higher than the alignment we'll
98 // have on 32 bit platforms.
99 //
100 // (For the sake of being explicit: the alignment requirement here only matters
101 // if `error/repr_bitpacked.rs` is in use — for the unpacked repr it doesn't
102 // matter at all)
103 #[repr(align(4))]
104 #[derive(Debug)]
105 pub(crate) struct SimpleMessage {
106     kind: ErrorKind,
107     message: &'static str,
108 }
109
110 impl SimpleMessage {
111     pub(crate) const fn new(kind: ErrorKind, message: &'static str) -> Self {
112         Self { kind, message }
113     }
114 }
115
116 /// Create and return an `io::Error` for a given `ErrorKind` and constant
117 /// message. This doesn't allocate.
118 pub(crate) macro const_io_error($kind:expr, $message:expr $(,)?) {
119     $crate::io::error::Error::from_static_message({
120         const MESSAGE_DATA: $crate::io::error::SimpleMessage =
121             $crate::io::error::SimpleMessage::new($kind, $message);
122         &MESSAGE_DATA
123     })
124 }
125
126 // As with `SimpleMessage`: `#[repr(align(4))]` here is just because
127 // repr_bitpacked's encoding requires it. In practice it almost certainly be
128 // already be this high or higher.
129 #[derive(Debug)]
130 #[repr(align(4))]
131 struct Custom {
132     kind: ErrorKind,
133     error: Box<dyn error::Error + Send + Sync>,
134 }
135
136 /// A list specifying general categories of I/O error.
137 ///
138 /// This list is intended to grow over time and it is not recommended to
139 /// exhaustively match against it.
140 ///
141 /// It is used with the [`io::Error`] type.
142 ///
143 /// [`io::Error`]: Error
144 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[allow(deprecated)]
147 #[non_exhaustive]
148 pub enum ErrorKind {
149     /// An entity was not found, often a file.
150     #[stable(feature = "rust1", since = "1.0.0")]
151     NotFound,
152     /// The operation lacked the necessary privileges to complete.
153     #[stable(feature = "rust1", since = "1.0.0")]
154     PermissionDenied,
155     /// The connection was refused by the remote server.
156     #[stable(feature = "rust1", since = "1.0.0")]
157     ConnectionRefused,
158     /// The connection was reset by the remote server.
159     #[stable(feature = "rust1", since = "1.0.0")]
160     ConnectionReset,
161     /// The remote host is not reachable.
162     #[unstable(feature = "io_error_more", issue = "86442")]
163     HostUnreachable,
164     /// The network containing the remote host is not reachable.
165     #[unstable(feature = "io_error_more", issue = "86442")]
166     NetworkUnreachable,
167     /// The connection was aborted (terminated) by the remote server.
168     #[stable(feature = "rust1", since = "1.0.0")]
169     ConnectionAborted,
170     /// The network operation failed because it was not connected yet.
171     #[stable(feature = "rust1", since = "1.0.0")]
172     NotConnected,
173     /// A socket address could not be bound because the address is already in
174     /// use elsewhere.
175     #[stable(feature = "rust1", since = "1.0.0")]
176     AddrInUse,
177     /// A nonexistent interface was requested or the requested address was not
178     /// local.
179     #[stable(feature = "rust1", since = "1.0.0")]
180     AddrNotAvailable,
181     /// The system's networking is down.
182     #[unstable(feature = "io_error_more", issue = "86442")]
183     NetworkDown,
184     /// The operation failed because a pipe was closed.
185     #[stable(feature = "rust1", since = "1.0.0")]
186     BrokenPipe,
187     /// An entity already exists, often a file.
188     #[stable(feature = "rust1", since = "1.0.0")]
189     AlreadyExists,
190     /// The operation needs to block to complete, but the blocking operation was
191     /// requested to not occur.
192     #[stable(feature = "rust1", since = "1.0.0")]
193     WouldBlock,
194     /// A filesystem object is, unexpectedly, not a directory.
195     ///
196     /// For example, a filesystem path was specified where one of the intermediate directory
197     /// components was, in fact, a plain file.
198     #[unstable(feature = "io_error_more", issue = "86442")]
199     NotADirectory,
200     /// The filesystem object is, unexpectedly, a directory.
201     ///
202     /// A directory was specified when a non-directory was expected.
203     #[unstable(feature = "io_error_more", issue = "86442")]
204     IsADirectory,
205     /// A non-empty directory was specified where an empty directory was expected.
206     #[unstable(feature = "io_error_more", issue = "86442")]
207     DirectoryNotEmpty,
208     /// The filesystem or storage medium is read-only, but a write operation was attempted.
209     #[unstable(feature = "io_error_more", issue = "86442")]
210     ReadOnlyFilesystem,
211     /// Loop in the filesystem or IO subsystem; often, too many levels of symbolic links.
212     ///
213     /// There was a loop (or excessively long chain) resolving a filesystem object
214     /// or file IO object.
215     ///
216     /// On Unix this is usually the result of a symbolic link loop; or, of exceeding the
217     /// system-specific limit on the depth of symlink traversal.
218     #[unstable(feature = "io_error_more", issue = "86442")]
219     FilesystemLoop,
220     /// Stale network file handle.
221     ///
222     /// With some network filesystems, notably NFS, an open file (or directory) can be invalidated
223     /// by problems with the network or server.
224     #[unstable(feature = "io_error_more", issue = "86442")]
225     StaleNetworkFileHandle,
226     /// A parameter was incorrect.
227     #[stable(feature = "rust1", since = "1.0.0")]
228     InvalidInput,
229     /// Data not valid for the operation were encountered.
230     ///
231     /// Unlike [`InvalidInput`], this typically means that the operation
232     /// parameters were valid, however the error was caused by malformed
233     /// input data.
234     ///
235     /// For example, a function that reads a file into a string will error with
236     /// `InvalidData` if the file's contents are not valid UTF-8.
237     ///
238     /// [`InvalidInput`]: ErrorKind::InvalidInput
239     #[stable(feature = "io_invalid_data", since = "1.2.0")]
240     InvalidData,
241     /// The I/O operation's timeout expired, causing it to be canceled.
242     #[stable(feature = "rust1", since = "1.0.0")]
243     TimedOut,
244     /// An error returned when an operation could not be completed because a
245     /// call to [`write`] returned [`Ok(0)`].
246     ///
247     /// This typically means that an operation could only succeed if it wrote a
248     /// particular number of bytes but only a smaller number of bytes could be
249     /// written.
250     ///
251     /// [`write`]: crate::io::Write::write
252     /// [`Ok(0)`]: Ok
253     #[stable(feature = "rust1", since = "1.0.0")]
254     WriteZero,
255     /// The underlying storage (typically, a filesystem) is full.
256     ///
257     /// This does not include out of quota errors.
258     #[unstable(feature = "io_error_more", issue = "86442")]
259     StorageFull,
260     /// Seek on unseekable file.
261     ///
262     /// Seeking was attempted on an open file handle which is not suitable for seeking - for
263     /// example, on Unix, a named pipe opened with `File::open`.
264     #[unstable(feature = "io_error_more", issue = "86442")]
265     NotSeekable,
266     /// Filesystem quota was exceeded.
267     #[unstable(feature = "io_error_more", issue = "86442")]
268     FilesystemQuotaExceeded,
269     /// File larger than allowed or supported.
270     ///
271     /// This might arise from a hard limit of the underlying filesystem or file access API, or from
272     /// an administratively imposed resource limitation.  Simple disk full, and out of quota, have
273     /// their own errors.
274     #[unstable(feature = "io_error_more", issue = "86442")]
275     FileTooLarge,
276     /// Resource is busy.
277     #[unstable(feature = "io_error_more", issue = "86442")]
278     ResourceBusy,
279     /// Executable file is busy.
280     ///
281     /// An attempt was made to write to a file which is also in use as a running program.  (Not all
282     /// operating systems detect this situation.)
283     #[unstable(feature = "io_error_more", issue = "86442")]
284     ExecutableFileBusy,
285     /// Deadlock (avoided).
286     ///
287     /// A file locking operation would result in deadlock.  This situation is typically detected, if
288     /// at all, on a best-effort basis.
289     #[unstable(feature = "io_error_more", issue = "86442")]
290     Deadlock,
291     /// Cross-device or cross-filesystem (hard) link or rename.
292     #[unstable(feature = "io_error_more", issue = "86442")]
293     CrossesDevices,
294     /// Too many (hard) links to the same filesystem object.
295     ///
296     /// The filesystem does not support making so many hardlinks to the same file.
297     #[unstable(feature = "io_error_more", issue = "86442")]
298     TooManyLinks,
299     /// A filename was invalid.
300     ///
301     /// This error can also cause if it exceeded the filename length limit.
302     #[unstable(feature = "io_error_more", issue = "86442")]
303     InvalidFilename,
304     /// Program argument list too long.
305     ///
306     /// When trying to run an external program, a system or process limit on the size of the
307     /// arguments would have been exceeded.
308     #[unstable(feature = "io_error_more", issue = "86442")]
309     ArgumentListTooLong,
310     /// This operation was interrupted.
311     ///
312     /// Interrupted operations can typically be retried.
313     #[stable(feature = "rust1", since = "1.0.0")]
314     Interrupted,
315
316     /// This operation is unsupported on this platform.
317     ///
318     /// This means that the operation can never succeed.
319     #[stable(feature = "unsupported_error", since = "1.53.0")]
320     Unsupported,
321
322     // ErrorKinds which are primarily categorisations for OS error
323     // codes should be added above.
324     //
325     /// An error returned when an operation could not be completed because an
326     /// "end of file" was reached prematurely.
327     ///
328     /// This typically means that an operation could only succeed if it read a
329     /// particular number of bytes but only a smaller number of bytes could be
330     /// read.
331     #[stable(feature = "read_exact", since = "1.6.0")]
332     UnexpectedEof,
333
334     /// An operation could not be completed, because it failed
335     /// to allocate enough memory.
336     #[stable(feature = "out_of_memory_error", since = "1.54.0")]
337     OutOfMemory,
338
339     // "Unusual" error kinds which do not correspond simply to (sets
340     // of) OS error codes, should be added just above this comment.
341     // `Other` and `Uncategorised` should remain at the end:
342     //
343     /// A custom error that does not fall under any other I/O error kind.
344     ///
345     /// This can be used to construct your own [`Error`]s that do not match any
346     /// [`ErrorKind`].
347     ///
348     /// This [`ErrorKind`] is not used by the standard library.
349     ///
350     /// Errors from the standard library that do not fall under any of the I/O
351     /// error kinds cannot be `match`ed on, and will only match a wildcard (`_`) pattern.
352     /// New [`ErrorKind`]s might be added in the future for some of those.
353     #[stable(feature = "rust1", since = "1.0.0")]
354     Other,
355
356     /// Any I/O error from the standard library that's not part of this list.
357     ///
358     /// Errors that are `Uncategorized` now may move to a different or a new
359     /// [`ErrorKind`] variant in the future. It is not recommended to match
360     /// an error against `Uncategorized`; use a wildcard match (`_`) instead.
361     #[unstable(feature = "io_error_uncategorized", issue = "none")]
362     #[doc(hidden)]
363     Uncategorized,
364 }
365
366 impl ErrorKind {
367     pub(crate) fn as_str(&self) -> &'static str {
368         use ErrorKind::*;
369         // Strictly alphabetical, please.  (Sadly rustfmt cannot do this yet.)
370         match *self {
371             AddrInUse => "address in use",
372             AddrNotAvailable => "address not available",
373             AlreadyExists => "entity already exists",
374             ArgumentListTooLong => "argument list too long",
375             BrokenPipe => "broken pipe",
376             ConnectionAborted => "connection aborted",
377             ConnectionRefused => "connection refused",
378             ConnectionReset => "connection reset",
379             CrossesDevices => "cross-device link or rename",
380             Deadlock => "deadlock",
381             DirectoryNotEmpty => "directory not empty",
382             ExecutableFileBusy => "executable file busy",
383             FileTooLarge => "file too large",
384             FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)",
385             FilesystemQuotaExceeded => "filesystem quota exceeded",
386             HostUnreachable => "host unreachable",
387             Interrupted => "operation interrupted",
388             InvalidData => "invalid data",
389             InvalidFilename => "invalid filename",
390             InvalidInput => "invalid input parameter",
391             IsADirectory => "is a directory",
392             NetworkDown => "network down",
393             NetworkUnreachable => "network unreachable",
394             NotADirectory => "not a directory",
395             NotConnected => "not connected",
396             NotFound => "entity not found",
397             NotSeekable => "seek on unseekable file",
398             Other => "other error",
399             OutOfMemory => "out of memory",
400             PermissionDenied => "permission denied",
401             ReadOnlyFilesystem => "read-only filesystem or storage medium",
402             ResourceBusy => "resource busy",
403             StaleNetworkFileHandle => "stale network file handle",
404             StorageFull => "no storage space",
405             TimedOut => "timed out",
406             TooManyLinks => "too many links",
407             Uncategorized => "uncategorized error",
408             UnexpectedEof => "unexpected end of file",
409             Unsupported => "unsupported",
410             WouldBlock => "operation would block",
411             WriteZero => "write zero",
412         }
413     }
414 }
415
416 #[stable(feature = "io_errorkind_display", since = "1.60.0")]
417 impl fmt::Display for ErrorKind {
418     /// Shows a human-readable description of the `ErrorKind`.
419     ///
420     /// This is similar to `impl Display for Error`, but doesn't require first converting to Error.
421     ///
422     /// # Examples
423     /// ```
424     /// use std::io::ErrorKind;
425     /// assert_eq!("entity not found", ErrorKind::NotFound.to_string());
426     /// ```
427     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
428         fmt.write_str(self.as_str())
429     }
430 }
431
432 /// Intended for use for errors not exposed to the user, where allocating onto
433 /// the heap (for normal construction via Error::new) is too costly.
434 #[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
435 impl From<ErrorKind> for Error {
436     /// Converts an [`ErrorKind`] into an [`Error`].
437     ///
438     /// This conversion creates a new error with a simple representation of error kind.
439     ///
440     /// # Examples
441     ///
442     /// ```
443     /// use std::io::{Error, ErrorKind};
444     ///
445     /// let not_found = ErrorKind::NotFound;
446     /// let error = Error::from(not_found);
447     /// assert_eq!("entity not found", format!("{}", error));
448     /// ```
449     #[inline]
450     fn from(kind: ErrorKind) -> Error {
451         Error { repr: Repr::new_simple(kind) }
452     }
453 }
454
455 impl Error {
456     /// Creates a new I/O error from a known kind of error as well as an
457     /// arbitrary error payload.
458     ///
459     /// This function is used to generically create I/O errors which do not
460     /// originate from the OS itself. The `error` argument is an arbitrary
461     /// payload which will be contained in this [`Error`].
462     ///
463     /// If no extra payload is required, use the `From` conversion from
464     /// `ErrorKind`.
465     ///
466     /// # Examples
467     ///
468     /// ```
469     /// use std::io::{Error, ErrorKind};
470     ///
471     /// // errors can be created from strings
472     /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
473     ///
474     /// // errors can also be created from other errors
475     /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
476     ///
477     /// // creating an error without payload
478     /// let eof_error = Error::from(ErrorKind::UnexpectedEof);
479     /// ```
480     #[stable(feature = "rust1", since = "1.0.0")]
481     pub fn new<E>(kind: ErrorKind, error: E) -> Error
482     where
483         E: Into<Box<dyn error::Error + Send + Sync>>,
484     {
485         Self::_new(kind, error.into())
486     }
487
488     /// Creates a new I/O error from an arbitrary error payload.
489     ///
490     /// This function is used to generically create I/O errors which do not
491     /// originate from the OS itself. It is a shortcut for [`Error::new`]
492     /// with [`ErrorKind::Other`].
493     ///
494     /// # Examples
495     ///
496     /// ```
497     /// #![feature(io_error_other)]
498     ///
499     /// use std::io::Error;
500     ///
501     /// // errors can be created from strings
502     /// let custom_error = Error::other("oh no!");
503     ///
504     /// // errors can also be created from other errors
505     /// let custom_error2 = Error::other(custom_error);
506     /// ```
507     #[unstable(feature = "io_error_other", issue = "91946")]
508     pub fn other<E>(error: E) -> Error
509     where
510         E: Into<Box<dyn error::Error + Send + Sync>>,
511     {
512         Self::_new(ErrorKind::Other, error.into())
513     }
514
515     fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
516         Error { repr: Repr::new_custom(Box::new(Custom { kind, error })) }
517     }
518
519     /// Creates a new I/O error from a known kind of error as well as a constant
520     /// message.
521     ///
522     /// This function does not allocate.
523     ///
524     /// You should not use this directly, and instead use the `const_io_error!`
525     /// macro: `io::const_io_error!(ErrorKind::Something, "some_message")`.
526     ///
527     /// This function should maybe change to `from_static_message<const MSG: &'static
528     /// str>(kind: ErrorKind)` in the future, when const generics allow that.
529     #[inline]
530     pub(crate) const fn from_static_message(msg: &'static SimpleMessage) -> Error {
531         Self { repr: Repr::new_simple_message(msg) }
532     }
533
534     /// Returns an error representing the last OS error which occurred.
535     ///
536     /// This function reads the value of `errno` for the target platform (e.g.
537     /// `GetLastError` on Windows) and will return a corresponding instance of
538     /// [`Error`] for the error code.
539     ///
540     /// This should be called immediately after a call to a platform function,
541     /// otherwise the state of the error value is indeterminate. In particular,
542     /// other standard library functions may call platform functions that may
543     /// (or may not) reset the error value even if they succeed.
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// use std::io::Error;
549     ///
550     /// let os_error = Error::last_os_error();
551     /// println!("last OS error: {:?}", os_error);
552     /// ```
553     #[stable(feature = "rust1", since = "1.0.0")]
554     #[must_use]
555     #[inline]
556     pub fn last_os_error() -> Error {
557         Error::from_raw_os_error(sys::os::errno() as i32)
558     }
559
560     /// Creates a new instance of an [`Error`] from a particular OS error code.
561     ///
562     /// # Examples
563     ///
564     /// On Linux:
565     ///
566     /// ```
567     /// # if cfg!(target_os = "linux") {
568     /// use std::io;
569     ///
570     /// let error = io::Error::from_raw_os_error(22);
571     /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
572     /// # }
573     /// ```
574     ///
575     /// On Windows:
576     ///
577     /// ```
578     /// # if cfg!(windows) {
579     /// use std::io;
580     ///
581     /// let error = io::Error::from_raw_os_error(10022);
582     /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
583     /// # }
584     /// ```
585     #[stable(feature = "rust1", since = "1.0.0")]
586     #[must_use]
587     #[inline]
588     pub fn from_raw_os_error(code: i32) -> Error {
589         Error { repr: Repr::new_os(code) }
590     }
591
592     /// Returns the OS error that this error represents (if any).
593     ///
594     /// If this [`Error`] was constructed via [`last_os_error`] or
595     /// [`from_raw_os_error`], then this function will return [`Some`], otherwise
596     /// it will return [`None`].
597     ///
598     /// [`last_os_error`]: Error::last_os_error
599     /// [`from_raw_os_error`]: Error::from_raw_os_error
600     ///
601     /// # Examples
602     ///
603     /// ```
604     /// use std::io::{Error, ErrorKind};
605     ///
606     /// fn print_os_error(err: &Error) {
607     ///     if let Some(raw_os_err) = err.raw_os_error() {
608     ///         println!("raw OS error: {:?}", raw_os_err);
609     ///     } else {
610     ///         println!("Not an OS error");
611     ///     }
612     /// }
613     ///
614     /// fn main() {
615     ///     // Will print "raw OS error: ...".
616     ///     print_os_error(&Error::last_os_error());
617     ///     // Will print "Not an OS error".
618     ///     print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
619     /// }
620     /// ```
621     #[stable(feature = "rust1", since = "1.0.0")]
622     #[must_use]
623     #[inline]
624     pub fn raw_os_error(&self) -> Option<i32> {
625         match self.repr.data() {
626             ErrorData::Os(i) => Some(i),
627             ErrorData::Custom(..) => None,
628             ErrorData::Simple(..) => None,
629             ErrorData::SimpleMessage(..) => None,
630         }
631     }
632
633     /// Returns a reference to the inner error wrapped by this error (if any).
634     ///
635     /// If this [`Error`] was constructed via [`new`] then this function will
636     /// return [`Some`], otherwise it will return [`None`].
637     ///
638     /// [`new`]: Error::new
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// use std::io::{Error, ErrorKind};
644     ///
645     /// fn print_error(err: &Error) {
646     ///     if let Some(inner_err) = err.get_ref() {
647     ///         println!("Inner error: {:?}", inner_err);
648     ///     } else {
649     ///         println!("No inner error");
650     ///     }
651     /// }
652     ///
653     /// fn main() {
654     ///     // Will print "No inner error".
655     ///     print_error(&Error::last_os_error());
656     ///     // Will print "Inner error: ...".
657     ///     print_error(&Error::new(ErrorKind::Other, "oh no!"));
658     /// }
659     /// ```
660     #[stable(feature = "io_error_inner", since = "1.3.0")]
661     #[must_use]
662     #[inline]
663     pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
664         match self.repr.data() {
665             ErrorData::Os(..) => None,
666             ErrorData::Simple(..) => None,
667             ErrorData::SimpleMessage(..) => None,
668             ErrorData::Custom(c) => Some(&*c.error),
669         }
670     }
671
672     /// Returns a mutable reference to the inner error wrapped by this error
673     /// (if any).
674     ///
675     /// If this [`Error`] was constructed via [`new`] then this function will
676     /// return [`Some`], otherwise it will return [`None`].
677     ///
678     /// [`new`]: Error::new
679     ///
680     /// # Examples
681     ///
682     /// ```
683     /// use std::io::{Error, ErrorKind};
684     /// use std::{error, fmt};
685     /// use std::fmt::Display;
686     ///
687     /// #[derive(Debug)]
688     /// struct MyError {
689     ///     v: String,
690     /// }
691     ///
692     /// impl MyError {
693     ///     fn new() -> MyError {
694     ///         MyError {
695     ///             v: "oh no!".to_string()
696     ///         }
697     ///     }
698     ///
699     ///     fn change_message(&mut self, new_message: &str) {
700     ///         self.v = new_message.to_string();
701     ///     }
702     /// }
703     ///
704     /// impl error::Error for MyError {}
705     ///
706     /// impl Display for MyError {
707     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
708     ///         write!(f, "MyError: {}", &self.v)
709     ///     }
710     /// }
711     ///
712     /// fn change_error(mut err: Error) -> Error {
713     ///     if let Some(inner_err) = err.get_mut() {
714     ///         inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
715     ///     }
716     ///     err
717     /// }
718     ///
719     /// fn print_error(err: &Error) {
720     ///     if let Some(inner_err) = err.get_ref() {
721     ///         println!("Inner error: {}", inner_err);
722     ///     } else {
723     ///         println!("No inner error");
724     ///     }
725     /// }
726     ///
727     /// fn main() {
728     ///     // Will print "No inner error".
729     ///     print_error(&change_error(Error::last_os_error()));
730     ///     // Will print "Inner error: ...".
731     ///     print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
732     /// }
733     /// ```
734     #[stable(feature = "io_error_inner", since = "1.3.0")]
735     #[must_use]
736     #[inline]
737     pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
738         match self.repr.data_mut() {
739             ErrorData::Os(..) => None,
740             ErrorData::Simple(..) => None,
741             ErrorData::SimpleMessage(..) => None,
742             ErrorData::Custom(c) => Some(&mut *c.error),
743         }
744     }
745
746     /// Consumes the `Error`, returning its inner error (if any).
747     ///
748     /// If this [`Error`] was constructed via [`new`] then this function will
749     /// return [`Some`], otherwise it will return [`None`].
750     ///
751     /// [`new`]: Error::new
752     ///
753     /// # Examples
754     ///
755     /// ```
756     /// use std::io::{Error, ErrorKind};
757     ///
758     /// fn print_error(err: Error) {
759     ///     if let Some(inner_err) = err.into_inner() {
760     ///         println!("Inner error: {}", inner_err);
761     ///     } else {
762     ///         println!("No inner error");
763     ///     }
764     /// }
765     ///
766     /// fn main() {
767     ///     // Will print "No inner error".
768     ///     print_error(Error::last_os_error());
769     ///     // Will print "Inner error: ...".
770     ///     print_error(Error::new(ErrorKind::Other, "oh no!"));
771     /// }
772     /// ```
773     #[stable(feature = "io_error_inner", since = "1.3.0")]
774     #[must_use = "`self` will be dropped if the result is not used"]
775     #[inline]
776     pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
777         match self.repr.into_data() {
778             ErrorData::Os(..) => None,
779             ErrorData::Simple(..) => None,
780             ErrorData::SimpleMessage(..) => None,
781             ErrorData::Custom(c) => Some(c.error),
782         }
783     }
784
785     /// Returns the corresponding [`ErrorKind`] for this error.
786     ///
787     /// # Examples
788     ///
789     /// ```
790     /// use std::io::{Error, ErrorKind};
791     ///
792     /// fn print_error(err: Error) {
793     ///     println!("{:?}", err.kind());
794     /// }
795     ///
796     /// fn main() {
797     ///     // Will print "Uncategorized".
798     ///     print_error(Error::last_os_error());
799     ///     // Will print "AddrInUse".
800     ///     print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
801     /// }
802     /// ```
803     #[stable(feature = "rust1", since = "1.0.0")]
804     #[must_use]
805     #[inline]
806     pub fn kind(&self) -> ErrorKind {
807         match self.repr.data() {
808             ErrorData::Os(code) => sys::decode_error_kind(code),
809             ErrorData::Custom(c) => c.kind,
810             ErrorData::Simple(kind) => kind,
811             ErrorData::SimpleMessage(m) => m.kind,
812         }
813     }
814 }
815
816 impl fmt::Debug for Repr {
817     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
818         match self.data() {
819             ErrorData::Os(code) => fmt
820                 .debug_struct("Os")
821                 .field("code", &code)
822                 .field("kind", &sys::decode_error_kind(code))
823                 .field("message", &sys::os::error_string(code))
824                 .finish(),
825             ErrorData::Custom(c) => fmt::Debug::fmt(&c, fmt),
826             ErrorData::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
827             ErrorData::SimpleMessage(msg) => fmt
828                 .debug_struct("Error")
829                 .field("kind", &msg.kind)
830                 .field("message", &msg.message)
831                 .finish(),
832         }
833     }
834 }
835
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl fmt::Display for Error {
838     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
839         match self.repr.data() {
840             ErrorData::Os(code) => {
841                 let detail = sys::os::error_string(code);
842                 write!(fmt, "{} (os error {})", detail, code)
843             }
844             ErrorData::Custom(ref c) => c.error.fmt(fmt),
845             ErrorData::Simple(kind) => write!(fmt, "{}", kind.as_str()),
846             ErrorData::SimpleMessage(msg) => msg.message.fmt(fmt),
847         }
848     }
849 }
850
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl error::Error for Error {
853     #[allow(deprecated, deprecated_in_future)]
854     fn description(&self) -> &str {
855         match self.repr.data() {
856             ErrorData::Os(..) | ErrorData::Simple(..) => self.kind().as_str(),
857             ErrorData::SimpleMessage(msg) => msg.message,
858             ErrorData::Custom(c) => c.error.description(),
859         }
860     }
861
862     #[allow(deprecated)]
863     fn cause(&self) -> Option<&dyn error::Error> {
864         match self.repr.data() {
865             ErrorData::Os(..) => None,
866             ErrorData::Simple(..) => None,
867             ErrorData::SimpleMessage(..) => None,
868             ErrorData::Custom(c) => c.error.cause(),
869         }
870     }
871
872     fn source(&self) -> Option<&(dyn error::Error + 'static)> {
873         match self.repr.data() {
874             ErrorData::Os(..) => None,
875             ErrorData::Simple(..) => None,
876             ErrorData::SimpleMessage(..) => None,
877             ErrorData::Custom(c) => c.error.source(),
878         }
879     }
880 }
881
882 fn _assert_error_is_sync_send() {
883     fn _is_sync_send<T: Sync + Send>() {}
884     _is_sync_send::<Error>();
885 }