]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/error.rs
Auto merge of #75687 - TimDiekmann:realloc-align, r=Amanieu
[rust.git] / library / std / src / io / error.rs
1 use crate::convert::From;
2 use crate::error;
3 use crate::fmt;
4 use crate::result;
5 use crate::sys;
6
7 /// A specialized [`Result`] type for I/O operations.
8 ///
9 /// This type is broadly used across [`std::io`] for any operation which may
10 /// produce an error.
11 ///
12 /// This typedef is generally used to avoid writing out [`io::Error`] directly and
13 /// is otherwise a direct mapping to [`Result`].
14 ///
15 /// While usual Rust style is to import types directly, aliases of [`Result`]
16 /// often are not, to make it easier to distinguish between them. [`Result`] is
17 /// generally assumed to be [`std::result::Result`][`Result`], and so users of this alias
18 /// will generally use `io::Result` instead of shadowing the [prelude]'s import
19 /// of [`std::result::Result`][`Result`].
20 ///
21 /// [`std::io`]: crate::io
22 /// [`io::Error`]: Error
23 /// [`Result`]: crate::result::Result
24 /// [prelude]: crate::prelude
25 ///
26 /// # Examples
27 ///
28 /// A convenience function that bubbles an `io::Result` to its caller:
29 ///
30 /// ```
31 /// use std::io;
32 ///
33 /// fn get_string() -> io::Result<String> {
34 ///     let mut buffer = String::new();
35 ///
36 ///     io::stdin().read_line(&mut buffer)?;
37 ///
38 ///     Ok(buffer)
39 /// }
40 /// ```
41 #[stable(feature = "rust1", since = "1.0.0")]
42 pub type Result<T> = result::Result<T, Error>;
43
44 /// The error type for I/O operations of the [`Read`], [`Write`], [`Seek`], and
45 /// associated traits.
46 ///
47 /// Errors mostly originate from the underlying OS, but custom instances of
48 /// `Error` can be created with crafted error messages and a particular value of
49 /// [`ErrorKind`].
50 ///
51 /// [`Read`]: crate::io::Read
52 /// [`Write`]: crate::io::Write
53 /// [`Seek`]: crate::io::Seek
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub struct Error {
56     repr: Repr,
57 }
58
59 #[stable(feature = "rust1", since = "1.0.0")]
60 impl fmt::Debug for Error {
61     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62         fmt::Debug::fmt(&self.repr, f)
63     }
64 }
65
66 enum Repr {
67     Os(i32),
68     Simple(ErrorKind),
69     Custom(Box<Custom>),
70 }
71
72 #[derive(Debug)]
73 struct Custom {
74     kind: ErrorKind,
75     error: Box<dyn error::Error + Send + Sync>,
76 }
77
78 /// A list specifying general categories of I/O error.
79 ///
80 /// This list is intended to grow over time and it is not recommended to
81 /// exhaustively match against it.
82 ///
83 /// It is used with the [`io::Error`] type.
84 ///
85 /// [`io::Error`]: Error
86 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
87 #[stable(feature = "rust1", since = "1.0.0")]
88 #[allow(deprecated)]
89 #[non_exhaustive]
90 pub enum ErrorKind {
91     /// An entity was not found, often a file.
92     #[stable(feature = "rust1", since = "1.0.0")]
93     NotFound,
94     /// The operation lacked the necessary privileges to complete.
95     #[stable(feature = "rust1", since = "1.0.0")]
96     PermissionDenied,
97     /// The connection was refused by the remote server.
98     #[stable(feature = "rust1", since = "1.0.0")]
99     ConnectionRefused,
100     /// The connection was reset by the remote server.
101     #[stable(feature = "rust1", since = "1.0.0")]
102     ConnectionReset,
103     /// The connection was aborted (terminated) by the remote server.
104     #[stable(feature = "rust1", since = "1.0.0")]
105     ConnectionAborted,
106     /// The network operation failed because it was not connected yet.
107     #[stable(feature = "rust1", since = "1.0.0")]
108     NotConnected,
109     /// A socket address could not be bound because the address is already in
110     /// use elsewhere.
111     #[stable(feature = "rust1", since = "1.0.0")]
112     AddrInUse,
113     /// A nonexistent interface was requested or the requested address was not
114     /// local.
115     #[stable(feature = "rust1", since = "1.0.0")]
116     AddrNotAvailable,
117     /// The operation failed because a pipe was closed.
118     #[stable(feature = "rust1", since = "1.0.0")]
119     BrokenPipe,
120     /// An entity already exists, often a file.
121     #[stable(feature = "rust1", since = "1.0.0")]
122     AlreadyExists,
123     /// The operation needs to block to complete, but the blocking operation was
124     /// requested to not occur.
125     #[stable(feature = "rust1", since = "1.0.0")]
126     WouldBlock,
127     /// A parameter was incorrect.
128     #[stable(feature = "rust1", since = "1.0.0")]
129     InvalidInput,
130     /// Data not valid for the operation were encountered.
131     ///
132     /// Unlike [`InvalidInput`], this typically means that the operation
133     /// parameters were valid, however the error was caused by malformed
134     /// input data.
135     ///
136     /// For example, a function that reads a file into a string will error with
137     /// `InvalidData` if the file's contents are not valid UTF-8.
138     ///
139     /// [`InvalidInput`]: ErrorKind::InvalidInput
140     #[stable(feature = "io_invalid_data", since = "1.2.0")]
141     InvalidData,
142     /// The I/O operation's timeout expired, causing it to be canceled.
143     #[stable(feature = "rust1", since = "1.0.0")]
144     TimedOut,
145     /// An error returned when an operation could not be completed because a
146     /// call to [`write`] returned [`Ok(0)`].
147     ///
148     /// This typically means that an operation could only succeed if it wrote a
149     /// particular number of bytes but only a smaller number of bytes could be
150     /// written.
151     ///
152     /// [`write`]: crate::io::Write::write
153     /// [`Ok(0)`]: Ok
154     #[stable(feature = "rust1", since = "1.0.0")]
155     WriteZero,
156     /// This operation was interrupted.
157     ///
158     /// Interrupted operations can typically be retried.
159     #[stable(feature = "rust1", since = "1.0.0")]
160     Interrupted,
161     /// Any I/O error not part of this list.
162     ///
163     /// Errors that are `Other` now may move to a different or a new
164     /// [`ErrorKind`] variant in the future. It is not recommended to match
165     /// an error against `Other` and to expect any additional characteristics,
166     /// e.g., a specific [`Error::raw_os_error`] return value.
167     #[stable(feature = "rust1", since = "1.0.0")]
168     Other,
169
170     /// An error returned when an operation could not be completed because an
171     /// "end of file" was reached prematurely.
172     ///
173     /// This typically means that an operation could only succeed if it read a
174     /// particular number of bytes but only a smaller number of bytes could be
175     /// read.
176     #[stable(feature = "read_exact", since = "1.6.0")]
177     UnexpectedEof,
178 }
179
180 impl ErrorKind {
181     pub(crate) fn as_str(&self) -> &'static str {
182         match *self {
183             ErrorKind::NotFound => "entity not found",
184             ErrorKind::PermissionDenied => "permission denied",
185             ErrorKind::ConnectionRefused => "connection refused",
186             ErrorKind::ConnectionReset => "connection reset",
187             ErrorKind::ConnectionAborted => "connection aborted",
188             ErrorKind::NotConnected => "not connected",
189             ErrorKind::AddrInUse => "address in use",
190             ErrorKind::AddrNotAvailable => "address not available",
191             ErrorKind::BrokenPipe => "broken pipe",
192             ErrorKind::AlreadyExists => "entity already exists",
193             ErrorKind::WouldBlock => "operation would block",
194             ErrorKind::InvalidInput => "invalid input parameter",
195             ErrorKind::InvalidData => "invalid data",
196             ErrorKind::TimedOut => "timed out",
197             ErrorKind::WriteZero => "write zero",
198             ErrorKind::Interrupted => "operation interrupted",
199             ErrorKind::Other => "other os error",
200             ErrorKind::UnexpectedEof => "unexpected end of file",
201         }
202     }
203 }
204
205 /// Intended for use for errors not exposed to the user, where allocating onto
206 /// the heap (for normal construction via Error::new) is too costly.
207 #[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
208 impl From<ErrorKind> for Error {
209     /// Converts an [`ErrorKind`] into an [`Error`].
210     ///
211     /// This conversion allocates a new error with a simple representation of error kind.
212     ///
213     /// # Examples
214     ///
215     /// ```
216     /// use std::io::{Error, ErrorKind};
217     ///
218     /// let not_found = ErrorKind::NotFound;
219     /// let error = Error::from(not_found);
220     /// assert_eq!("entity not found", format!("{}", error));
221     /// ```
222     #[inline]
223     fn from(kind: ErrorKind) -> Error {
224         Error { repr: Repr::Simple(kind) }
225     }
226 }
227
228 impl Error {
229     /// Creates a new I/O error from a known kind of error as well as an
230     /// arbitrary error payload.
231     ///
232     /// This function is used to generically create I/O errors which do not
233     /// originate from the OS itself. The `error` argument is an arbitrary
234     /// payload which will be contained in this [`Error`].
235     ///
236     /// # Examples
237     ///
238     /// ```
239     /// use std::io::{Error, ErrorKind};
240     ///
241     /// // errors can be created from strings
242     /// let custom_error = Error::new(ErrorKind::Other, "oh no!");
243     ///
244     /// // errors can also be created from other errors
245     /// let custom_error2 = Error::new(ErrorKind::Interrupted, custom_error);
246     /// ```
247     #[stable(feature = "rust1", since = "1.0.0")]
248     pub fn new<E>(kind: ErrorKind, error: E) -> Error
249     where
250         E: Into<Box<dyn error::Error + Send + Sync>>,
251     {
252         Self::_new(kind, error.into())
253     }
254
255     fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
256         Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
257     }
258
259     /// Returns an error representing the last OS error which occurred.
260     ///
261     /// This function reads the value of `errno` for the target platform (e.g.
262     /// `GetLastError` on Windows) and will return a corresponding instance of
263     /// [`Error`] for the error code.
264     ///
265     /// # Examples
266     ///
267     /// ```
268     /// use std::io::Error;
269     ///
270     /// println!("last OS error: {:?}", Error::last_os_error());
271     /// ```
272     #[stable(feature = "rust1", since = "1.0.0")]
273     pub fn last_os_error() -> Error {
274         Error::from_raw_os_error(sys::os::errno() as i32)
275     }
276
277     /// Creates a new instance of an [`Error`] from a particular OS error code.
278     ///
279     /// # Examples
280     ///
281     /// On Linux:
282     ///
283     /// ```
284     /// # if cfg!(target_os = "linux") {
285     /// use std::io;
286     ///
287     /// let error = io::Error::from_raw_os_error(22);
288     /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
289     /// # }
290     /// ```
291     ///
292     /// On Windows:
293     ///
294     /// ```
295     /// # if cfg!(windows) {
296     /// use std::io;
297     ///
298     /// let error = io::Error::from_raw_os_error(10022);
299     /// assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
300     /// # }
301     /// ```
302     #[stable(feature = "rust1", since = "1.0.0")]
303     pub fn from_raw_os_error(code: i32) -> Error {
304         Error { repr: Repr::Os(code) }
305     }
306
307     /// Returns the OS error that this error represents (if any).
308     ///
309     /// If this [`Error`] was constructed via [`last_os_error`] or
310     /// [`from_raw_os_error`], then this function will return [`Some`], otherwise
311     /// it will return [`None`].
312     ///
313     /// [`last_os_error`]: Error::last_os_error
314     /// [`from_raw_os_error`]: Error::from_raw_os_error
315     ///
316     /// # Examples
317     ///
318     /// ```
319     /// use std::io::{Error, ErrorKind};
320     ///
321     /// fn print_os_error(err: &Error) {
322     ///     if let Some(raw_os_err) = err.raw_os_error() {
323     ///         println!("raw OS error: {:?}", raw_os_err);
324     ///     } else {
325     ///         println!("Not an OS error");
326     ///     }
327     /// }
328     ///
329     /// fn main() {
330     ///     // Will print "raw OS error: ...".
331     ///     print_os_error(&Error::last_os_error());
332     ///     // Will print "Not an OS error".
333     ///     print_os_error(&Error::new(ErrorKind::Other, "oh no!"));
334     /// }
335     /// ```
336     #[stable(feature = "rust1", since = "1.0.0")]
337     pub fn raw_os_error(&self) -> Option<i32> {
338         match self.repr {
339             Repr::Os(i) => Some(i),
340             Repr::Custom(..) => None,
341             Repr::Simple(..) => None,
342         }
343     }
344
345     /// Returns a reference to the inner error wrapped by this error (if any).
346     ///
347     /// If this [`Error`] was constructed via [`new`] then this function will
348     /// return [`Some`], otherwise it will return [`None`].
349     ///
350     /// [`new`]: Error::new
351     ///
352     /// # Examples
353     ///
354     /// ```
355     /// use std::io::{Error, ErrorKind};
356     ///
357     /// fn print_error(err: &Error) {
358     ///     if let Some(inner_err) = err.get_ref() {
359     ///         println!("Inner error: {:?}", inner_err);
360     ///     } else {
361     ///         println!("No inner error");
362     ///     }
363     /// }
364     ///
365     /// fn main() {
366     ///     // Will print "No inner error".
367     ///     print_error(&Error::last_os_error());
368     ///     // Will print "Inner error: ...".
369     ///     print_error(&Error::new(ErrorKind::Other, "oh no!"));
370     /// }
371     /// ```
372     #[stable(feature = "io_error_inner", since = "1.3.0")]
373     pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
374         match self.repr {
375             Repr::Os(..) => None,
376             Repr::Simple(..) => None,
377             Repr::Custom(ref c) => Some(&*c.error),
378         }
379     }
380
381     /// Returns a mutable reference to the inner error wrapped by this error
382     /// (if any).
383     ///
384     /// If this [`Error`] was constructed via [`new`] then this function will
385     /// return [`Some`], otherwise it will return [`None`].
386     ///
387     /// [`new`]: Error::new
388     ///
389     /// # Examples
390     ///
391     /// ```
392     /// use std::io::{Error, ErrorKind};
393     /// use std::{error, fmt};
394     /// use std::fmt::Display;
395     ///
396     /// #[derive(Debug)]
397     /// struct MyError {
398     ///     v: String,
399     /// }
400     ///
401     /// impl MyError {
402     ///     fn new() -> MyError {
403     ///         MyError {
404     ///             v: "oh no!".to_string()
405     ///         }
406     ///     }
407     ///
408     ///     fn change_message(&mut self, new_message: &str) {
409     ///         self.v = new_message.to_string();
410     ///     }
411     /// }
412     ///
413     /// impl error::Error for MyError {}
414     ///
415     /// impl Display for MyError {
416     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417     ///         write!(f, "MyError: {}", &self.v)
418     ///     }
419     /// }
420     ///
421     /// fn change_error(mut err: Error) -> Error {
422     ///     if let Some(inner_err) = err.get_mut() {
423     ///         inner_err.downcast_mut::<MyError>().unwrap().change_message("I've been changed!");
424     ///     }
425     ///     err
426     /// }
427     ///
428     /// fn print_error(err: &Error) {
429     ///     if let Some(inner_err) = err.get_ref() {
430     ///         println!("Inner error: {}", inner_err);
431     ///     } else {
432     ///         println!("No inner error");
433     ///     }
434     /// }
435     ///
436     /// fn main() {
437     ///     // Will print "No inner error".
438     ///     print_error(&change_error(Error::last_os_error()));
439     ///     // Will print "Inner error: ...".
440     ///     print_error(&change_error(Error::new(ErrorKind::Other, MyError::new())));
441     /// }
442     /// ```
443     #[stable(feature = "io_error_inner", since = "1.3.0")]
444     pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'static)> {
445         match self.repr {
446             Repr::Os(..) => None,
447             Repr::Simple(..) => None,
448             Repr::Custom(ref mut c) => Some(&mut *c.error),
449         }
450     }
451
452     /// Consumes the `Error`, returning its inner error (if any).
453     ///
454     /// If this [`Error`] was constructed via [`new`] then this function will
455     /// return [`Some`], otherwise it will return [`None`].
456     ///
457     /// [`new`]: Error::new
458     ///
459     /// # Examples
460     ///
461     /// ```
462     /// use std::io::{Error, ErrorKind};
463     ///
464     /// fn print_error(err: Error) {
465     ///     if let Some(inner_err) = err.into_inner() {
466     ///         println!("Inner error: {}", inner_err);
467     ///     } else {
468     ///         println!("No inner error");
469     ///     }
470     /// }
471     ///
472     /// fn main() {
473     ///     // Will print "No inner error".
474     ///     print_error(Error::last_os_error());
475     ///     // Will print "Inner error: ...".
476     ///     print_error(Error::new(ErrorKind::Other, "oh no!"));
477     /// }
478     /// ```
479     #[stable(feature = "io_error_inner", since = "1.3.0")]
480     pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
481         match self.repr {
482             Repr::Os(..) => None,
483             Repr::Simple(..) => None,
484             Repr::Custom(c) => Some(c.error),
485         }
486     }
487
488     /// Returns the corresponding [`ErrorKind`] for this error.
489     ///
490     /// # Examples
491     ///
492     /// ```
493     /// use std::io::{Error, ErrorKind};
494     ///
495     /// fn print_error(err: Error) {
496     ///     println!("{:?}", err.kind());
497     /// }
498     ///
499     /// fn main() {
500     ///     // Will print "Other".
501     ///     print_error(Error::last_os_error());
502     ///     // Will print "AddrInUse".
503     ///     print_error(Error::new(ErrorKind::AddrInUse, "oh no!"));
504     /// }
505     /// ```
506     #[stable(feature = "rust1", since = "1.0.0")]
507     pub fn kind(&self) -> ErrorKind {
508         match self.repr {
509             Repr::Os(code) => sys::decode_error_kind(code),
510             Repr::Custom(ref c) => c.kind,
511             Repr::Simple(kind) => kind,
512         }
513     }
514 }
515
516 impl fmt::Debug for Repr {
517     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
518         match *self {
519             Repr::Os(code) => fmt
520                 .debug_struct("Os")
521                 .field("code", &code)
522                 .field("kind", &sys::decode_error_kind(code))
523                 .field("message", &sys::os::error_string(code))
524                 .finish(),
525             Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
526             Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
527         }
528     }
529 }
530
531 #[stable(feature = "rust1", since = "1.0.0")]
532 impl fmt::Display for Error {
533     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
534         match self.repr {
535             Repr::Os(code) => {
536                 let detail = sys::os::error_string(code);
537                 write!(fmt, "{} (os error {})", detail, code)
538             }
539             Repr::Custom(ref c) => c.error.fmt(fmt),
540             Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
541         }
542     }
543 }
544
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl error::Error for Error {
547     #[allow(deprecated, deprecated_in_future)]
548     fn description(&self) -> &str {
549         match self.repr {
550             Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
551             Repr::Custom(ref c) => c.error.description(),
552         }
553     }
554
555     #[allow(deprecated)]
556     fn cause(&self) -> Option<&dyn error::Error> {
557         match self.repr {
558             Repr::Os(..) => None,
559             Repr::Simple(..) => None,
560             Repr::Custom(ref c) => c.error.cause(),
561         }
562     }
563
564     fn source(&self) -> Option<&(dyn error::Error + 'static)> {
565         match self.repr {
566             Repr::Os(..) => None,
567             Repr::Simple(..) => None,
568             Repr::Custom(ref c) => c.error.source(),
569         }
570     }
571 }
572
573 fn _assert_error_is_sync_send() {
574     fn _is_sync_send<T: Sync + Send>() {}
575     _is_sync_send::<Error>();
576 }
577
578 #[cfg(test)]
579 mod test {
580     use super::{Custom, Error, ErrorKind, Repr};
581     use crate::error;
582     use crate::fmt;
583     use crate::sys::decode_error_kind;
584     use crate::sys::os::error_string;
585
586     #[test]
587     fn test_debug_error() {
588         let code = 6;
589         let msg = error_string(code);
590         let kind = decode_error_kind(code);
591         let err = Error {
592             repr: Repr::Custom(box Custom {
593                 kind: ErrorKind::InvalidInput,
594                 error: box Error { repr: super::Repr::Os(code) },
595             }),
596         };
597         let expected = format!(
598             "Custom {{ \
599              kind: InvalidInput, \
600              error: Os {{ \
601              code: {:?}, \
602              kind: {:?}, \
603              message: {:?} \
604              }} \
605              }}",
606             code, kind, msg
607         );
608         assert_eq!(format!("{:?}", err), expected);
609     }
610
611     #[test]
612     fn test_downcasting() {
613         #[derive(Debug)]
614         struct TestError;
615
616         impl fmt::Display for TestError {
617             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618                 f.write_str("asdf")
619             }
620         }
621
622         impl error::Error for TestError {}
623
624         // we have to call all of these UFCS style right now since method
625         // resolution won't implicitly drop the Send+Sync bounds
626         let mut err = Error::new(ErrorKind::Other, TestError);
627         assert!(err.get_ref().unwrap().is::<TestError>());
628         assert_eq!("asdf", err.get_ref().unwrap().to_string());
629         assert!(err.get_mut().unwrap().is::<TestError>());
630         let extracted = err.into_inner().unwrap();
631         extracted.downcast::<TestError>().unwrap();
632     }
633 }