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