custom_print/macros/
printlike.rs

1/// Defines a `print`-like macro with a given name that uses
2/// specified write macro, error-handling policy and writer.
3///
4/// The writer itself is specified by the rest arguments with the [`define_writer`] macros.
5///
6/// # Examples
7///
8/// ```rust
9/// let mut string = String::new();
10/// custom_print::define_printlike!(cprintln, writeln, expect, fmt, |value: &str| string += value);
11/// custom_print::define_printlike!(try_println, writeln, try, fmt, |value: &str| string += value);
12///
13/// assert_eq!(cprintln!("first"), ());
14/// assert_eq!(string, "first\n");
15/// assert_eq!(try_println!("second"), Ok(()));
16/// assert_eq!(string, "first\nsecond\n");
17/// ```
18///
19/// [`define_writer`]: macro.define_writer.html
20#[macro_export]
21macro_rules! define_printlike {
22    (
23        $( #[$meta:meta] )*
24        $name:ident,
25        $macro:path,
26        expect,
27        $( $args:tt )*
28    ) => {
29        $crate::_define_printlike_impl!(
30            ($),
31            $( #[$meta] )*,
32            $name,
33            $macro,
34            expect,
35            $crate::define_writer!($($args)*)
36        );
37    };
38    (
39        $( #[$meta:meta] )*
40        $name:ident,
41        $macro:path,
42        try,
43        $( $args:tt )*
44    ) => {
45        $crate::_define_printlike_impl!(
46            ($),
47            $( #[$meta] )*,
48            $name,
49            $macro,
50            try,
51            $crate::define_try_writer!($($args)*)
52        );
53    };
54}
55
56#[doc(hidden)]
57#[macro_export]
58macro_rules! _define_printlike_impl {
59    (
60        ($d:tt),
61        $( #[$meta:meta] )*,
62        $name:ident,
63        $macro:path,
64        $handler:tt,
65        $( $writer:tt )*
66    ) => {
67        $( #[$meta] )*
68        #[allow(unused_macros)]
69        macro_rules! $name {
70            // Dummy comment below is used to avoid rustfmt formatting bug.
71            // Issue: https://github.com/rust-lang/rustfmt/issues/4609
72            /* ================================================================================== */
73            () => {
74                $crate::write!($macro, $( $writer )*, $handler)
75            };
76            ($d ($d args:tt)+) => {
77                $crate::write!($macro, $( $writer )*, $handler, $d ($d args)+)
78            };
79        }
80    };
81}