1#[macro_export]
15macro_rules! impl_json_display {
16 ($($t:ty),+ $(,)?) => {
17 $(
18 impl std::fmt::Display for $t {
19 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 match serde_json::to_string(self) {
21 Ok(json) => write!(f, "{}", json),
22 Err(e) => write!(f, "<serialization error: {}>", e),
23 }
24 }
25 }
26 )+
27 };
28}
29
30#[macro_export]
33macro_rules! impl_json_debug_pretty {
34 ($($t:ty),+ $(,)?) => {
35 $(
36 impl std::fmt::Debug for $t {
37 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38 match serde_json::to_string_pretty(self) {
39 Ok(json) => write!(f, "{}", json),
40 Err(e) => write!(f, "<serialization error: {}>", e),
41 }
42 }
43 }
44 )+
45 };
46}
47
48#[cfg(test)]
49mod tests {
50 use serde::Serialize;
51
52 #[derive(Serialize)]
53 struct TestStruct {
54 name: String,
55 value: i32,
56 }
57
58 impl_json_display!(TestStruct);
59 impl_json_debug_pretty!(TestStruct);
60
61 #[test]
62 fn test_display() {
63 let test = TestStruct {
64 name: "test".to_string(),
65 value: 42,
66 };
67 let display = format!("{}", test);
68 assert!(display.contains("test"));
69 assert!(display.contains("42"));
70 }
71
72 #[test]
73 fn test_debug() {
74 let test = TestStruct {
75 name: "test".to_string(),
76 value: 42,
77 };
78 let debug = format!("{:?}", test);
79 assert!(debug.contains("test"));
80 assert!(debug.contains("42"));
81 }
82}