Skip to content

Commit 30eee70

Browse files
committed
Add DebugStructExt helper for writing less verbose Debug impls
1 parent 149950c commit 30eee70

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed

crates/matrix-sdk-common/src/debug.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,28 @@ use std::fmt;
1818

1919
use ruma::serde::Raw;
2020

21+
pub trait DebugStructExt<'a, 'b> {
22+
fn maybe_field<T: fmt::Debug>(
23+
&mut self,
24+
name: &str,
25+
value: &Option<T>,
26+
) -> &mut fmt::DebugStruct<'a, 'b>;
27+
}
28+
29+
impl<'a, 'b> DebugStructExt<'a, 'b> for fmt::DebugStruct<'a, 'b> {
30+
fn maybe_field<T: fmt::Debug>(
31+
&mut self,
32+
name: &str,
33+
value: &Option<T>,
34+
) -> &mut fmt::DebugStruct<'a, 'b> {
35+
if let Some(value) = value {
36+
self.field(name, value);
37+
}
38+
39+
self
40+
}
41+
}
42+
2143
/// A wrapper around `Raw` that implements `Debug` in a way that only prints the
2244
/// event ID and event type.
2345
pub struct DebugRawEvent<'a, T>(pub &'a Raw<T>);

crates/matrix-sdk/src/config/sync.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
use std::{fmt, time::Duration};
1616

17+
use matrix_sdk_common::debug::DebugStructExt;
1718
use ruma::{api::client::sync::sync_events, presence::PresenceState};
1819

1920
const DEFAULT_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
@@ -38,20 +39,13 @@ impl Default for SyncSettings {
3839
#[cfg(not(tarpaulin_include))]
3940
impl fmt::Debug for SyncSettings {
4041
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41-
let mut s = f.debug_struct("SyncSettings");
42-
43-
macro_rules! opt_field {
44-
($field:ident) => {
45-
if let Some(value) = &self.$field {
46-
s.field(stringify!($field), value);
47-
}
48-
};
49-
}
50-
51-
opt_field!(filter);
52-
opt_field!(timeout);
53-
54-
s.field("full_state", &self.full_state).finish()
42+
let Self { filter, timeout, token: _, full_state, set_presence } = self;
43+
f.debug_struct("SyncSettings")
44+
.maybe_field("filter", filter)
45+
.maybe_field("timeout", timeout)
46+
.field("full_state", full_state)
47+
.field("set_presence", set_presence)
48+
.finish()
5549
}
5650
}
5751

0 commit comments

Comments
 (0)