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