std/io/
error.rs

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