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