io_result_optional/
lib.rs

1//! Provides a trait for `std::io::Result` that adds a method making
2//! it easy to tell the difference between a file not found and
3//! another error, since a common practice is to handle a file if it
4//! exists.
5//!
6//! # Examples
7//! ````
8//! use io_result_optional::IoResultOptional;
9//! use std::fs::File;
10//! # use std::io;
11//!
12//! # fn readconfig(data: File) -> u8 {
13//! #     17
14//! # }
15//! # fn main() -> io::Result<()> {
16//! let config = File::open(".app.rc")
17//!     .optional()?
18//!     .map(readconfig)
19//!     .unwrap_or_default();
20//! # Ok(())
21//! # }
22//! ````
23//!
24//! ````
25//! use io_result_optional::IoResultOptional;
26//! use std::fs::File;
27//! # use std::io;
28//!
29//! # fn main() -> io::Result<()> {
30//! if let Some(input) = File::open("data").optional()? {
31//!     // The data exists, so handle it ...
32//!     // If it doesn't exist, it is just ignored
33//!     // If there is another error, this function returns it.
34//! }
35//! # Ok(())
36//! # }
37//! ````
38use std::io;
39
40/// A trait for [`io::Result`] that adds a method making it easy to
41/// tell the difference between a file not found and another error,
42/// since a common practice is to handle a file if it exists.
43pub trait IoResultOptional<T> {
44    /// Consider the given file access optional.
45    /// if the result is an error with [`io::ErrorKind`] `NotFound`, convert it to
46    /// `Ok(None)`.
47    /// If it is any other error, return it as-is,
48    /// and if it is `Ok(value)` convert it to `Ok(Some(value))`.
49    ///
50    /// # Examples
51    /// ````
52    /// use std::fs::File;
53    /// # use std::io;
54    /// use io_result_optional::IoResultOptional;
55    ///
56    /// # fn parseconfig(data: File) -> u8 {
57    /// #     17
58    /// # }
59    /// # fn main() -> io::Result<()> {
60    /// let config = File::open(".app.rc")
61    ///     .optional()?
62    ///     .map(parseconfig)
63    ///     .unwrap_or_default();
64    /// # Ok(())
65    /// # }
66    /// ````
67    fn optional(self) -> io::Result<Option<T>>;
68}
69
70impl<T> IoResultOptional<T> for io::Result<T> {
71    fn optional(self) -> io::Result<Option<T>> {
72        match self {
73            Ok(value) => Ok(Some(value)),
74            Err(ref e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
75            Err(e) => Err(e),
76        }
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use crate::IoResultOptional;
83    use std::fs::File;
84    use std::io;
85    use std::path::Path;
86
87    #[test]
88    fn existing_some() {
89        assert!(
90            File::open(&Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"))
91                .optional()
92                .unwrap()
93                .is_some()
94        )
95    }
96
97    #[test]
98    fn non_existing_none() {
99        assert!(
100            File::open(&Path::new(env!("CARGO_MANIFEST_DIR")).join("nosuch.file"))
101                .optional()
102                .unwrap()
103                .is_none()
104        )
105    }
106
107    #[test]
108    fn other_is_error() {
109        let result: io::Result<()> = Err(io::Error::new(io::ErrorKind::TimedOut, "too slow"));
110        assert_eq!(
111            format!("{:?}", result.optional()),
112            "Err(Custom { kind: TimedOut, error: StringError(\"too slow\") })",
113        )
114    }
115}