dbg_pls/
debug_list.rs

1use crate::{DebugPls, Formatter};
2
3/// A helper designed to assist with creation of
4/// [`DebugPls`] implementations for list-like structures.
5///
6/// # Examples
7///
8/// ```rust
9/// use dbg_pls::{pretty, DebugPls, Formatter};
10///
11/// struct Foo(Vec<i32>);
12///
13/// impl DebugPls for Foo {
14///     fn fmt(&self, f: Formatter<'_>) {
15///         f.debug_list().entries(&self.0).finish()
16///     }
17/// }
18///
19/// let value = Foo(vec![10, 11]);
20/// assert_eq!(format!("{}", pretty(&value)), "[10, 11]");
21/// ```
22pub struct DebugList<'a> {
23    formatter: Formatter<'a>,
24    expr: syn::ExprArray,
25}
26
27impl<'a> DebugList<'a> {
28    pub(crate) fn new(formatter: Formatter<'a>) -> Self {
29        DebugList {
30            formatter,
31            expr: syn::ExprArray {
32                attrs: vec![],
33                bracket_token: syn::token::Bracket::default(),
34                elems: syn::punctuated::Punctuated::default(),
35            },
36        }
37    }
38
39    /// Adds a new entry to the list output.
40    #[must_use]
41    pub fn entry(mut self, entry: &dyn DebugPls) -> Self {
42        self.expr.elems.push(Formatter::process(entry));
43        self
44    }
45
46    /// Adds all the entries to the list output.
47    #[must_use]
48    pub fn entries<D, I>(mut self, entries: I) -> Self
49    where
50        D: DebugPls,
51        I: IntoIterator<Item = D>,
52    {
53        self.extend(entries);
54        self
55    }
56
57    /// Closes off the list
58    pub fn finish(self) {
59        self.formatter.write_expr(self.expr);
60    }
61}
62
63impl<'f, D: DebugPls> Extend<D> for DebugList<'f> {
64    fn extend<T: IntoIterator<Item = D>>(&mut self, iter: T) {
65        self.expr
66            .elems
67            .extend(iter.into_iter().map(|entry| Formatter::process(&entry)));
68    }
69}