stdx/
macros.rs

1//! Convenience macros.
2
3/// Appends formatted string to a `String`.
4#[macro_export]
5macro_rules! format_to {
6    ($buf:expr) => ();
7    ($buf:expr, $lit:literal $($arg:tt)*) => {
8        {
9            use ::std::fmt::Write as _;
10            // We can't do ::std::fmt::Write::write_fmt($buf, format_args!($lit $($arg)*))
11            // unfortunately, as that loses out on autoref behavior.
12            _ = $buf.write_fmt(format_args!($lit $($arg)*))
13        }
14    };
15}
16
17/// Appends formatted string to a `String` and returns the `String`.
18///
19/// Useful for folding iterators into a `String`.
20#[macro_export]
21macro_rules! format_to_acc {
22    ($buf:expr, $lit:literal $($arg:tt)*) => {
23        {
24            use ::std::fmt::Write as _;
25            // We can't do ::std::fmt::Write::write_fmt($buf, format_args!($lit $($arg)*))
26            // unfortunately, as that loses out on autoref behavior.
27            _ = $buf.write_fmt(format_args!($lit $($arg)*));
28            $buf
29        }
30    };
31}
32
33/// Generates `From` impls for `Enum E { Foo(Foo), Bar(Bar) }` enums
34///
35/// # Example
36///
37/// ```ignore
38/// impl_from!(Struct, Union, Enum for Adt);
39/// ```
40#[macro_export]
41macro_rules! impl_from {
42    ($($variant:ident $(($($sub_variant:ident),*))?),* for $enum:ident) => {
43        $(
44            impl From<$variant> for $enum {
45                fn from(it: $variant) -> $enum {
46                    $enum::$variant(it)
47                }
48            }
49            $($(
50                impl From<$sub_variant> for $enum {
51                    fn from(it: $sub_variant) -> $enum {
52                        $enum::$variant($variant::$sub_variant(it))
53                    }
54                }
55            )*)?
56        )*
57    };
58    ($($variant:ident$(<$V:ident>)?),* for $enum:ident) => {
59        $(
60            impl$(<$V>)? From<$variant$(<$V>)?> for $enum$(<$V>)? {
61                fn from(it: $variant$(<$V>)?) -> $enum$(<$V>)? {
62                    $enum::$variant(it)
63                }
64            }
65        )*
66    }
67}