to_display/
display_slice.rs

1use std::fmt;
2
3use crate::Context;
4use crate::DisplayConfig;
5use crate::ToDisplay;
6
7/// Displays a slice `[T]`.
8///
9/// This is the return value of calling a `[T]::display()`.
10pub struct DisplaySlice<'a, T> {
11    slice: &'a [T],
12    context: Context,
13}
14
15impl<T> DisplayConfig for DisplaySlice<'_, T> {
16    fn context_mut(&mut self) -> &mut Context {
17        &mut self.context
18    }
19}
20
21impl<T> fmt::Display for DisplaySlice<'_, T>
22where
23    T: ToDisplay,
24{
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        let max_items = self.context.max_items();
27
28        write!(f, "[")?;
29        for (i, t) in self.slice.iter().take(max_items).enumerate() {
30            if i > 0 {
31                write!(f, ", ")?;
32            }
33            write!(f, "{}", t.display_with_context(self.context))?;
34        }
35
36        if self.slice.len() > max_items {
37            write!(f, ", ...")?;
38        }
39
40        write!(f, "]")
41    }
42}
43
44impl<T> crate::ToDisplay for [T]
45where
46    T: ToDisplay,
47{
48    type Displayer<'a>
49        = DisplaySlice<'a, T>
50    where
51        T: 'a;
52
53    fn display_with_context(&self, context: Context) -> Self::Displayer<'_> {
54        DisplaySlice {
55            slice: self,
56            context,
57        }
58    }
59}
60
61impl<T> crate::ToDisplay for Vec<T>
62where
63    T: ToDisplay,
64{
65    type Displayer<'a>
66        = DisplaySlice<'a, T>
67    where
68        T: 'a;
69
70    fn display_with_context(&self, context: Context) -> Self::Displayer<'_> {
71        DisplaySlice {
72            slice: self.as_slice(),
73            context,
74        }
75    }
76}