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
78
79
80
81
82
83
84
85
86
87
88
89
//! A simple crate that provides a way to create instances of opaque types that implement
//! [`fmt::Display`] and [`fmt::Debug`] by calling a provided formatting closure.
//!
//! # Examples
//!
//! ```
//! use display_with::{display_with, debug_with};
//!
//! let display = display_with(|f| write!(f, "Hello, world!"));
//! assert_eq!(format!("{display}"), "Hello, world!");
//!
//! let debug = debug_with(|f| write!(f, "Hello, world!"));
//! assert_eq!(format!("{debug:?}"), "Hello, world!");
//! ```
//!
//! This can be combined with the `format_args!` macro to use the opaque types with the `write!` and
//! `writeln!` macros.
//!
//! ```
//! use core::fmt::Write;
//! use display_with::{display_with, debug_with};
//!
//! fn main() -> std::fmt::Result {
//! let display = display_with(|f| write!(f, "Hello, world!"));
//! let mut s = String::new();
//! // Unlike `s.push_str(&format!("{display}"))`, this doesn't require an extra allocation.
//! write!(&mut s, "{}", format_args!("{display}"))?;
//! Ok(())
//! }
//! ```
//!
//!
//! Credit: <https://internals.rust-lang.org/t/format-args-with-long-lifetimes/19494/2>.
use fmt;
/// Creates an instance of an opaque type that implements [`fmt::Display`] by calling the provided
/// formatting closure.
///
/// # Examples
///
/// ```
/// use display_with::display_with;
///
/// let display = display_with(|f| write!(f, "Hello, world!"));
/// assert_eq!(format!("{display}"), "Hello, world!");
/// ```
/// Creates an instance of an opaque type that implements [`fmt::Debug`] by calling the provided
/// formatting closure.
///
/// # Examples
///
/// ```
/// use display_with::debug_with;
///
/// let debug = debug_with(|f| write!(f, "Hello, world!"));
/// assert_eq!(format!("{debug:?}"), "Hello, world!");
/// ```