custom_print/macros/
dbglike.rs

1/// Defines a `dbg`-like macro with a given name that uses
2/// specified write macro, error-handling policy, format string and writer.
3///
4/// The implementation of the generated `dbg`-like macro
5/// is based on [`std::dbg`] macro implementation,
6/// but the exact output printed by [`std::dbg`]
7/// should not be relied upon and is subject to future changes.
8///
9/// If the `try` policy is used, it propagates write error and
10/// returns values wrapper into `Result`.
11///
12/// The writer itself is specified by the rest arguments with the [`define_writer`] macros.
13///
14/// # Examples
15///
16/// ```rust
17/// let mut string = String::new();
18/// custom_print::define_dbglike!(cdbg, writeln, expect, ":?", fmt, |value: &str| string += value);
19/// custom_print::define_dbglike!(try_dbg, writeln, try, ":?", fmt, |value: &str| string += value);
20///
21/// assert_eq!(cdbg!("first"), "first");
22/// assert!(string.contains("\"first\""));
23/// assert_eq!(try_dbg!("second"), Ok("second"));
24/// assert!(string.contains("\"second\""));
25/// ```
26///
27/// [`define_writer`]: macro.define_writer.html
28#[macro_export]
29macro_rules! define_dbglike {
30    (
31        $( #[$meta:meta] )*
32        $name:ident,
33        $macro:path,
34        expect,
35        $format:literal,
36        $($args:tt)*
37    ) => {
38        $crate::_define_dbglike_impl!(
39            ($),
40            $( #[$meta] )*,
41            $name,
42            $macro,
43            expect,
44            $format,
45            $crate::define_writer!($($args)*)
46        );
47    };
48    (
49        $( #[$meta:meta] )*
50        $name:ident,
51        $macro:path,
52        try,
53        $format:literal,
54        $($args:tt)*
55    ) => {
56        $crate::_define_dbglike_impl!(
57            ($),
58            $( #[$meta] )*,
59            $name,
60            $macro,
61            try,
62            $format,
63            $crate::define_try_writer!($($args)*)
64        );
65    };
66}
67
68#[doc(hidden)]
69#[macro_export]
70macro_rules! _define_dbglike_impl {
71    (
72        ($d:tt),
73        $( #[$meta:meta] )*,
74        $name:ident,
75        $macro:path,
76        $handler:tt,
77        $format:literal,
78        $( $writer:tt )*
79    ) => {
80        $( #[$meta] )*
81        #[allow(unused_macros)]
82        macro_rules! $name {
83            // Dummy comment below is used to avoid rustfmt formatting bug.
84            // Issue: https://github.com/rust-lang/rustfmt/issues/4609
85            /* ================================================================================== */
86            () => {
87                $crate::dbgwrite!($macro, $( $writer )*, $handler, $format)
88            };
89            ($d ($d args:tt)+) => {
90                $crate::dbgwrite!($macro, $( $writer )*, $handler, $format, $d ($d args)+)
91            };
92        }
93    };
94}