darling_core/error/
util.rs

1use std::fmt;
2
3/// Represents something surrounded by opening and closing strings.
4pub(crate) struct Quoted<T> {
5    open: &'static str,
6    body: T,
7    close: &'static str,
8}
9
10impl<T> Quoted<T> {
11    /// Creates a new instance with matching open and close strings.
12    pub fn new(quote: &'static str, body: T) -> Self {
13        Self {
14            open: quote,
15            body,
16            close: quote,
17        }
18    }
19
20    /// Creates a new instance using a backtick as the open and close string.
21    pub fn backticks(body: T) -> Self {
22        Self::new("`", body)
23    }
24}
25
26impl<T: fmt::Display> fmt::Display for Quoted<T> {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "{}{}{}", self.open, self.body, self.close)
29    }
30}
31
32/// Iterate through a list of items, writing each of them to the target separated
33/// by a delimiter string.
34pub(crate) fn write_delimited<T: fmt::Display>(
35    f: &mut impl fmt::Write,
36    items: impl IntoIterator<Item = T>,
37    delimiter: &str,
38) -> fmt::Result {
39    let mut first = true;
40    for item in items {
41        if !first {
42            write!(f, "{}", delimiter)?;
43        }
44        first = false;
45        write!(f, "{}", item)?;
46    }
47
48    Ok(())
49}