Skip to main content

core/io/
error.rs

1#![unstable(feature = "core_io", issue = "154046")]
2
3use crate::fmt;
4
5/// The type of raw OS error codes.
6///
7/// This is an [`i32`] on all currently supported platforms, but platforms
8/// added in the future (such as UEFI) may use a different primitive type like
9/// [`usize`]. Use `as` or [`into`] conversions where applicable to ensure maximum
10/// portability.
11///
12/// [`into`]: Into::into
13#[unstable(feature = "raw_os_error_ty", issue = "107792")]
14pub type RawOsError = cfg_select! {
15    target_os = "uefi" => usize,
16    _ => i32,
17};
18
19/// A list specifying general categories of I/O error.
20///
21/// This list is intended to grow over time and it is not recommended to
22/// exhaustively match against it.
23///
24/// It is used with the [`io::Error`][error] type.
25///
26/// [error]: ../../std/io/struct.Error.html
27///
28/// # Handling errors and matching on `ErrorKind`
29///
30/// In application code, use `match` for the `ErrorKind` values you are
31/// expecting; use `_` to match "all other errors".
32///
33/// In comprehensive and thorough tests that want to verify that a test doesn't
34/// return any known incorrect error kind, you may want to cut-and-paste the
35/// current full list of errors from here into your test code, and then match
36/// `_` as the correct case. This seems counterintuitive, but it will make your
37/// tests more robust. In particular, if you want to verify that your code does
38/// produce an unrecognized error kind, the robust solution is to check for all
39/// the recognized error kinds and fail in those cases.
40#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
41#[stable(feature = "rust1", since = "1.0.0")]
42#[cfg_attr(not(test), rustc_diagnostic_item = "io_errorkind")]
43#[allow(deprecated)]
44#[non_exhaustive]
45pub enum ErrorKind {
46    /// An entity was not found, often a file.
47    #[stable(feature = "rust1", since = "1.0.0")]
48    NotFound,
49    /// The operation lacked the necessary privileges to complete.
50    #[stable(feature = "rust1", since = "1.0.0")]
51    PermissionDenied,
52    /// The connection was refused by the remote server.
53    #[stable(feature = "rust1", since = "1.0.0")]
54    ConnectionRefused,
55    /// The connection was reset by the remote server.
56    #[stable(feature = "rust1", since = "1.0.0")]
57    ConnectionReset,
58    /// The remote host is not reachable.
59    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
60    HostUnreachable,
61    /// The network containing the remote host is not reachable.
62    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
63    NetworkUnreachable,
64    /// The connection was aborted (terminated) by the remote server.
65    #[stable(feature = "rust1", since = "1.0.0")]
66    ConnectionAborted,
67    /// The network operation failed because it was not connected yet.
68    #[stable(feature = "rust1", since = "1.0.0")]
69    NotConnected,
70    /// A socket address could not be bound because the address is already in
71    /// use elsewhere.
72    #[stable(feature = "rust1", since = "1.0.0")]
73    AddrInUse,
74    /// A nonexistent interface was requested or the requested address was not
75    /// local.
76    #[stable(feature = "rust1", since = "1.0.0")]
77    AddrNotAvailable,
78    /// The system's networking is down.
79    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
80    NetworkDown,
81    /// The operation failed because a pipe was closed.
82    #[stable(feature = "rust1", since = "1.0.0")]
83    BrokenPipe,
84    /// An entity already exists, often a file.
85    #[stable(feature = "rust1", since = "1.0.0")]
86    AlreadyExists,
87    /// The operation needs to block to complete, but the blocking operation was
88    /// requested to not occur.
89    #[stable(feature = "rust1", since = "1.0.0")]
90    WouldBlock,
91    /// A filesystem object is, unexpectedly, not a directory.
92    ///
93    /// For example, a filesystem path was specified where one of the intermediate directory
94    /// components was, in fact, a plain file.
95    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
96    NotADirectory,
97    /// The filesystem object is, unexpectedly, a directory.
98    ///
99    /// A directory was specified when a non-directory was expected.
100    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
101    IsADirectory,
102    /// A non-empty directory was specified where an empty directory was expected.
103    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
104    DirectoryNotEmpty,
105    /// The filesystem or storage medium is read-only, but a write operation was attempted.
106    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
107    ReadOnlyFilesystem,
108    /// Loop in the filesystem or IO subsystem; often, too many levels of symbolic links.
109    ///
110    /// There was a loop (or excessively long chain) resolving a filesystem object
111    /// or file IO object.
112    ///
113    /// On Unix this is usually the result of a symbolic link loop; or, of exceeding the
114    /// system-specific limit on the depth of symlink traversal.
115    #[unstable(feature = "io_error_more", issue = "86442")]
116    FilesystemLoop,
117    /// Stale network file handle.
118    ///
119    /// With some network filesystems, notably NFS, an open file (or directory) can be invalidated
120    /// by problems with the network or server.
121    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
122    StaleNetworkFileHandle,
123    /// A parameter was incorrect.
124    #[stable(feature = "rust1", since = "1.0.0")]
125    InvalidInput,
126    /// Data not valid for the operation were encountered.
127    ///
128    /// Unlike [`InvalidInput`], this typically means that the operation
129    /// parameters were valid, however the error was caused by malformed
130    /// input data.
131    ///
132    /// For example, a function that reads a file into a string will error with
133    /// `InvalidData` if the file's contents are not valid UTF-8.
134    ///
135    /// [`InvalidInput`]: ErrorKind::InvalidInput
136    #[stable(feature = "io_invalid_data", since = "1.2.0")]
137    InvalidData,
138    /// The I/O operation's timeout expired, causing it to be canceled.
139    #[stable(feature = "rust1", since = "1.0.0")]
140    TimedOut,
141    /// An error returned when an operation could not be completed because a
142    /// call to [`write`][write] returned [`Ok(0)`].
143    ///
144    /// This typically means that an operation could only succeed if it wrote a
145    /// particular number of bytes but only a smaller number of bytes could be
146    /// written.
147    ///
148    /// [write]: ../../std/io/trait.Write.html#tymethod.write
149    /// [`Ok(0)`]: Ok
150    #[stable(feature = "rust1", since = "1.0.0")]
151    WriteZero,
152    /// The underlying storage (typically, a filesystem) is full.
153    ///
154    /// This does not include out of quota errors.
155    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
156    StorageFull,
157    /// Seek on unseekable file.
158    ///
159    /// Seeking was attempted on an open file handle which is not suitable for seeking - for
160    /// example, on Unix, a named pipe opened with `File::open`.
161    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
162    NotSeekable,
163    /// Filesystem quota or some other kind of quota was exceeded.
164    #[stable(feature = "io_error_quota_exceeded", since = "1.85.0")]
165    QuotaExceeded,
166    /// File larger than allowed or supported.
167    ///
168    /// This might arise from a hard limit of the underlying filesystem or file access API, or from
169    /// an administratively imposed resource limitation.  Simple disk full, and out of quota, have
170    /// their own errors.
171    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
172    FileTooLarge,
173    /// Resource is busy.
174    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
175    ResourceBusy,
176    /// Executable file is busy.
177    ///
178    /// An attempt was made to write to a file which is also in use as a running program.  (Not all
179    /// operating systems detect this situation.)
180    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
181    ExecutableFileBusy,
182    /// Deadlock (avoided).
183    ///
184    /// A file locking operation would result in deadlock.  This situation is typically detected, if
185    /// at all, on a best-effort basis.
186    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
187    Deadlock,
188    /// Cross-device or cross-filesystem (hard) link or rename.
189    #[stable(feature = "io_error_crosses_devices", since = "1.85.0")]
190    CrossesDevices,
191    /// Too many (hard) links to the same filesystem object.
192    ///
193    /// The filesystem does not support making so many hardlinks to the same file.
194    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
195    TooManyLinks,
196    /// A filename was invalid.
197    ///
198    /// This error can also occur if a length limit for a name was exceeded.
199    #[stable(feature = "io_error_invalid_filename", since = "1.87.0")]
200    InvalidFilename,
201    /// Program argument list too long.
202    ///
203    /// When trying to run an external program, a system or process limit on the size of the
204    /// arguments would have been exceeded.
205    #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
206    ArgumentListTooLong,
207    /// This operation was interrupted.
208    ///
209    /// Interrupted operations can typically be retried.
210    #[stable(feature = "rust1", since = "1.0.0")]
211    Interrupted,
212
213    /// This operation is unsupported on this platform.
214    ///
215    /// This means that the operation can never succeed.
216    #[stable(feature = "unsupported_error", since = "1.53.0")]
217    Unsupported,
218
219    // ErrorKinds which are primarily categorisations for OS error
220    // codes should be added above.
221    //
222    /// An error returned when an operation could not be completed because an
223    /// "end of file" was reached prematurely.
224    ///
225    /// This typically means that an operation could only succeed if it read a
226    /// particular number of bytes but only a smaller number of bytes could be
227    /// read.
228    #[stable(feature = "read_exact", since = "1.6.0")]
229    UnexpectedEof,
230
231    /// An operation could not be completed, because it failed
232    /// to allocate enough memory.
233    #[stable(feature = "out_of_memory_error", since = "1.54.0")]
234    OutOfMemory,
235
236    /// The operation was partially successful and needs to be checked
237    /// later on due to not blocking.
238    #[unstable(feature = "io_error_inprogress", issue = "130840")]
239    InProgress,
240
241    // "Unusual" error kinds which do not correspond simply to (sets
242    // of) OS error codes, should be added just above this comment.
243    // `Other` and `Uncategorized` should remain at the end:
244    //
245    /// A custom error that does not fall under any other I/O error kind.
246    ///
247    /// This can be used to construct your own [`Error`][error]s that do not match any
248    /// [`ErrorKind`].
249    ///
250    /// This [`ErrorKind`] is not used by the standard library.
251    ///
252    /// Errors from the standard library that do not fall under any of the I/O
253    /// error kinds cannot be `match`ed on, and will only match a wildcard (`_`) pattern.
254    /// New [`ErrorKind`]s might be added in the future for some of those.
255    ///
256    /// [error]: ../../std/io/struct.Error.html
257    #[stable(feature = "rust1", since = "1.0.0")]
258    Other,
259
260    /// Any I/O error from the standard library that's not part of this list.
261    ///
262    /// Errors that are `Uncategorized` now may move to a different or a new
263    /// [`ErrorKind`] variant in the future. It is not recommended to match
264    /// an error against `Uncategorized`; use a wildcard match (`_`) instead.
265    #[unstable(feature = "io_error_uncategorized", issue = "none")]
266    #[doc(hidden)]
267    Uncategorized,
268}
269
270impl ErrorKind {
271    pub(crate) const fn as_str(&self) -> &'static str {
272        use ErrorKind::*;
273        match *self {
274            // tidy-alphabetical-start
275            AddrInUse => "address in use",
276            AddrNotAvailable => "address not available",
277            AlreadyExists => "entity already exists",
278            ArgumentListTooLong => "argument list too long",
279            BrokenPipe => "broken pipe",
280            ConnectionAborted => "connection aborted",
281            ConnectionRefused => "connection refused",
282            ConnectionReset => "connection reset",
283            CrossesDevices => "cross-device link or rename",
284            Deadlock => "deadlock",
285            DirectoryNotEmpty => "directory not empty",
286            ExecutableFileBusy => "executable file busy",
287            FileTooLarge => "file too large",
288            FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)",
289            HostUnreachable => "host unreachable",
290            InProgress => "in progress",
291            Interrupted => "operation interrupted",
292            InvalidData => "invalid data",
293            InvalidFilename => "invalid filename",
294            InvalidInput => "invalid input parameter",
295            IsADirectory => "is a directory",
296            NetworkDown => "network down",
297            NetworkUnreachable => "network unreachable",
298            NotADirectory => "not a directory",
299            NotConnected => "not connected",
300            NotFound => "entity not found",
301            NotSeekable => "seek on unseekable file",
302            Other => "other error",
303            OutOfMemory => "out of memory",
304            PermissionDenied => "permission denied",
305            QuotaExceeded => "quota exceeded",
306            ReadOnlyFilesystem => "read-only filesystem or storage medium",
307            ResourceBusy => "resource busy",
308            StaleNetworkFileHandle => "stale network file handle",
309            StorageFull => "no storage space",
310            TimedOut => "timed out",
311            TooManyLinks => "too many links",
312            Uncategorized => "uncategorized error",
313            UnexpectedEof => "unexpected end of file",
314            Unsupported => "unsupported",
315            WouldBlock => "operation would block",
316            WriteZero => "write zero",
317            // tidy-alphabetical-end
318        }
319    }
320
321    // This compiles to the same code as the check+transmute, but doesn't require
322    // unsafe, or to hard-code max ErrorKind or its size in a way the compiler
323    // couldn't verify.
324    #[inline]
325    #[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
326    #[doc(hidden)]
327    pub const fn from_prim(ek: u32) -> Option<Self> {
328        macro_rules! from_prim {
329            ($prim:expr => $Enum:ident { $($Variant:ident),* $(,)? }) => {{
330                // Force a compile error if the list gets out of date.
331                const _: fn(e: $Enum) = |e: $Enum| match e {
332                    $($Enum::$Variant => (),)*
333                };
334                match $prim {
335                    $(v if v == ($Enum::$Variant as _) => Some($Enum::$Variant),)*
336                    _ => None,
337                }
338            }}
339        }
340        from_prim!(ek => ErrorKind {
341            NotFound,
342            PermissionDenied,
343            ConnectionRefused,
344            ConnectionReset,
345            HostUnreachable,
346            NetworkUnreachable,
347            ConnectionAborted,
348            NotConnected,
349            AddrInUse,
350            AddrNotAvailable,
351            NetworkDown,
352            BrokenPipe,
353            AlreadyExists,
354            WouldBlock,
355            NotADirectory,
356            IsADirectory,
357            DirectoryNotEmpty,
358            ReadOnlyFilesystem,
359            FilesystemLoop,
360            StaleNetworkFileHandle,
361            InvalidInput,
362            InvalidData,
363            TimedOut,
364            WriteZero,
365            StorageFull,
366            NotSeekable,
367            QuotaExceeded,
368            FileTooLarge,
369            ResourceBusy,
370            ExecutableFileBusy,
371            Deadlock,
372            CrossesDevices,
373            TooManyLinks,
374            InvalidFilename,
375            ArgumentListTooLong,
376            Interrupted,
377            Other,
378            UnexpectedEof,
379            Unsupported,
380            OutOfMemory,
381            InProgress,
382            Uncategorized,
383        })
384    }
385}
386
387#[stable(feature = "io_errorkind_display", since = "1.60.0")]
388impl fmt::Display for ErrorKind {
389    /// Shows a human-readable description of the [`ErrorKind`].
390    ///
391    /// This is similar to `impl Display for Error`, but doesn't require first converting to Error.
392    ///
393    /// # Examples
394    /// ```
395    /// use core::io::ErrorKind;
396    /// assert_eq!("entity not found", ErrorKind::NotFound.to_string());
397    /// ```
398    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
399        fmt.write_str(self.as_str())
400    }
401}