casper_types/
display_iter.rs

1use core::{
2    cell::RefCell,
3    fmt::{self, Display, Formatter},
4};
5
6/// A helper to allow `Display` printing the items of an iterator with a comma and space between
7/// each.
8#[derive(Debug)]
9pub struct DisplayIter<T>(RefCell<Option<T>>);
10
11impl<T> DisplayIter<T> {
12    /// Returns a new `DisplayIter`.
13    pub fn new(item: T) -> Self {
14        DisplayIter(RefCell::new(Some(item)))
15    }
16}
17
18impl<I, T> Display for DisplayIter<I>
19where
20    I: IntoIterator<Item = T>,
21    T: Display,
22{
23    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
24        if let Some(src) = self.0.borrow_mut().take() {
25            let mut first = true;
26            for item in src.into_iter().take(f.width().unwrap_or(usize::MAX)) {
27                if first {
28                    first = false;
29                    write!(f, "{}", item)?;
30                } else {
31                    write!(f, ", {}", item)?;
32                }
33            }
34
35            Ok(())
36        } else {
37            write!(f, "DisplayIter:GONE")
38        }
39    }
40}