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 /// The process or the whole system has reached its limit on the number of
242 /// open files or sockets.
243 #[unstable(feature = "io_error_too_many_open_files", issue = "158319")]
244 TooManyOpenFiles,
245
246 // "Unusual" error kinds which do not correspond simply to (sets
247 // of) OS error codes, should be added just above this comment.
248 // `Other` and `Uncategorized` should remain at the end:
249 //
250 /// A custom error that does not fall under any other I/O error kind.
251 ///
252 /// This can be used to construct your own [`Error`][error]s that do not match any
253 /// [`ErrorKind`].
254 ///
255 /// This [`ErrorKind`] is not used by the standard library.
256 ///
257 /// Errors from the standard library that do not fall under any of the I/O
258 /// error kinds cannot be `match`ed on, and will only match a wildcard (`_`) pattern.
259 /// New [`ErrorKind`]s might be added in the future for some of those.
260 ///
261 /// [error]: ../../std/io/struct.Error.html
262 #[stable(feature = "rust1", since = "1.0.0")]
263 Other,
264
265 /// Any I/O error from the standard library that's not part of this list.
266 ///
267 /// Errors that are `Uncategorized` now may move to a different or a new
268 /// [`ErrorKind`] variant in the future. It is not recommended to match
269 /// an error against `Uncategorized`; use a wildcard match (`_`) instead.
270 #[unstable(feature = "io_error_uncategorized", issue = "none")]
271 #[doc(hidden)]
272 Uncategorized,
273}
274
275impl ErrorKind {
276 pub(crate) const fn as_str(&self) -> &'static str {
277 use ErrorKind::*;
278 match *self {
279 // tidy-alphabetical-start
280 AddrInUse => "address in use",
281 AddrNotAvailable => "address not available",
282 AlreadyExists => "entity already exists",
283 ArgumentListTooLong => "argument list too long",
284 BrokenPipe => "broken pipe",
285 ConnectionAborted => "connection aborted",
286 ConnectionRefused => "connection refused",
287 ConnectionReset => "connection reset",
288 CrossesDevices => "cross-device link or rename",
289 Deadlock => "deadlock",
290 DirectoryNotEmpty => "directory not empty",
291 ExecutableFileBusy => "executable file busy",
292 FileTooLarge => "file too large",
293 FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)",
294 HostUnreachable => "host unreachable",
295 InProgress => "in progress",
296 Interrupted => "operation interrupted",
297 InvalidData => "invalid data",
298 InvalidFilename => "invalid filename",
299 InvalidInput => "invalid input parameter",
300 IsADirectory => "is a directory",
301 NetworkDown => "network down",
302 NetworkUnreachable => "network unreachable",
303 NotADirectory => "not a directory",
304 NotConnected => "not connected",
305 NotFound => "entity not found",
306 NotSeekable => "seek on unseekable file",
307 Other => "other error",
308 OutOfMemory => "out of memory",
309 PermissionDenied => "permission denied",
310 QuotaExceeded => "quota exceeded",
311 ReadOnlyFilesystem => "read-only filesystem or storage medium",
312 ResourceBusy => "resource busy",
313 StaleNetworkFileHandle => "stale network file handle",
314 StorageFull => "no storage space",
315 TimedOut => "timed out",
316 TooManyLinks => "too many links",
317 TooManyOpenFiles => "too many open files",
318 Uncategorized => "uncategorized error",
319 UnexpectedEof => "unexpected end of file",
320 Unsupported => "unsupported",
321 WouldBlock => "operation would block",
322 WriteZero => "write zero",
323 // tidy-alphabetical-end
324 }
325 }
326
327 // This compiles to the same code as the check+transmute, but doesn't require
328 // unsafe, or to hard-code max ErrorKind or its size in a way the compiler
329 // couldn't verify.
330 #[inline]
331 #[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
332 #[doc(hidden)]
333 pub const fn from_prim(ek: u32) -> Option<Self> {
334 macro_rules! from_prim {
335 ($prim:expr => $Enum:ident { $($Variant:ident),* $(,)? }) => {{
336 // Force a compile error if the list gets out of date.
337 const _: fn(e: $Enum) = |e: $Enum| match e {
338 $($Enum::$Variant => (),)*
339 };
340 match $prim {
341 $(v if v == ($Enum::$Variant as _) => Some($Enum::$Variant),)*
342 _ => None,
343 }
344 }}
345 }
346 from_prim!(ek => ErrorKind {
347 NotFound,
348 PermissionDenied,
349 ConnectionRefused,
350 ConnectionReset,
351 HostUnreachable,
352 NetworkUnreachable,
353 ConnectionAborted,
354 NotConnected,
355 AddrInUse,
356 AddrNotAvailable,
357 NetworkDown,
358 BrokenPipe,
359 AlreadyExists,
360 WouldBlock,
361 NotADirectory,
362 IsADirectory,
363 DirectoryNotEmpty,
364 ReadOnlyFilesystem,
365 FilesystemLoop,
366 StaleNetworkFileHandle,
367 InvalidInput,
368 InvalidData,
369 TimedOut,
370 WriteZero,
371 StorageFull,
372 NotSeekable,
373 QuotaExceeded,
374 FileTooLarge,
375 ResourceBusy,
376 ExecutableFileBusy,
377 Deadlock,
378 CrossesDevices,
379 TooManyLinks,
380 InvalidFilename,
381 ArgumentListTooLong,
382 Interrupted,
383 Other,
384 UnexpectedEof,
385 Unsupported,
386 OutOfMemory,
387 InProgress,
388 TooManyOpenFiles,
389 Uncategorized,
390 })
391 }
392}
393
394#[stable(feature = "io_errorkind_display", since = "1.60.0")]
395impl fmt::Display for ErrorKind {
396 /// Shows a human-readable description of the [`ErrorKind`].
397 ///
398 /// This is similar to `impl Display for Error`, but doesn't require first converting to Error.
399 ///
400 /// # Examples
401 /// ```
402 /// use core::io::ErrorKind;
403 /// assert_eq!("entity not found", ErrorKind::NotFound.to_string());
404 /// ```
405 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
406 fmt.write_str(self.as_str())
407 }
408}