Skip to main content

solar_data_structures/
fmt.rs

1use std::{
2    cell::{Cell, RefCell},
3    fmt,
4};
5
6pub use fmt::*;
7
8/// Formats a line-oriented diff with the same prefixes as rustc MIR tests.
9pub fn line_diff<'a>(before: &'a str, after: &'a str) -> impl fmt::Display + 'a {
10    from_fn(move |f| {
11        for result in diff::lines(before, after) {
12            match result {
13                diff::Result::Left(line) => writeln!(f, "- {line}")?,
14                diff::Result::Right(line) => writeln!(f, "+ {line}")?,
15                diff::Result::Both(line, _) => writeln!(f, "  {line}")?,
16            }
17        }
18        Ok(())
19    })
20}
21
22/// Iterator formatting helpers.
23pub trait FmtIteratorExt: Iterator + Sized {
24    /// Formats each item separated by `separator`.
25    fn format<'a>(self, separator: &'a str) -> Format<'a, Self>
26    where
27        Self::Item: fmt::Display,
28    {
29        Format { iter: Cell::new(Some(self)), separator }
30    }
31
32    /// Formats each item separated by `separator`, using `format` for each item.
33    fn format_with<'a, F>(self, separator: &'a str, format: F) -> FormatWith<'a, Self, F>
34    where
35        F: FnMut(&mut fmt::Formatter<'_>, Self::Item) -> fmt::Result,
36    {
37        FormatWith { inner: RefCell::new(Some((self, format))), separator }
38    }
39}
40
41impl<I: Iterator> FmtIteratorExt for I {}
42
43/// Display adapter returned by [`FmtIteratorExt::format`].
44pub struct Format<'a, I> {
45    iter: Cell<Option<I>>,
46    separator: &'a str,
47}
48
49impl<I> fmt::Display for Format<'_, I>
50where
51    I: Iterator,
52    I::Item: fmt::Display,
53{
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        let iter = self.iter.take().expect("format called twice");
56        for (i, item) in iter.enumerate() {
57            if i != 0 {
58                f.write_str(self.separator)?;
59            }
60            write!(f, "{item}")?;
61        }
62        Ok(())
63    }
64}
65
66/// Display adapter returned by [`FmtIteratorExt::format_with`].
67pub struct FormatWith<'a, I, F> {
68    inner: RefCell<Option<(I, F)>>,
69    separator: &'a str,
70}
71
72impl<I, F> fmt::Display for FormatWith<'_, I, F>
73where
74    I: Iterator,
75    F: FnMut(&mut fmt::Formatter<'_>, I::Item) -> fmt::Result,
76{
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        let (iter, mut format) = self.inner.borrow_mut().take().expect("format_with called twice");
79        for (i, item) in iter.enumerate() {
80            if i != 0 {
81                f.write_str(self.separator)?;
82            }
83            format(f, item)?;
84        }
85        Ok(())
86    }
87}
88
89/// Returns `list` formatted as a comma-separated list with "or" before the last item.
90pub fn or_list<I>(list: I) -> impl fmt::Display
91where
92    I: IntoIterator<IntoIter: ExactSizeIterator, Item: fmt::Display>,
93{
94    let list = Cell::new(Some(list.into_iter()));
95    from_fn(move |f| {
96        let list = list.take().expect("or_list called twice");
97        let len = list.len();
98        for (i, t) in list.enumerate() {
99            if i > 0 {
100                let is_last = i == len - 1;
101                f.write_str(if len > 2 && is_last {
102                    ", or "
103                } else if len == 2 && is_last {
104                    " or "
105                } else {
106                    ", "
107                })?;
108            }
109            write!(f, "{t}")?;
110        }
111        Ok(())
112    })
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn test_or_list() {
121        let tests: &[(&[&str], &str)] = &[
122            (&[], ""),
123            (&["`<eof>`"], "`<eof>`"),
124            (&["integer", "identifier"], "integer or identifier"),
125            (&["path", "string literal", "`&&`"], "path, string literal, or `&&`"),
126            (&["`&&`", "`||`", "`&&`", "`||`"], "`&&`, `||`, `&&`, or `||`"),
127        ];
128        for &(tokens, expected) in tests {
129            assert_eq!(or_list(tokens).to_string(), expected, "{tokens:?}");
130        }
131    }
132
133    #[test]
134    fn test_format() {
135        assert_eq!([1, 2, 3].iter().format(", ").to_string(), "1, 2, 3");
136    }
137
138    #[test]
139    fn test_format_with() {
140        let values = [1, 2, 3];
141        let formatted = values.iter().format_with(" | ", |f, value| write!(f, "#{value}"));
142        assert_eq!(formatted.to_string(), "#1 | #2 | #3");
143    }
144
145    #[test]
146    fn test_line_diff() {
147        assert_eq!(line_diff("a\nb\n", "a\nc\n").to_string(), "  a\n- b\n+ c\n  \n");
148    }
149}