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