1use std::fmt::{self, Display, Formatter};
2
3pub trait FormatterJoinExtension<'b> {
4 fn join<'a>(&'a mut self, separator: &'static str) -> Join<'a, 'b>;
5}
6
7impl<'b> FormatterJoinExtension<'b> for Formatter<'b> {
8 fn join<'a>(&'a mut self, separator: &'static str) -> Join<'a, 'b> {
9 Join {
10 fmt: self,
11 separator,
12 result: fmt::Result::Ok(()),
13 seen_first: false,
14 }
15 }
16}
17
18pub struct Join<'a, 'b> {
19 fmt: &'a mut Formatter<'b>,
20 separator: &'static str,
21 result: fmt::Result,
22 seen_first: bool,
23}
24
25impl Join<'_, '_> {
26 pub fn entry(&mut self, item: &dyn Display) -> &mut Self {
27 if self.seen_first {
28 self.result = self
29 .result
30 .and_then(|()| self.fmt.write_str(self.separator));
31 } else {
32 self.seen_first = true;
33 }
34 self.result = self.result.and_then(|()| item.fmt(self.fmt));
35 self
36 }
37
38 pub fn finish(&mut self) -> fmt::Result {
39 self.result
40 }
41}