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