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