shapely_pretty/
display.rs

1//! Display trait implementations for pretty-printing Shapely types
2
3use std::fmt::{self, Display, Formatter};
4
5use crate::printer::PrettyPrinter;
6
7/// Display wrapper for any type that implements Shapely
8pub 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
19/// Extension trait for Shapely types to easily pretty-print them
20pub trait ShapelyPretty: shapely_core::Shapely {
21    /// Get a displayable wrapper that pretty-prints this value
22    fn pretty(&self) -> PrettyDisplay<'_, Self>;
23
24    /// Get a displayable wrapper with custom printer settings
25    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    // Use the derive macro from shapely
51    #[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        // Just check that it contains the field name and doesn't panic
65        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        // Just check that it contains the field name and doesn't panic
78        assert!(output.contains("field"));
79    }
80}