iota_sdk_types/utils.rs
1// Copyright (c) 2026 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4/// Write an iterator of items to a formatter, joined by a separator.
5///
6/// If `delimiters` is provided, the output is wrapped in the given left and
7/// right delimiter strings. An empty iterator produces no output at all (not
8/// even delimiters).
9///
10/// # Examples
11///
12/// ```
13/// use std::fmt;
14///
15/// struct Nums(Vec<i32>);
16///
17/// impl fmt::Display for Nums {
18/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19/// iota_sdk_types::utils::write_sep(f, &self.0, Some(("[", "]")), ", ")
20/// }
21/// }
22///
23/// assert_eq!(Nums(vec![1, 2, 3]).to_string(), "[1, 2, 3]");
24/// assert_eq!(Nums(vec![]).to_string(), "");
25/// ```
26pub fn write_sep<T: core::fmt::Display>(
27 f: &mut core::fmt::Formatter<'_>,
28 items: impl IntoIterator<Item = T>,
29 delimiters: Option<(&str, &str)>,
30 separator: &str,
31) -> std::fmt::Result {
32 let mut xs = items.into_iter();
33 let Some(x) = xs.next() else {
34 return Ok(());
35 };
36 if let Some((l, _)) = delimiters {
37 write!(f, "{l}")?;
38 }
39 write!(f, "{x}")?;
40 for x in xs {
41 write!(f, "{separator}{x}")?;
42 }
43 if let Some((_, r)) = delimiters {
44 write!(f, "{r}")?;
45 }
46 Ok(())
47}