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