bool_mappings/
lib.rs

1//! Useful extensions to convert `bool` to other Rust types.
2//!
3//! At the moment there are two extensions:
4//!
5//! - `.true_or()`
6//! - `.false_or()`
7//!
8//! # Examples
9//!
10//! ```
11//! use bool_mappings::BoolMappings;
12//! 
13//! struct MyError;
14//!
15//! // Turn a bool into a Result
16//! fn some_fn() -> Result<(), MyError> {
17//!     true.true_or(MyError)
18//! }
19//!
20//! fn some_other_fn() -> Result<(), MyError> {
21//!     true.false_or(MyError)
22//! }
23//! ```
24
25/// This extension trait adds additional methods to `bool`s
26pub trait BoolMappings {
27    fn true_or<T>(&self, err: T) -> Result<(), T>;
28    fn false_or<T>(&self, err: T) -> Result<(), T>;
29}
30
31/// This is the impl of the extension trait
32impl BoolMappings for bool {
33    /// Convert a `bool` into a `Result<(),T>`
34    fn true_or<T>(&self, err: T) -> Result<(), T> {
35        self.then_some(()).ok_or::<T>(err)
36    }
37    /// Convert a `bool` into a `Result<(),T>`
38    fn false_or<T>(&self, err: T) -> Result<(), T> {
39        (!self).then_some(()).ok_or::<T>(err)
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::BoolMappings;
46    use std::fmt::*;
47
48    #[derive(Debug, PartialEq, Eq)]
49    struct MyError;
50
51    impl Display for MyError {
52        fn fmt(&self, f: &mut Formatter<'_>) -> Result {
53            write!(f, "MyError")
54        }
55    }
56
57    impl std::error::Error for MyError {}
58
59    #[test]
60    fn test_true_or_for_true() {
61        assert!(true.true_or(MyError).is_ok())
62    }
63
64    #[test]
65    fn test_true_or_for_false() {
66        assert_eq!(false.true_or(MyError).err().unwrap(), MyError);
67    }
68
69    #[test]
70    fn test_false_or_for_false() {
71        assert!(false.false_or(MyError).is_ok())
72    }
73
74    #[test]
75    fn test_false_or_for_true() {
76        assert_eq!(true.false_or(MyError).err().unwrap(), MyError);
77    }
78}