1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/// A convenient way to create a new error using the normal formatting infrastructure
#[macro_export]
macro_rules! format_err {
    ($kind:expr, $msg:literal $(,)?) => {{
        // Handle $:literal as a special case to make cargo-expanded code more
        // concise in the common case.
        $crate::error::Error::message($kind, $msg)
    }};
    ($kind:expr, $msg:expr $(,)?) => {{
        $crate::error::Error::message($kind, $msg)
    }};
    ($kind:expr, $msg:expr, $($arg:tt)*) => {{
        $crate::error::Error::with_message($kind, || { format!($msg, $($arg)*) })
    }};
}

/// Return early with an error if a condition is not satisfied.
#[macro_export]
macro_rules! ensure {
    ($cond:expr, $kind:expr, $msg:literal $(,)?) => {
        if !$cond {
            return ::std::result::Result::Err($crate::format_err!($kind, $msg));
        }
    };
    ($cond:expr, $kind:expr, dicate $msg:expr $(,)?) => {
        if !$cond {
            return ::std::result::Result::Err($crate::format_err!($kind, $msg));
        }
    };
    ($cond:expr, $kind:expr, dicate $msg:expr, $($arg:tt)*) => {
        if !$cond {
            return ::std::result::Result::Err($crate::format_err!($kind, $msg, $($arg)*));
        }
    };
}

/// Return early with an error if two expressions are not equal to each other.
#[macro_export]
macro_rules! ensure_eq {
    ($left:expr, $right:expr, $kind:expr, $msg:literal $(,)?) => {
        $crate::ensure!($left == $right, $kind, $msg);
    };
    ($left:expr, $right:expr, $kind:expr, dicate $msg:expr $(,)?) => {
        $crate::ensure!($left == $right, $kind, $msg);
    };
    ($left:expr, $right:expr, $kind:expr, dicate $msg:expr, $($arg:tt)*) => {
        $crate::ensure!($left == $right, $kind, $msg, $($arg)*);
    };
}

/// Return early with an error if two expressions are equal to each other.
#[macro_export]
macro_rules! ensure_ne {
    ($left:expr, $right:expr, $kind:expr, $msg:literal $(,)?) => {
        $crate::ensure!($left != $right, $kind, $msg);
    };
    ($left:expr, $right:expr, $kind:expr, dicate $msg:expr $(,)?) => {
        $crate::ensure!($left != $right, $kind, $msg);
    };
    ($left:expr, $right:expr, $kind:expr, dicate $msg:expr, $($arg:tt)*) => {
        $crate::ensure!($left != $right, $kind, $msg, $($arg)*);
    };
}

#[cfg(test)]
mod tests {
    use super::super::*;

    #[derive(Debug, PartialEq, Copy, Clone)]
    struct OperationError;

    impl Display for OperationError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "OperationError")
        }
    }

    #[derive(thiserror::Error, Debug)]
    enum IntermediateError {
        #[error("second error")]
        Io(#[from] std::io::Error),
    }

    #[test]
    fn ensure_works() {
        fn test_ensure(predicate: bool) -> crate::Result<()> {
            ensure!(predicate, ErrorKind::Other, "predicate failed");
            Ok(())
        }

        fn test_ensure_eq(item1: &str, item2: &str) -> crate::Result<()> {
            ensure_eq!(item1, item2, ErrorKind::Other, "predicate failed");
            Ok(())
        }

        fn test_ensure_ne(item1: &str, item2: &str) -> crate::Result<()> {
            ensure_ne!(item1, item2, ErrorKind::Other, "predicate failed");
            Ok(())
        }

        let err = test_ensure(false).unwrap_err();
        assert_eq!(format!("{}", err), "predicate failed");
        assert_eq!(err.kind(), &ErrorKind::Other);

        assert!(test_ensure(true).is_ok());

        let err = test_ensure_eq("foo", "bar").unwrap_err();
        assert_eq!(format!("{}", err), "predicate failed");
        assert_eq!(err.kind(), &ErrorKind::Other);

        assert!(test_ensure_eq("foo", "foo").is_ok());

        let err = test_ensure_ne("foo", "foo").unwrap_err();
        assert_eq!(format!("{}", err), "predicate failed");
        assert_eq!(err.kind(), &ErrorKind::Other);

        assert!(test_ensure_ne("foo", "bar").is_ok());
    }
}