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
/// Assure a condition is true.
///
/// If true, then return Ok(true).
///
/// Otherwise, return Err(std::io::Error …).
///
/// This macro has a second form, where a custom
/// message can be provided.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate assure; fn main() {
/// assure_io!(true);
/// assure_io!(true, "message");
/// # }
/// ```
#[macro_export]
macro_rules! assure_io {
    ($x:expr $(,)?) => ({
        if ($x) {
            Ok(true)
        } else {
            Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "assure_io"))
        }
    });
    ($x:expr, $($arg:tt)+) => ({
        if ($x) {
            Ok(true)
        } else {
            Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, $($arg)+))
        }
    });
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_assure_io_x_arity_2_return_ok() {
        let x = assure_io!(true);
        assert_eq!(x.unwrap(), true);
    } 

    #[test]
    fn test_assure_io_x_arity_3_return_ok() {
        let x = assure_io!(true, "message");
        assert_eq!(x.unwrap(), true);
    } 

    #[test]
    fn test_assure_io_x_arity_2_return_err() {
        let x = assure_io!(false);
        assert!(x.is_err());
    } 

    #[test]
    fn test_assure_io_x_arity_3_return_err() {
        let x = assure_io!(false, "message");
        assert!(x.is_err());
    } 

}