io_extra/lib.rs
1//! An extension trait for [`io::Error`], with shorthand constructors for various
2//! [`io::ErrorKind`]s, and a [`context()`] method.
3//!
4//! ```
5//! use std::{fs::File, io::{self, Write as _}, str};
6//! use io_extra::{IoErrorExt as _, context, with};
7//!
8//! fn write_log(contents: &[u8], mut file: File) -> io::Result<()> {
9//! if let Err(e) = str::from_utf8(contents) {
10//! return Err(io::Error::invalid_input("`contents` was not UTF-8"))
11//! // ^ shorthand constructor
12//! }
13//! file.write_all(contents).map_err(with("couldn't write file"))
14//! // ^ easily add context
15//! }
16//! ```
17use sealed::Sealed;
18use std::{
19 error::Error,
20 fmt,
21 io::{
22 self,
23 ErrorKind::{
24 AddrInUse, AddrNotAvailable, AlreadyExists, BrokenPipe, ConnectionAborted,
25 ConnectionRefused, ConnectionReset, Interrupted, InvalidData, InvalidInput,
26 NotConnected, NotFound, OutOfMemory, PermissionDenied, TimedOut, UnexpectedEof,
27 Unsupported, WouldBlock, WriteZero,
28 },
29 },
30};
31
32#[doc(inline)]
33pub use context::{context, with};
34
35mod context;
36
37mod sealed {
38 pub trait Sealed: Into<std::io::Error> {}
39}
40
41macro_rules! ctor {
42 ($($name:ident -> $kind:expr),* $(,)?) => {
43 $(
44 #[doc = concat!(
45 "Create an [`io::Error`] with kind [`",
46 stringify!($kind),
47 "`], wrapping the passed in `error`."
48 )]
49 fn $name(error: impl Into<Box<dyn Error + Send + Sync>>) -> io::Error {
50 io::Error::new($kind, error)
51 }
52 )*
53 };
54}
55
56/// An extension trait for [`io::Error`], with shorthand constructors for various
57/// [`io::ErrorKind`]s.
58///
59/// ```
60/// use std::io;
61/// use io_extra::IoErrorExt as _;
62///
63/// fn read_to_string(mut r: impl io::Read) -> io::Result<String> {
64/// let mut buf = vec![];
65/// r.read_to_end(&mut buf)?;
66/// String::from_utf8(buf).map_err(io::Error::invalid_data)
67/// }
68///
69/// fn check_magic_number(mut r: impl io::Read) -> io::Result<()> {
70/// let mut buf = [0; 2];
71/// r.read_exact(&mut buf)?;
72/// match buf == 0xDEAD_u16.to_le_bytes() {
73/// true => Ok(()),
74/// false => Err(io::Error::invalid_data("unrecognised format"))
75/// }
76/// }
77/// ```
78///
79/// This trait is _sealed_, and cannot be implemented by types outside this library.
80pub trait IoErrorExt: Sealed {
81 ctor! {
82 addr_in_use -> AddrInUse,
83 addr_not_available -> AddrNotAvailable,
84 already_exists -> AlreadyExists,
85 broken_pipe -> BrokenPipe,
86 connection_aborted -> ConnectionAborted,
87 connection_refused -> ConnectionRefused,
88 connection_reset -> ConnectionReset,
89 interrupted -> Interrupted,
90 invalid_data -> InvalidData,
91 invalid_input -> InvalidInput,
92 not_connected -> NotConnected,
93 not_found -> NotFound,
94 out_of_memory -> OutOfMemory,
95 permission_denied -> PermissionDenied,
96 timed_out -> TimedOut,
97 unexpected_eof -> UnexpectedEof,
98 unsupported -> Unsupported,
99 would_block -> WouldBlock,
100 write_zero -> WriteZero,
101 }
102 /// Attach a message to this error.
103 fn context(self, msg: impl fmt::Display) -> io::Error {
104 context(self.into(), msg)
105 }
106 /// Attach a message to this error.
107 ///
108 /// Provided with a different name to not conflict with [`anyhow::Context`].
109 ///
110 /// [`anyhow::Context`]: (https://docs.rs/anyhow/1/anyhow/trait.Context.html#method.context).
111 fn io_context(self, msg: impl fmt::Display) -> io::Error {
112 self.context(msg)
113 }
114}
115
116impl Sealed for io::Error {}
117impl IoErrorExt for io::Error {}