Skip to main content

lexe_std/
fmt.rs

1use std::fmt;
2
3/// Displays a slice of elements using each element's [`fmt::Display`] impl.
4pub struct DisplaySlice<'a, T>(pub &'a [T]);
5
6impl<T: fmt::Display> fmt::Display for DisplaySlice<'_, T> {
7    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8        // Slice iterators are cheaply cloneable (just pointer + length)
9        DisplayIter(self.0.iter()).fmt(f)
10    }
11}
12
13/// Displays an iterator of items using each element's [`fmt::Display`] impl.
14///
15/// As [`fmt::Display`] can't take ownership of the underlying iterator, the
16/// iterator is cloned every time it is displayed, so it should be cheaply
17/// clonable (most iterators are).
18pub struct DisplayIter<I>(pub I);
19
20impl<I> fmt::Display for DisplayIter<I>
21where
22    I: Iterator + Clone,
23    I::Item: fmt::Display,
24{
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        let mut first = true;
27        write!(f, "[")?;
28        for item in self.0.clone() {
29            if !first {
30                write!(f, ", ")?;
31            }
32            first = false;
33            write!(f, "{item}")?;
34        }
35        write!(f, "]")
36    }
37}
38
39/// Displays an iterator of items using each element's [`fmt::Debug`] impl.
40///
41/// As [`fmt::Display`] can't take ownership of the underlying iterator, the
42/// iterator is cloned every time it is displayed, so it should be cheaply
43/// clonable (most iterators are).
44pub struct DebugIter<I>(pub I);
45
46impl<I> fmt::Display for DebugIter<I>
47where
48    I: Iterator + Clone,
49    I::Item: fmt::Debug,
50{
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        let mut first = true;
53        write!(f, "[")?;
54        for item in self.0.clone() {
55            if !first {
56                write!(f, ", ")?;
57            }
58            first = false;
59            write!(f, "{item:?}")?;
60        }
61        write!(f, "]")
62    }
63}
64
65/// Displays an `Option<T>` using `T`'s [`fmt::Display`] impl,
66/// or "(null)" if the [`Option`] was [`None`].
67pub struct DisplayOption<T>(pub Option<T>);
68
69impl<T: fmt::Display> fmt::Display for DisplayOption<T> {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match &self.0 {
72            Some(value) => write!(f, "{value}"),
73            None => write!(f, "(none)"),
74        }
75    }
76}