dbg_pls/
debug_tuple_struct.rs

1use crate::{DebugPls, Formatter};
2
3/// A helper designed to assist with creation of
4/// [`DebugPls`] implementations for tuple structs.
5///
6/// # Examples
7///
8/// ```rust
9/// use dbg_pls::{pretty, DebugPls, Formatter};
10///
11/// struct Foo(i32, String);
12///
13/// impl DebugPls for Foo {
14///     fn fmt(&self, f: Formatter) {
15///         f.debug_tuple_struct("Foo")
16///             .field(&self.0)
17///             .field(&self.1)
18///             .finish()
19///     }
20/// }
21///
22/// let value = Foo(10, "Hello".to_string());
23/// assert_eq!(format!("{}", pretty(&value)), "Foo(10, \"Hello\")");
24/// ```
25pub struct DebugTupleStruct<'a> {
26    formatter: Formatter<'a>,
27    expr: syn::ExprCall,
28}
29
30impl<'a> DebugTupleStruct<'a> {
31    pub(crate) fn new(formatter: Formatter<'a>, name: &str) -> Self {
32        DebugTupleStruct {
33            formatter,
34            expr: syn::ExprCall {
35                attrs: vec![],
36                func: Box::new(syn::Expr::Path(syn::ExprPath {
37                    attrs: vec![],
38                    qself: None,
39                    path: syn::Ident::into(syn::parse_str(name).unwrap()),
40                })),
41                paren_token: syn::token::Paren::default(),
42                args: syn::punctuated::Punctuated::new(),
43            },
44        }
45    }
46
47    /// Adds the field to the tuple struct output.
48    #[must_use]
49    pub fn field(mut self, value: &dyn DebugPls) -> Self {
50        self.expr.args.push(Formatter::process(value));
51        self
52    }
53
54    /// Closes off the tuple struct.
55    pub fn finish(self) {
56        self.formatter.write_expr(self.expr);
57    }
58}