pear/input/
show.rs

1// TODO: Print parser arguments in debug/error output.
2
3pub trait Show {
4    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
5}
6
7impl std::fmt::Display for &dyn Show {
8    #[inline(always)]
9    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10        Show::fmt(*self, f)
11    }
12}
13
14impl<T: Show + ?Sized> Show for &T {
15    #[inline(always)]
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        <T as Show>::fmt(self, f)
18    }
19}
20
21impl<T: Show> Show for Option<T> {
22    #[inline(always)]
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        if let Some(val) = self {
25            <T as Show>::fmt(val, f)?;
26        }
27
28        Ok(())
29    }
30}
31
32impl<T: Show> Show for [T] {
33    #[inline(always)]
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        for (i, value) in self.iter().enumerate() {
36            if i > 0 { write!(f, " ")?; }
37            write!(f, "{}", value as &dyn Show)?;
38        }
39
40        Ok(())
41    }
42}
43
44impl<T: Show + ?Sized + ToOwned> Show for std::borrow::Cow<'_, T> {
45    #[inline(always)]
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        Show::fmt(self.as_ref(), f)
48    }
49}
50
51macro_rules! impl_for_slice_len {
52    ($($n:expr),*) => ($(
53        impl<T: Show> Show for [T; $n] {
54            #[inline(always)]
55            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56                Show::fmt(&self[..], f)
57            }
58        }
59    )*)
60}
61
62impl_for_slice_len!(
63    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
64    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32
65);
66
67impl<T: Show> Show for Vec<T> {
68    #[inline(always)]
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        Show::fmt(self.as_slice(), f)
71    }
72}
73
74impl Show for u8 {
75    #[inline(always)]
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        if self.is_ascii() {
78            write!(f, "'{}'", char::from(*self).escape_debug())
79        } else {
80            write!(f, "byte {}", self)
81        }
82    }
83}
84
85impl_show_with! { Debug,
86        u16, u32, u64, u128, usize,
87    i8, i16, i32, i64, i128, isize
88}
89
90macro_rules! impl_with_tick_display {
91    ($($T:ty,)*) => ($(
92        impl Show for $T {
93            #[inline(always)]
94            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95                write!(f, "{:?}", self)
96            }
97        }
98    )*)
99}
100
101impl_with_tick_display! {
102    &str, String, char, std::borrow::Cow<'static, str>,
103}