summaryrefslogtreecommitdiff
path: root/src/macros.rs
blob: b6f069b7110395583b191cb406081f018ff02d93 (plain) (blame)
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
//! Auxiliary macros.

/// Create trait implementations for an error type.
macro_rules! error_type {
    (
        $var:ident: $err:ident,
        $(res: $res:ident,)*
        show: $f:ident => $show:expr,
        $(source: $source:expr,)*
        $(from: ($from:path, $conv:expr),)*
    ) => {
        // Possibly create a result type.
        $(type $res<T> = std::result::Result<T, $err>;)*

        impl std::fmt::Display for $err {
            fn fmt(&self, $f: &mut std::fmt::Formatter) -> std::fmt::Result {
                #[allow(unused)]
                let $var = self;
                $show
            }
        }

        debug_display!($err);

        impl std::error::Error for $err {
            // The source method is only generated if an implementation was given.
            $(fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                #[allow(unused)]
                let $var = self;
                $source
            })*
        }

        // Create any number of from implementations.
        $(impl From<$from> for $err {
            fn from($var: $from) -> $err {
                $conv
            }
        })*
    };
}

/// Shorthand for checking whether an expression matches a pattern.
macro_rules! matches {
    ($expr:expr, $($pattern:tt)*) => {
        match $expr {
            $($pattern)* => true,
            _ => false,
        }
    };
}

/// Create a `Debug` implementation from a `Display` implementation.
macro_rules! debug_display {
    ($type:ident) => (
        impl std::fmt::Debug for $type {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                std::fmt::Display::fmt(self, f)
            }
        }
    );
    ($type:ident; $generics:tt where $($bounds:tt)*) => (
        impl<$generics> std::fmt::Debug for $type<$generics> where $($bounds)* {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                std::fmt::Display::fmt(self, f)
            }
        }
    );
}

/// Declare a module and reexport all its contents.
macro_rules! pub_use_mod {
    ($name:ident) => {
        mod $name;
        pub use $name::*;
    };
}