shapely_pretty/
display.rs1use std::fmt::{self, Display, Formatter};
4
5use crate::printer::PrettyPrinter;
6
7pub struct PrettyDisplay<'a, T: shapely_core::Shapely> {
9 pub(crate) value: &'a T,
10 pub(crate) printer: PrettyPrinter,
11}
12
13impl<T: shapely_core::Shapely> Display for PrettyDisplay<'_, T> {
14 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15 self.printer.format_to(self.value, f)
16 }
17}
18
19pub trait ShapelyPretty: shapely_core::Shapely {
21 fn pretty(&self) -> PrettyDisplay<'_, Self>;
23
24 fn pretty_with(&self, printer: PrettyPrinter) -> PrettyDisplay<'_, Self>;
26}
27
28impl<T: shapely_core::Shapely> ShapelyPretty for T {
29 fn pretty(&self) -> PrettyDisplay<'_, Self> {
30 PrettyDisplay {
31 value: self,
32 printer: PrettyPrinter::default(),
33 }
34 }
35
36 fn pretty_with(&self, printer: PrettyPrinter) -> PrettyDisplay<'_, Self> {
37 PrettyDisplay {
38 value: self,
39 printer,
40 }
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47 use shapely::Shapely;
48 use std::fmt::Write;
49
50 #[derive(Shapely)]
52 struct TestStruct {
53 field: u32,
54 }
55
56 #[test]
57 fn test_pretty_display() {
58 let test = TestStruct { field: 42 };
59 let display = test.pretty();
60
61 let mut output = String::new();
62 write!(output, "{}", display).unwrap();
63
64 assert!(output.contains("field"));
66 }
67
68 #[test]
69 fn test_pretty_with_custom_printer() {
70 let test = TestStruct { field: 42 };
71 let printer = PrettyPrinter::new().with_colors(false);
72 let display = test.pretty_with(printer);
73
74 let mut output = String::new();
75 write!(output, "{}", display).unwrap();
76
77 assert!(output.contains("field"));
79 }
80}