4 #[cfg(target_pointer_width = "64")]
6 #[cfg(target_pointer_width = "64")]
7 use repr_bitpacked::Repr;
9 #[cfg(not(target_pointer_width = "64"))]
11 #[cfg(not(target_pointer_width = "64"))]
12 use repr_unpacked::Repr;
14 use crate::convert::From;
20 /// A specialized [`Result`] type for I/O operations.
22 /// This type is broadly used across [`std::io`] for any operation which may
25 /// This typedef is generally used to avoid writing out [`io::Error`] directly and
26 /// is otherwise a direct mapping to [`Result`].
28 /// While usual Rust style is to import types directly, aliases of [`Result`]
29 /// often are not, to make it easier to distinguish between them. [`Result`] is
30 /// generally assumed to be [`std::result::Result`][`Result`], and so users of this alias
31 /// will generally use `io::Result` instead of shadowing the [prelude]'s import
32 /// of [`std::result::Result`][`Result`].
34 /// [`std::io`]: crate::io
35 /// [`io::Error`]: Error
36 /// [`Result`]: crate::result::Result
37 /// [prelude]: crate::prelude
41 /// A convenience function that bubbles an `io::Result` to its caller:
46 /// fn get_string() -> io::Result<String> {
47 /// let mut buffer = String::new();
49 /// io::stdin().read_line(&mut buffer)?;
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub type Result<T> = result::Result<T, Error>;
57 /// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and
58 /// associated traits.
60 /// Errors mostly originate from the underlying OS, but custom instances of
61 /// `Error` can be created with crafted error messages and a particular value of
64 /// [`Read`]: crate::io::Read
65 /// [`Write`]: crate::io::Write
66 /// [`Seek`]: crate::io::Seek
67 #[stable(feature = "rust1", since = "1.0.0")]
72 #[stable(feature = "rust1", since = "1.0.0")]
73 impl fmt::Debug for Error {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 fmt::Debug::fmt(&self.repr, f)
79 // Only derive debug in tests, to make sure it
80 // doesn't accidentally get printed.
81 #[cfg_attr(test, derive(Debug))]
85 SimpleMessage(&'static SimpleMessage),
89 // `#[repr(align(4))]` is probably redundant, it should have that value or
90 // higher already. We include it just because repr_bitpacked.rs's encoding
91 // requires an alignment >= 4 (note that `#[repr(align)]` will not reduce the
92 // alignment required by the struct, only increase it).
94 // If we add more variants to ErrorData, this can be increased to 8, but it
95 // should probably be behind `#[cfg_attr(target_pointer_width = "64", ...)]` or
96 // whatever cfg we're using to enable the `repr_bitpacked` code, since only the
97 // that version needs the alignment, and 8 is higher than the alignment we'll
98 // have on 32 bit platforms.
100 // (For the sake of being explicit: the alignment requirement here only matters
101 // if `error/repr_bitpacked.rs` is in use — for the unpacked repr it doesn't
105 pub(crate) struct SimpleMessage {
107 message: &'static str,
111 pub(crate) const fn new(kind: ErrorKind, message: &'static str) -> Self {
112 Self { kind, message }
116 /// Create and return an `io::Error` for a given `ErrorKind` and constant
117 /// message. This doesn't allocate.
118 pub(crate) macro const_io_error($kind:expr, $message:expr $(,)?) {
119 $crate::io::error::Error::from_static_message({
120 const MESSAGE_DATA: $crate::io::error::SimpleMessage =
121 $crate::io::error::SimpleMessage::new($kind, $message);
126 // As with `SimpleMessage`: `#[repr(align(4))]` here is just because
127 // repr_bitpacked's encoding requires it. In practice it almost certainly be
128 // already be this high or higher.
133 error: Box<dyn error::Error + Send + Sync>,
136 /// A list specifying general categories of I/O error.
138 /// This list is intended to grow over time and it is not recommended to
139 /// exhaustively match against it.
141 /// It is used with the [`io::Error`] type.
143 /// [`io::Error`]: Error
145 /// # Handling errors and matching on `ErrorKind`
147 /// In application code, use `match` for the `ErrorKind` values you are expecting; use `_` to match
148 /// "all other errors".
150 /// In comprehensive and thorough tests, you may need to cut-and-paste the current list of
151 /// errors from here into your test code.
152 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
153 #[stable(feature = "rust1", since = "1.0.0")]
157 /// An entity was not found, often a file.
158 #[stable(feature = "rust1", since = "1.0.0")]
160 /// The operation lacked the necessary privileges to complete.
161 #[stable(feature = "rust1", since = "1.0.0")]
163 /// The connection was refused by the remote server.
164 #[stable(feature = "rust1", since = "1.0.0")]
166 /// The connection was reset by the remote server.
167 #[stable(feature = "rust1", since = "1.0.0")]
169 /// The remote host is not reachable.
170 #[unstable(feature = "io_error_more", issue = "86442")]
172 /// The network containing the remote host is not reachable.
173 #[unstable(feature = "io_error_more", issue = "86442")]
175 /// The connection was aborted (terminated) by the remote server.
176 #[stable(feature = "rust1", since = "1.0.0")]
178 /// The network operation failed because it was not connected yet.
179 #[stable(feature = "rust1", since = "1.0.0")]
181 /// A socket address could not be bound because the address is already in
183 #[stable(feature = "rust1", since = "1.0.0")]
185 /// A nonexistent interface was requested or the requested address was not
187 #[stable(feature = "rust1", since = "1.0.0")]
189 /// The system's networking is down.
190 #[unstable(feature = "io_error_more", issue = "86442")]
192 /// The operation failed because a pipe was closed.
193 #[stable(feature = "rust1", since = "1.0.0")]
195 /// An entity already exists, often a file.
196 #[stable(feature = "rust1", since = "1.0.0")]
198 /// The operation needs to block to complete, but the blocking operation was
199 /// requested to not occur.
200 #[stable(feature = "rust1", since = "1.0.0")]
202 /// A filesystem object is, unexpectedly, not a directory.
204 /// For example, a filesystem path was specified where one of the intermediate directory
205 /// components was, in fact, a plain file.
206 #[unstable(feature = "io_error_more", issue = "86442")]
208 /// The filesystem object is, unexpectedly, a directory.
210 /// A directory was specified when a non-directory was expected.
211 #[unstable(feature = "io_error_more", issue = "86442")]
213 /// A non-empty directory was specified where an empty directory was expected.
214 #[unstable(feature = "io_error_more", issue = "86442")]
216 /// The filesystem or storage medium is read-only, but a write operation was attempted.
217 #[unstable(feature = "io_error_more", issue = "86442")]
219 /// Loop in the filesystem or IO subsystem; often, too many levels of symbolic links.
221 /// There was a loop (or excessively long chain) resolving a filesystem object
222 /// or file IO object.
224 /// On Unix this is usually the result of a symbolic link loop; or, of exceeding the
225 /// system-specific limit on the depth of symlink traversal.
226 #[unstable(feature = "io_error_more", issue = "86442")]
228 /// Stale network file handle.
230 /// With some network filesystems, notably NFS, an open file (or directory) can be invalidated
231 /// by problems with the network or server.
232 #[unstable(feature = "io_error_more", issue = "86442")]
233 StaleNetworkFileHandle,
234 /// A parameter was incorrect.
235 #[stable(feature = "rust1", since = "1.0.0")]
237 /// Data not valid for the operation were encountered.
239 /// Unlike [`InvalidInput`], this typically means that the operation
240 /// parameters were valid, however the error was caused by malformed
243 /// For example, a function that reads a file into a string will error with
244 /// `InvalidData` if the file's contents are not valid UTF-8.
246 /// [`InvalidInput`]: ErrorKind::InvalidInput
247 #[stable(feature = "io_invalid_data", since = "1.2.0")]
249 /// The I/O operation's timeout expired, causing it to be canceled.
250 #[stable(feature = "rust1", since = "1.0.0")]
252 /// An error returned when an operation could not be completed because a
253 /// call to [`write`] returned [`Ok(0)`].
255 /// This typically means that an operation could only succeed if it wrote a
256 /// particular number of bytes but only a smaller number of bytes could be
259 /// [`write`]: crate::io::Write::write
261 #[stable(feature = "rust1", since = "1.0.0")]
263 /// The underlying storage (typically, a filesystem) is full.
265 /// This does not include out of quota errors.
266 #[unstable(feature = "io_error_more", issue = "86442")]
268 /// Seek on unseekable file.
270 /// Seeking was attempted on an open file handle which is not suitable for seeking - for
271 /// example, on Unix, a named pipe opened with `File::open`.
272 #[unstable(feature = "io_error_more", issue = "86442")]
274 /// Filesystem quota was exceeded.
275 #[unstable(feature = "io_error_more", issue = "86442")]
276 FilesystemQuotaExceeded,
277 /// File larger than allowed or supported.
279 /// This might arise from a hard limit of the underlying filesystem or file access API, or from
280 /// an administratively imposed resource limitation. Simple disk full, and out of quota, have
281 /// their own errors.
282 #[unstable(feature = "io_error_more", issue = "86442")]
284 /// Resource is busy.
285 #[unstable(feature = "io_error_more", issue = "86442")]
287 /// Executable file is busy.
289 /// An attempt was made to write to a file which is also in use as a running program. (Not all
290 /// operating systems detect this situation.)
291 #[unstable(feature = "io_error_more", issue = "86442")]
293 /// Deadlock (avoided).
295 /// A file locking operation would result in deadlock. This situation is typically detected, if
296 /// at all, on a best-effort basis.
297 #[unstable(feature = "io_error_more", issue = "86442")]
299 /// Cross-device or cross-filesystem (hard) link or rename.
300 #[unstable(feature = "io_error_more", issue = "86442")]
302 /// Too many (hard) links to the same filesystem object.
304 /// The filesystem does not support making so many hardlinks to the same file.
305 #[unstable(feature = "io_error_more", issue = "86442")]
307 /// A filename was invalid.
309 /// This error can also cause if it exceeded the filename length limit.
310 #[unstable(feature = "io_error_more", issue = "86442")]
312 /// Program argument list too long.
314 /// When trying to run an external program, a system or process limit on the size of the
315 /// arguments would have been exceeded.
316 #[unstable(feature = "io_error_more", issue = "86442")]
318 /// This operation was interrupted.
320 /// Interrupted operations can typically be retried.
321 #[stable(feature = "rust1", since = "1.0.0")]
324 /// This operation is unsupported on this platform.
326 /// This means that the operation can never succeed.
327 #[stable(feature = "unsupported_error", since = "1.53.0")]
330 // ErrorKinds which are primarily categorisations for OS error
331 // codes should be added above.
333 /// An error returned when an operation could not be completed because an
334 /// "end of file" was reached prematurely.
336 /// This typically means that an operation could only succeed if it read a
337 /// particular number of bytes but only a smaller number of bytes could be
339 #[stable(feature = "read_exact", since = "1.6.0")]
342 /// An operation could not be completed, because it failed
343 /// to allocate enough memory.
344 #[stable(feature = "out_of_memory_error", since = "1.54.0")]
347 // "Unusual" error kinds which do not correspond simply to (sets
348 // of) OS error codes, should be added just above this comment.
349 // `Other` and `Uncategorised` should remain at the end:
351 /// A custom error that does not fall under any other I/O error kind.
353 /// This can be used to construct your own [`Error`]s that do not match any
356 /// This [`ErrorKind`] is not used by the standard library.
358 /// Errors from the standard library that do not fall under any of the I/O
359 /// error kinds cannot be `match`ed on, and will only match a wildcard (`_`) pattern.
360 /// New [`ErrorKind`]s might be added in the future for some of those.
361 #[stable(feature = "rust1", since = "1.0.0")]
364 /// Any I/O error from the standard library that's not part of this list.
366 /// Errors that are `Uncategorized` now may move to a different or a new
367 /// [`ErrorKind`] variant in the future. It is not recommended to match
368 /// an error against `Uncategorized`; use a wildcard match (`_`) instead.
369 #[unstable(feature = "io_error_uncategorized", issue = "none")]
375 pub(crate) fn as_str(&self) -> &'static str {
377 // Strictly alphabetical, please. (Sadly rustfmt cannot do this yet.)
379 AddrInUse => "address in use",
380 AddrNotAvailable => "address not available",
381 AlreadyExists => "entity already exists",
382 ArgumentListTooLong => "argument list too long",
383 BrokenPipe => "broken pipe",
384 ConnectionAborted => "connection aborted",
385 ConnectionRefused => "connection refused",
386 ConnectionReset => "connection reset",
387 CrossesDevices => "cross-device link or rename",
388 Deadlock => "deadlock",
389 DirectoryNotEmpty => "directory not empty",
390 ExecutableFileBusy => "executable file busy",
391 FileTooLarge => "file too large",
392 FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)",
393 FilesystemQuotaExceeded => "filesystem quota exceeded",
394 HostUnreachable => "host unreachable",
395 Interrupted => "operation interrupted",
396 InvalidData => "invalid data",
397 InvalidFilename => "invalid filename",
398 InvalidInput => "invalid input parameter",
399 IsADirectory => "is a directory",
400 NetworkDown => "network down",
401 NetworkUnreachable => "network unreachable",
402 NotADirectory => "not a directory",
403 NotConnected => "not connected",
404 NotFound => "entity not found",
405 NotSeekable => "seek on unseekable file",
406 Other => "other error",
407 OutOfMemory => "out of memory",
408 PermissionDenied => "permission denied",
409 ReadOnlyFilesystem => "read-only filesystem or storage medium",
410 ResourceBusy => "resource busy",
411 StaleNetworkFileHandle => "stale network file handle",
412 StorageFull => "no storage space",
413 TimedOut => "timed out",
414 TooManyLinks => "too many links",
415 Uncategorized => "uncategorized error",
416 UnexpectedEof => "unexpected end of file",
417 Unsupported => "unsupported",
418 WouldBlock => "operation would block",
419 WriteZero => "write zero",
424 #[stable(feature = "io_errorkind_display", since = "1.60.0")]
425 impl fmt::Display for ErrorKind {
426 /// Shows a human-readable description of the `ErrorKind`.
428 /// This is similar to `impl Display for Error`, but doesn't require first converting to Error.
432 /// use std::io::ErrorKind;
433 /// assert_eq!("entity not found", ErrorKind::NotFound.to_string());
435 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
436 fmt.write_str(self.as_str())
440 /// Intended for use for errors not exposed to the user, where allocating onto
441 /// the heap (for normal construction via Error::new) is too costly.
442 #[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
443 impl From<ErrorKind> for Error {
444 /// Converts an [`ErrorKind`] into an [`Error`].
446 /// This conversion creates a new error with a simple representation of error kind.
451 /// use std::io::{Error, ErrorKind};
453 /// let not_found = ErrorKind::NotFound;
454 /// let error = Error::from(not_found);
455 /// assert_eq!("entity not found", format!("{}", error));
458 fn from(kind: ErrorKind) -> Error {
459 Error { repr: Repr::new_simple(kind) }
464 /// Creates a new I/O error from a known kind of error as well as an
465 /// arbitrary error payload.
467 /// This function is used to generically create I/O errors which do not
468 /// originate from the OS itself. The `error` argument is an arbitrary
469 /// payload which will be contained in this [`Error`].
471 /// If no extra payload is required, use the `From` conversion from
477 /// use std::io::{Error, ErrorKind};
479 /// // errors can be created from strings
480 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
482 /// // errors can also be created from other errors
483 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
485 /// // creating an error without payload
486 /// let eof_error = Error::from(ErrorKind::UnexpectedEof);
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn new<E>(kind: ErrorKind, error: E) -> Error
491 E: Into<Box<dyn error::Error + Send + Sync>>,
493 Self::_new(kind, error.into())
496 /// Creates a new I/O error from an arbitrary error payload.
498 /// This function is used to generically create I/O errors which do not
499 /// originate from the OS itself. It is a shortcut for [`Error::new`]
500 /// with [`ErrorKind::Other`].
505 /// #![feature(io_error_other)]
507 /// use std::io::Error;
509 /// // errors can be created from strings
510 /// let custom_error = Error::other("oh no!");
512 /// // errors can also be created from other errors
513 /// let custom_error2 = Error::other(custom_error);
515 #[unstable(feature = "io_error_other", issue = "91946")]
516 pub fn other<E>(error: E) -> Error
518 E: Into<Box<dyn error::Error + Send + Sync>>,
520 Self::_new(ErrorKind::Other, error.into())
523 fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
524 Error { repr: Repr::new_custom(Box::new(Custom { kind, error })) }
527 /// Creates a new I/O error from a known kind of error as well as a constant
530 /// This function does not allocate.
532 /// You should not use this directly, and instead use the `const_io_error!`
533 /// macro: `io::const_io_error!(ErrorKind::Something, "some_message")`.
535 /// This function should maybe change to `from_static_message<const MSG: &'static
536 /// str>(kind: ErrorKind)` in the future, when const generics allow that.
538 pub(crate) const fn from_static_message(msg: &'static SimpleMessage) -> Error {
539 Self { repr: Repr::new_simple_message(msg) }
542 /// Returns an error representing the last OS error which occurred.
544 /// This function reads the value of `errno` for the target platform (e.g.
545 /// `GetLastError` on Windows) and will return a corresponding instance of
546 /// [`Error`] for the error code.
548 /// This should be called immediately after a call to a platform function,
549 /// otherwise the state of the error value is indeterminate. In particular,
550 /// other standard library functions may call platform functions that may
551 /// (or may not) reset the error value even if they succeed.
556 /// use std::io::Error;
558 /// let os_error = Error::last_os_error();
559 /// println!("last OS error: {:?}", os_error);
561 #[stable(feature = "rust1", since = "1.0.0")]
564 pub fn last_os_error() -> Error {
565 Error::from_raw_os_error(sys::os::errno() as i32)
568 /// Creates a new instance of an [`Error`] from a particular OS error code.
575 /// # if cfg!(target_os = "linux") {
578 /// let error = io::Error::from_raw_os_error(22);
579 /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
586 /// # if cfg!(windows) {
589 /// let error = io::Error::from_raw_os_error(10022);
590 /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
593 #[stable(feature = "rust1", since = "1.0.0")]
596 pub fn from_raw_os_error(code: i32) -> Error {
597 Error { repr: Repr::new_os(code) }
600 /// Returns the OS error that this error represents (if any).
602 /// If this [`Error`] was constructed via [`last_os_error`] or
603 /// [`from_raw_os_error`], then this function will return [`Some`], otherwise
604 /// it will return [`None`].
606 /// [`last_os_error`]: Error::last_os_error
607 /// [`from_raw_os_error`]: Error::from_raw_os_error
612 /// use std::io::{Error, ErrorKind};
614 /// fn print_os_error(err: &Error) {
615 /// if let Some(raw_os_err) = err.raw_os_error() {
616 /// println!("raw OS error: {:?}", raw_os_err);
618 /// println!("Not an OS error");
623 /// // Will print "raw OS error: ...".
624 /// print_os_error(&Error::last_os_error());
625 /// // Will print "Not an OS error".
626 /// print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
629 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn raw_os_error(&self) -> Option<i32> {
633 match self.repr.data() {
634 ErrorData::Os(i) => Some(i),
635 ErrorData::Custom(..) => None,
636 ErrorData::Simple(..) => None,
637 ErrorData::SimpleMessage(..) => None,
641 /// Returns a reference to the inner error wrapped by this error (if any).
643 /// If this [`Error`] was constructed via [`new`] then this function will
644 /// return [`Some`], otherwise it will return [`None`].
646 /// [`new`]: Error::new
651 /// use std::io::{Error, ErrorKind};
653 /// fn print_error(err: &Error) {
654 /// if let Some(inner_err) = err.get_ref() {
655 /// println!("Inner error: {:?}", inner_err);
657 /// println!("No inner error");
662 /// // Will print "No inner error".
663 /// print_error(&Error::last_os_error());
664 /// // Will print "Inner error: ...".
665 /// print_error(&Error::new(ErrorKind::Other, "oh no!"));
668 #[stable(feature = "io_error_inner", since = "1.3.0")]
671 pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
672 match self.repr.data() {
673 ErrorData::Os(..) => None,
674 ErrorData::Simple(..) => None,
675 ErrorData::SimpleMessage(..) => None,
676 ErrorData::Custom(c) => Some(&*c.error),
680 /// Returns a mutable reference to the inner error wrapped by this error
683 /// If this [`Error`] was constructed via [`new`] then this function will
684 /// return [`Some`], otherwise it will return [`None`].
686 /// [`new`]: Error::new
691 /// use std::io::{Error, ErrorKind};
692 /// use std::{error, fmt};
693 /// use std::fmt::Display;
701 /// fn new() -> MyError {
703 /// v: "oh no!".to_string()
707 /// fn change_message(&mut self, new_message: &str) {
708 /// self.v = new_message.to_string();
712 /// impl error::Error for MyError {}
714 /// impl Display for MyError {
715 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716 /// write!(f, "MyError: {}", &self.v)
720 /// fn change_error(mut err: Error) -> Error {
721 /// if let Some(inner_err) = err.get_mut() {
722 /// inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
727 /// fn print_error(err: &Error) {
728 /// if let Some(inner_err) = err.get_ref() {
729 /// println!("Inner error: {}", inner_err);
731 /// println!("No inner error");
736 /// // Will print "No inner error".
737 /// print_error(&change_error(Error::last_os_error()));
738 /// // Will print "Inner error: ...".
739 /// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
742 #[stable(feature = "io_error_inner", since = "1.3.0")]
745 pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
746 match self.repr.data_mut() {
747 ErrorData::Os(..) => None,
748 ErrorData::Simple(..) => None,
749 ErrorData::SimpleMessage(..) => None,
750 ErrorData::Custom(c) => Some(&mut *c.error),
754 /// Consumes the `Error`, returning its inner error (if any).
756 /// If this [`Error`] was constructed via [`new`] then this function will
757 /// return [`Some`], otherwise it will return [`None`].
759 /// [`new`]: Error::new
764 /// use std::io::{Error, ErrorKind};
766 /// fn print_error(err: Error) {
767 /// if let Some(inner_err) = err.into_inner() {
768 /// println!("Inner error: {}", inner_err);
770 /// println!("No inner error");
775 /// // Will print "No inner error".
776 /// print_error(Error::last_os_error());
777 /// // Will print "Inner error: ...".
778 /// print_error(Error::new(ErrorKind::Other, "oh no!"));
781 #[stable(feature = "io_error_inner", since = "1.3.0")]
782 #[must_use = "`self` will be dropped if the result is not used"]
784 pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
785 match self.repr.into_data() {
786 ErrorData::Os(..) => None,
787 ErrorData::Simple(..) => None,
788 ErrorData::SimpleMessage(..) => None,
789 ErrorData::Custom(c) => Some(c.error),
793 /// Returns the corresponding [`ErrorKind`] for this error.
798 /// use std::io::{Error, ErrorKind};
800 /// fn print_error(err: Error) {
801 /// println!("{:?}", err.kind());
805 /// // Will print "Uncategorized".
806 /// print_error(Error::last_os_error());
807 /// // Will print "AddrInUse".
808 /// print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
811 #[stable(feature = "rust1", since = "1.0.0")]
814 pub fn kind(&self) -> ErrorKind {
815 match self.repr.data() {
816 ErrorData::Os(code) => sys::decode_error_kind(code),
817 ErrorData::Custom(c) => c.kind,
818 ErrorData::Simple(kind) => kind,
819 ErrorData::SimpleMessage(m) => m.kind,
824 impl fmt::Debug for Repr {
825 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
827 ErrorData::Os(code) => fmt
829 .field("code", &code)
830 .field("kind", &sys::decode_error_kind(code))
831 .field("message", &sys::os::error_string(code))
833 ErrorData::Custom(c) => fmt::Debug::fmt(&c, fmt),
834 ErrorData::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
835 ErrorData::SimpleMessage(msg) => fmt
836 .debug_struct("Error")
837 .field("kind", &msg.kind)
838 .field("message", &msg.message)
844 #[stable(feature = "rust1", since = "1.0.0")]
845 impl fmt::Display for Error {
846 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
847 match self.repr.data() {
848 ErrorData::Os(code) => {
849 let detail = sys::os::error_string(code);
850 write!(fmt, "{} (os error {})", detail, code)
852 ErrorData::Custom(ref c) => c.error.fmt(fmt),
853 ErrorData::Simple(kind) => write!(fmt, "{}", kind.as_str()),
854 ErrorData::SimpleMessage(msg) => msg.message.fmt(fmt),
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl error::Error for Error {
861 #[allow(deprecated, deprecated_in_future)]
862 fn description(&self) -> &str {
863 match self.repr.data() {
864 ErrorData::Os(..) | ErrorData::Simple(..) => self.kind().as_str(),
865 ErrorData::SimpleMessage(msg) => msg.message,
866 ErrorData::Custom(c) => c.error.description(),
871 fn cause(&self) -> Option<&dyn error::Error> {
872 match self.repr.data() {
873 ErrorData::Os(..) => None,
874 ErrorData::Simple(..) => None,
875 ErrorData::SimpleMessage(..) => None,
876 ErrorData::Custom(c) => c.error.cause(),
880 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
881 match self.repr.data() {
882 ErrorData::Os(..) => None,
883 ErrorData::Simple(..) => None,
884 ErrorData::SimpleMessage(..) => None,
885 ErrorData::Custom(c) => c.error.source(),
890 fn _assert_error_is_sync_send() {
891 fn _is_sync_send<T: Sync + Send>() {}
892 _is_sync_send::<Error>();