std/io/error.rs
1#[cfg(test)]
2mod tests;
3
4#[stable(feature = "rust1", since = "1.0.0")]
5pub use core::io::ErrorKind;
6#[unstable(feature = "raw_os_error_ty", issue = "107792")]
7pub use core::io::RawOsError;
8
9// On 64-bit platforms, `io::Error` may use a bit-packed representation to
10// reduce size. However, this representation assumes that error codes are
11// always 32-bit wide.
12//
13// This assumption is invalid on 64-bit UEFI, where error codes are 64-bit.
14// Therefore, the packed representation is explicitly disabled for UEFI
15// targets, and the unpacked representation must be used instead.
16#[cfg(all(target_pointer_width = "64", not(target_os = "uefi")))]
17mod repr_bitpacked;
18#[cfg(all(target_pointer_width = "64", not(target_os = "uefi")))]
19use repr_bitpacked::Repr;
20
21#[cfg(any(not(target_pointer_width = "64"), target_os = "uefi"))]
22mod repr_unpacked;
23#[cfg(any(not(target_pointer_width = "64"), target_os = "uefi"))]
24use repr_unpacked::Repr;
25
26use crate::{error, fmt, result, sys};
27
28/// A specialized [`Result`] type for I/O operations.
29///
30/// This type is broadly used across [`std::io`] for any operation which may
31/// produce an error.
32///
33/// This type alias is generally used to avoid writing out [`io::Error`] directly and
34/// is otherwise a direct mapping to [`Result`].
35///
36/// While usual Rust style is to import types directly, aliases of [`Result`]
37/// often are not, to make it easier to distinguish between them. [`Result`] is
38/// generally assumed to be [`std::result::Result`][`Result`], and so users of this alias
39/// will generally use `io::Result` instead of shadowing the [prelude]'s import
40/// of [`std::result::Result`][`Result`].
41///
42/// [`std::io`]: crate::io
43/// [`io::Error`]: Error
44/// [`Result`]: crate::result::Result
45/// [prelude]: crate::prelude
46///
47/// # Examples
48///
49/// A convenience function that bubbles an `io::Result` to its caller:
50///
51/// ```
52/// use std::io;
53///
54/// fn get_string() -> io::Result<String> {
55/// let mut buffer = String::new();
56///
57/// io::stdin().read_line(&mut buffer)?;
58///
59/// Ok(buffer)
60/// }
61/// ```
62#[stable(feature = "rust1", since = "1.0.0")]
63#[doc(search_unbox)]
64pub type Result<T> = result::Result<T, Error>;
65
66/// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and
67/// associated traits.
68///
69/// Errors mostly originate from the underlying OS, but custom instances of
70/// `Error` can be created with crafted error messages and a particular value of
71/// [`ErrorKind`].
72///
73/// [`Read`]: crate::io::Read
74/// [`Write`]: crate::io::Write
75/// [`Seek`]: crate::io::Seek
76#[stable(feature = "rust1", since = "1.0.0")]
77pub struct Error {
78 repr: Repr,
79}
80
81#[stable(feature = "rust1", since = "1.0.0")]
82impl fmt::Debug for Error {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 fmt::Debug::fmt(&self.repr, f)
85 }
86}
87
88/// Common errors constants for use in std
89#[allow(dead_code)]
90impl Error {
91 pub(crate) const INVALID_UTF8: Self =
92 const_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8");
93
94 pub(crate) const READ_EXACT_EOF: Self =
95 const_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer");
96
97 pub(crate) const UNKNOWN_THREAD_COUNT: Self = const_error!(
98 ErrorKind::NotFound,
99 "the number of hardware threads is not known for the target platform",
100 );
101
102 pub(crate) const UNSUPPORTED_PLATFORM: Self =
103 const_error!(ErrorKind::Unsupported, "operation not supported on this platform");
104
105 pub(crate) const WRITE_ALL_EOF: Self =
106 const_error!(ErrorKind::WriteZero, "failed to write whole buffer");
107
108 pub(crate) const ZERO_TIMEOUT: Self =
109 const_error!(ErrorKind::InvalidInput, "cannot set a 0 duration timeout");
110
111 pub(crate) const NO_ADDRESSES: Self =
112 const_error!(ErrorKind::InvalidInput, "could not resolve to any addresses");
113}
114
115#[stable(feature = "rust1", since = "1.0.0")]
116impl From<alloc::ffi::NulError> for Error {
117 /// Converts a [`alloc::ffi::NulError`] into a [`Error`].
118 fn from(_: alloc::ffi::NulError) -> Error {
119 const_error!(ErrorKind::InvalidInput, "data provided contains a nul byte")
120 }
121}
122
123#[stable(feature = "io_error_from_try_reserve", since = "1.78.0")]
124impl From<alloc::collections::TryReserveError> for Error {
125 /// Converts `TryReserveError` to an error with [`ErrorKind::OutOfMemory`].
126 ///
127 /// `TryReserveError` won't be available as the error `source()`,
128 /// but this may change in the future.
129 fn from(_: alloc::collections::TryReserveError) -> Error {
130 // ErrorData::Custom allocates, which isn't great for handling OOM errors.
131 ErrorKind::OutOfMemory.into()
132 }
133}
134
135// Only derive debug in tests, to make sure it
136// doesn't accidentally get printed.
137#[cfg_attr(test, derive(Debug))]
138enum ErrorData<C> {
139 Os(RawOsError),
140 Simple(ErrorKind),
141 SimpleMessage(&'static SimpleMessage),
142 Custom(C),
143}
144
145// `#[repr(align(4))]` is probably redundant, it should have that value or
146// higher already. We include it just because repr_bitpacked.rs's encoding
147// requires an alignment >= 4 (note that `#[repr(align)]` will not reduce the
148// alignment required by the struct, only increase it).
149//
150// If we add more variants to ErrorData, this can be increased to 8, but it
151// should probably be behind `#[cfg_attr(target_pointer_width = "64", ...)]` or
152// whatever cfg we're using to enable the `repr_bitpacked` code, since only the
153// that version needs the alignment, and 8 is higher than the alignment we'll
154// have on 32 bit platforms.
155//
156// (For the sake of being explicit: the alignment requirement here only matters
157// if `error/repr_bitpacked.rs` is in use — for the unpacked repr it doesn't
158// matter at all)
159#[doc(hidden)]
160#[unstable(feature = "io_const_error_internals", issue = "none")]
161#[repr(align(4))]
162#[derive(Debug)]
163pub struct SimpleMessage {
164 pub kind: ErrorKind,
165 pub message: &'static str,
166}
167
168/// Creates a new I/O error from a known kind of error and a string literal.
169///
170/// Contrary to [`Error::new`], this macro does not allocate and can be used in
171/// `const` contexts.
172///
173/// # Example
174/// ```
175/// #![feature(io_const_error)]
176/// use std::io::{const_error, Error, ErrorKind};
177///
178/// const FAIL: Error = const_error!(ErrorKind::Unsupported, "tried something that never works");
179///
180/// fn not_here() -> Result<(), Error> {
181/// Err(FAIL)
182/// }
183/// ```
184#[rustc_macro_transparency = "semiopaque"]
185#[unstable(feature = "io_const_error", issue = "133448")]
186#[allow_internal_unstable(hint_must_use, io_const_error_internals)]
187pub macro const_error($kind:expr, $message:expr $(,)?) {
188 $crate::hint::must_use($crate::io::Error::from_static_message(
189 const { &$crate::io::SimpleMessage { kind: $kind, message: $message } },
190 ))
191}
192
193// As with `SimpleMessage`: `#[repr(align(4))]` here is just because
194// repr_bitpacked's encoding requires it. In practice it almost certainly be
195// already be this high or higher.
196#[derive(Debug)]
197#[repr(align(4))]
198struct Custom {
199 kind: ErrorKind,
200 error: Box<dyn error::Error + Send + Sync>,
201}
202
203/// Intended for use for errors not exposed to the user, where allocating onto
204/// the heap (for normal construction via Error::new) is too costly.
205#[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
206impl From<ErrorKind> for Error {
207 /// Converts an [`ErrorKind`] into an [`Error`].
208 ///
209 /// This conversion creates a new error with a simple representation of error kind.
210 ///
211 /// # Examples
212 ///
213 /// ```
214 /// use std::io::{Error, ErrorKind};
215 ///
216 /// let not_found = ErrorKind::NotFound;
217 /// let error = Error::from(not_found);
218 /// assert_eq!("entity not found", format!("{error}"));
219 /// ```
220 #[inline]
221 fn from(kind: ErrorKind) -> Error {
222 Error { repr: Repr::new_simple(kind) }
223 }
224}
225
226impl Error {
227 /// Creates a new I/O error from a known kind of error as well as an
228 /// arbitrary error payload.
229 ///
230 /// This function is used to generically create I/O errors which do not
231 /// originate from the OS itself. The `error` argument is an arbitrary
232 /// payload which will be contained in this [`Error`].
233 ///
234 /// Note that this function allocates memory on the heap.
235 /// If no extra payload is required, use the `From` conversion from
236 /// `ErrorKind`.
237 ///
238 /// # Examples
239 ///
240 /// ```
241 /// use std::io::{Error, ErrorKind};
242 ///
243 /// // errors can be created from strings
244 /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
245 ///
246 /// // errors can also be created from other errors
247 /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
248 ///
249 /// // creating an error without payload (and without memory allocation)
250 /// let eof_error = Error::from(ErrorKind::UnexpectedEof);
251 /// ```
252 #[stable(feature = "rust1", since = "1.0.0")]
253 #[cfg_attr(not(test), rustc_diagnostic_item = "io_error_new")]
254 #[inline(never)]
255 pub fn new<E>(kind: ErrorKind, error: E) -> Error
256 where
257 E: Into<Box<dyn error::Error + Send + Sync>>,
258 {
259 Self::_new(kind, error.into())
260 }
261
262 /// Creates a new I/O error from an arbitrary error payload.
263 ///
264 /// This function is used to generically create I/O errors which do not
265 /// originate from the OS itself. It is a shortcut for [`Error::new`]
266 /// with [`ErrorKind::Other`].
267 ///
268 /// # Examples
269 ///
270 /// ```
271 /// use std::io::Error;
272 ///
273 /// // errors can be created from strings
274 /// let custom_error = Error::other("oh no!");
275 ///
276 /// // errors can also be created from other errors
277 /// let custom_error2 = Error::other(custom_error);
278 /// ```
279 #[stable(feature = "io_error_other", since = "1.74.0")]
280 pub fn other<E>(error: E) -> Error
281 where
282 E: Into<Box<dyn error::Error + Send + Sync>>,
283 {
284 Self::_new(ErrorKind::Other, error.into())
285 }
286
287 fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
288 Error { repr: Repr::new_custom(Box::new(Custom { kind, error })) }
289 }
290
291 /// Creates a new I/O error from a known kind of error as well as a constant
292 /// message.
293 ///
294 /// This function does not allocate.
295 ///
296 /// You should not use this directly, and instead use the `const_error!`
297 /// macro: `io::const_error!(ErrorKind::Something, "some_message")`.
298 ///
299 /// This function should maybe change to `from_static_message<const MSG: &'static
300 /// str>(kind: ErrorKind)` in the future, when const generics allow that.
301 #[inline]
302 #[doc(hidden)]
303 #[unstable(feature = "io_const_error_internals", issue = "none")]
304 pub const fn from_static_message(msg: &'static SimpleMessage) -> Error {
305 Self { repr: Repr::new_simple_message(msg) }
306 }
307
308 /// Returns an error representing the last OS error which occurred.
309 ///
310 /// This function reads the value of `errno` for the target platform (e.g.
311 /// `GetLastError` on Windows) and will return a corresponding instance of
312 /// [`Error`] for the error code.
313 ///
314 /// This should be called immediately after a call to a platform function,
315 /// otherwise the state of the error value is indeterminate. In particular,
316 /// other standard library functions may call platform functions that may
317 /// (or may not) reset the error value even if they succeed.
318 ///
319 /// # Examples
320 ///
321 /// ```
322 /// use std::io::Error;
323 ///
324 /// let os_error = Error::last_os_error();
325 /// println!("last OS error: {os_error:?}");
326 /// ```
327 #[stable(feature = "rust1", since = "1.0.0")]
328 #[doc(alias = "GetLastError")]
329 #[doc(alias = "errno")]
330 #[must_use]
331 #[inline]
332 pub fn last_os_error() -> Error {
333 Error::from_raw_os_error(sys::io::errno())
334 }
335
336 /// Creates a new instance of an [`Error`] from a particular OS error code.
337 ///
338 /// # Examples
339 ///
340 /// On Linux:
341 ///
342 /// ```
343 /// # if cfg!(target_os = "linux") {
344 /// use std::io;
345 ///
346 /// let error = io::Error::from_raw_os_error(22);
347 /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
348 /// # }
349 /// ```
350 ///
351 /// On Windows:
352 ///
353 /// ```
354 /// # if cfg!(windows) {
355 /// use std::io;
356 ///
357 /// let error = io::Error::from_raw_os_error(10022);
358 /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
359 /// # }
360 /// ```
361 #[stable(feature = "rust1", since = "1.0.0")]
362 #[must_use]
363 #[inline]
364 pub fn from_raw_os_error(code: RawOsError) -> Error {
365 Error { repr: Repr::new_os(code) }
366 }
367
368 /// Returns the OS error that this error represents (if any).
369 ///
370 /// If this [`Error`] was constructed via [`last_os_error`] or
371 /// [`from_raw_os_error`], then this function will return [`Some`], otherwise
372 /// it will return [`None`].
373 ///
374 /// [`last_os_error`]: Error::last_os_error
375 /// [`from_raw_os_error`]: Error::from_raw_os_error
376 ///
377 /// # Examples
378 ///
379 /// ```
380 /// use std::io::{Error, ErrorKind};
381 ///
382 /// fn print_os_error(err: &Error) {
383 /// if let Some(raw_os_err) = err.raw_os_error() {
384 /// println!("raw OS error: {raw_os_err:?}");
385 /// } else {
386 /// println!("Not an OS error");
387 /// }
388 /// }
389 ///
390 /// fn main() {
391 /// // Will print "raw OS error: ...".
392 /// print_os_error(&Error::last_os_error());
393 /// // Will print "Not an OS error".
394 /// print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
395 /// }
396 /// ```
397 #[stable(feature = "rust1", since = "1.0.0")]
398 #[must_use]
399 #[inline]
400 pub fn raw_os_error(&self) -> Option<RawOsError> {
401 match self.repr.data() {
402 ErrorData::Os(i) => Some(i),
403 ErrorData::Custom(..) => None,
404 ErrorData::Simple(..) => None,
405 ErrorData::SimpleMessage(..) => None,
406 }
407 }
408
409 /// Returns a reference to the inner error wrapped by this error (if any).
410 ///
411 /// If this [`Error`] was constructed via [`new`] then this function will
412 /// return [`Some`], otherwise it will return [`None`].
413 ///
414 /// [`new`]: Error::new
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// use std::io::{Error, ErrorKind};
420 ///
421 /// fn print_error(err: &Error) {
422 /// if let Some(inner_err) = err.get_ref() {
423 /// println!("Inner error: {inner_err:?}");
424 /// } else {
425 /// println!("No inner error");
426 /// }
427 /// }
428 ///
429 /// fn main() {
430 /// // Will print "No inner error".
431 /// print_error(&Error::last_os_error());
432 /// // Will print "Inner error: ...".
433 /// print_error(&Error::new(ErrorKind::Other, "oh no!"));
434 /// }
435 /// ```
436 #[stable(feature = "io_error_inner", since = "1.3.0")]
437 #[must_use]
438 #[inline]
439 pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
440 match self.repr.data() {
441 ErrorData::Os(..) => None,
442 ErrorData::Simple(..) => None,
443 ErrorData::SimpleMessage(..) => None,
444 ErrorData::Custom(c) => Some(&*c.error),
445 }
446 }
447
448 /// Returns a mutable reference to the inner error wrapped by this error
449 /// (if any).
450 ///
451 /// If this [`Error`] was constructed via [`new`] then this function will
452 /// return [`Some`], otherwise it will return [`None`].
453 ///
454 /// [`new`]: Error::new
455 ///
456 /// # Examples
457 ///
458 /// ```
459 /// use std::io::{Error, ErrorKind};
460 /// use std::{error, fmt};
461 /// use std::fmt::Display;
462 ///
463 /// #[derive(Debug)]
464 /// struct MyError {
465 /// v: String,
466 /// }
467 ///
468 /// impl MyError {
469 /// fn new() -> MyError {
470 /// MyError {
471 /// v: "oh no!".to_string()
472 /// }
473 /// }
474 ///
475 /// fn change_message(&mut self, new_message: &str) {
476 /// self.v = new_message.to_string();
477 /// }
478 /// }
479 ///
480 /// impl error::Error for MyError {}
481 ///
482 /// impl Display for MyError {
483 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484 /// write!(f, "MyError: {}", self.v)
485 /// }
486 /// }
487 ///
488 /// fn change_error(mut err: Error) -> Error {
489 /// if let Some(inner_err) = err.get_mut() {
490 /// inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
491 /// }
492 /// err
493 /// }
494 ///
495 /// fn print_error(err: &Error) {
496 /// if let Some(inner_err) = err.get_ref() {
497 /// println!("Inner error: {inner_err}");
498 /// } else {
499 /// println!("No inner error");
500 /// }
501 /// }
502 ///
503 /// fn main() {
504 /// // Will print "No inner error".
505 /// print_error(&change_error(Error::last_os_error()));
506 /// // Will print "Inner error: ...".
507 /// print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
508 /// }
509 /// ```
510 #[stable(feature = "io_error_inner", since = "1.3.0")]
511 #[must_use]
512 #[inline]
513 pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
514 match self.repr.data_mut() {
515 ErrorData::Os(..) => None,
516 ErrorData::Simple(..) => None,
517 ErrorData::SimpleMessage(..) => None,
518 ErrorData::Custom(c) => Some(&mut *c.error),
519 }
520 }
521
522 /// Consumes the `Error`, returning its inner error (if any).
523 ///
524 /// If this [`Error`] was constructed via [`new`] or [`other`],
525 /// then this function will return [`Some`],
526 /// otherwise it will return [`None`].
527 ///
528 /// [`new`]: Error::new
529 /// [`other`]: Error::other
530 ///
531 /// # Examples
532 ///
533 /// ```
534 /// use std::io::{Error, ErrorKind};
535 ///
536 /// fn print_error(err: Error) {
537 /// if let Some(inner_err) = err.into_inner() {
538 /// println!("Inner error: {inner_err}");
539 /// } else {
540 /// println!("No inner error");
541 /// }
542 /// }
543 ///
544 /// fn main() {
545 /// // Will print "No inner error".
546 /// print_error(Error::last_os_error());
547 /// // Will print "Inner error: ...".
548 /// print_error(Error::new(ErrorKind::Other, "oh no!"));
549 /// }
550 /// ```
551 #[stable(feature = "io_error_inner", since = "1.3.0")]
552 #[must_use = "`self` will be dropped if the result is not used"]
553 #[inline]
554 pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
555 match self.repr.into_data() {
556 ErrorData::Os(..) => None,
557 ErrorData::Simple(..) => None,
558 ErrorData::SimpleMessage(..) => None,
559 ErrorData::Custom(c) => Some(c.error),
560 }
561 }
562
563 /// Attempts to downcast the custom boxed error to `E`.
564 ///
565 /// If this [`Error`] contains a custom boxed error,
566 /// then it would attempt downcasting on the boxed error,
567 /// otherwise it will return [`Err`].
568 ///
569 /// If the custom boxed error has the same type as `E`, it will return [`Ok`],
570 /// otherwise it will also return [`Err`].
571 ///
572 /// This method is meant to be a convenience routine for calling
573 /// `Box<dyn Error + Sync + Send>::downcast` on the custom boxed error, returned by
574 /// [`Error::into_inner`].
575 ///
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// use std::fmt;
581 /// use std::io;
582 /// use std::error::Error;
583 ///
584 /// #[derive(Debug)]
585 /// enum E {
586 /// Io(io::Error),
587 /// SomeOtherVariant,
588 /// }
589 ///
590 /// impl fmt::Display for E {
591 /// // ...
592 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593 /// # todo!()
594 /// # }
595 /// }
596 /// impl Error for E {}
597 ///
598 /// impl From<io::Error> for E {
599 /// fn from(err: io::Error) -> E {
600 /// err.downcast::<E>()
601 /// .unwrap_or_else(E::Io)
602 /// }
603 /// }
604 ///
605 /// impl From<E> for io::Error {
606 /// fn from(err: E) -> io::Error {
607 /// match err {
608 /// E::Io(io_error) => io_error,
609 /// e => io::Error::new(io::ErrorKind::Other, e),
610 /// }
611 /// }
612 /// }
613 ///
614 /// # fn main() {
615 /// let e = E::SomeOtherVariant;
616 /// // Convert it to an io::Error
617 /// let io_error = io::Error::from(e);
618 /// // Cast it back to the original variant
619 /// let e = E::from(io_error);
620 /// assert!(matches!(e, E::SomeOtherVariant));
621 ///
622 /// let io_error = io::Error::from(io::ErrorKind::AlreadyExists);
623 /// // Convert it to E
624 /// let e = E::from(io_error);
625 /// // Cast it back to the original variant
626 /// let io_error = io::Error::from(e);
627 /// assert_eq!(io_error.kind(), io::ErrorKind::AlreadyExists);
628 /// assert!(io_error.get_ref().is_none());
629 /// assert!(io_error.raw_os_error().is_none());
630 /// # }
631 /// ```
632 #[stable(feature = "io_error_downcast", since = "1.79.0")]
633 pub fn downcast<E>(self) -> result::Result<E, Self>
634 where
635 E: error::Error + Send + Sync + 'static,
636 {
637 if let ErrorData::Custom(c) = self.repr.data()
638 && c.error.is::<E>()
639 {
640 if let ErrorData::Custom(b) = self.repr.into_data()
641 && let Ok(err) = b.error.downcast::<E>()
642 {
643 Ok(*err)
644 } else {
645 // Safety: We have just checked that the condition is true
646 unsafe { crate::hint::unreachable_unchecked() }
647 }
648 } else {
649 Err(self)
650 }
651 }
652
653 /// Returns the corresponding [`ErrorKind`] for this error.
654 ///
655 /// This may be a value set by Rust code constructing custom `io::Error`s,
656 /// or if this `io::Error` was sourced from the operating system,
657 /// it will be a value inferred from the system's error encoding.
658 /// See [`last_os_error`] for more details.
659 ///
660 /// [`last_os_error`]: Error::last_os_error
661 ///
662 /// # Examples
663 ///
664 /// ```
665 /// use std::io::{Error, ErrorKind};
666 ///
667 /// fn print_error(err: Error) {
668 /// println!("{:?}", err.kind());
669 /// }
670 ///
671 /// fn main() {
672 /// // As no error has (visibly) occurred, this may print anything!
673 /// // It likely prints a placeholder for unidentified (non-)errors.
674 /// print_error(Error::last_os_error());
675 /// // Will print "AddrInUse".
676 /// print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
677 /// }
678 /// ```
679 #[stable(feature = "rust1", since = "1.0.0")]
680 #[must_use]
681 #[inline]
682 pub fn kind(&self) -> ErrorKind {
683 match self.repr.data() {
684 ErrorData::Os(code) => sys::io::decode_error_kind(code),
685 ErrorData::Custom(c) => c.kind,
686 ErrorData::Simple(kind) => kind,
687 ErrorData::SimpleMessage(m) => m.kind,
688 }
689 }
690
691 #[inline]
692 pub(crate) fn is_interrupted(&self) -> bool {
693 match self.repr.data() {
694 ErrorData::Os(code) => sys::io::is_interrupted(code),
695 ErrorData::Custom(c) => c.kind == ErrorKind::Interrupted,
696 ErrorData::Simple(kind) => kind == ErrorKind::Interrupted,
697 ErrorData::SimpleMessage(m) => m.kind == ErrorKind::Interrupted,
698 }
699 }
700}
701
702impl fmt::Debug for Repr {
703 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
704 match self.data() {
705 ErrorData::Os(code) => fmt
706 .debug_struct("Os")
707 .field("code", &code)
708 .field("kind", &sys::io::decode_error_kind(code))
709 .field("message", &sys::io::error_string(code))
710 .finish(),
711 ErrorData::Custom(c) => fmt::Debug::fmt(&c, fmt),
712 ErrorData::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
713 ErrorData::SimpleMessage(msg) => fmt
714 .debug_struct("Error")
715 .field("kind", &msg.kind)
716 .field("message", &msg.message)
717 .finish(),
718 }
719 }
720}
721
722#[stable(feature = "rust1", since = "1.0.0")]
723impl fmt::Display for Error {
724 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
725 match self.repr.data() {
726 ErrorData::Os(code) => {
727 let detail = sys::io::error_string(code);
728 write!(fmt, "{detail} (os error {code})")
729 }
730 ErrorData::Custom(ref c) => c.error.fmt(fmt),
731 ErrorData::Simple(kind) => kind.fmt(fmt),
732 ErrorData::SimpleMessage(msg) => msg.message.fmt(fmt),
733 }
734 }
735}
736
737#[stable(feature = "rust1", since = "1.0.0")]
738impl error::Error for Error {
739 #[allow(deprecated)]
740 fn cause(&self) -> Option<&dyn error::Error> {
741 match self.repr.data() {
742 ErrorData::Os(..) => None,
743 ErrorData::Simple(..) => None,
744 ErrorData::SimpleMessage(..) => None,
745 ErrorData::Custom(c) => c.error.cause(),
746 }
747 }
748
749 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
750 match self.repr.data() {
751 ErrorData::Os(..) => None,
752 ErrorData::Simple(..) => None,
753 ErrorData::SimpleMessage(..) => None,
754 ErrorData::Custom(c) => c.error.source(),
755 }
756 }
757}
758
759fn _assert_error_is_sync_send() {
760 fn _is_sync_send<T: Sync + Send>() {}
761 _is_sync_send::<Error>();
762}