facet_pretty/
display.rs

1//! Display trait implementations for pretty-printing Facet types
2
3use core::fmt::{self, Display, Formatter};
4
5use crate::printer::PrettyPrinter;
6use facet_trait::Facet;
7
8/// Display wrapper for any type that implements Facet
9pub struct PrettyDisplay<'a, T: Facet> {
10    pub(crate) value: &'a T,
11    pub(crate) printer: PrettyPrinter,
12}
13
14impl<T: Facet> Display for PrettyDisplay<'_, T> {
15    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
16        self.printer.format_to(self.value, f)
17    }
18}
19
20/// Extension trait for Facet types to easily pretty-print them
21pub trait FacetPretty: Facet {
22    /// Get a displayable wrapper that pretty-prints this value
23    fn pretty(&self) -> PrettyDisplay<'_, Self>;
24
25    /// Get a displayable wrapper with custom printer settings
26    fn pretty_with(&self, printer: PrettyPrinter) -> PrettyDisplay<'_, Self>;
27}
28
29impl<T: Facet> FacetPretty for T {
30    fn pretty(&self) -> PrettyDisplay<'_, Self> {
31        PrettyDisplay {
32            value: self,
33            printer: PrettyPrinter::default(),
34        }
35    }
36
37    fn pretty_with(&self, printer: PrettyPrinter) -> PrettyDisplay<'_, Self> {
38        PrettyDisplay {
39            value: self,
40            printer,
41        }
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    use facet_derive::Facet;
50    use facet_trait as facet;
51
52    use core::fmt::Write;
53
54    // Use the derive macro from facet
55    #[derive(Facet)]
56    struct TestStruct {
57        field: u32,
58    }
59
60    #[test]
61    fn test_pretty_display() {
62        let test = TestStruct { field: 42 };
63        let display = test.pretty();
64
65        let mut output = String::new();
66        write!(output, "{}", display).unwrap();
67
68        // Just check that it contains the field name and doesn't panic
69        assert!(output.contains("field"));
70    }
71
72    #[test]
73    fn test_pretty_with_custom_printer() {
74        let test = TestStruct { field: 42 };
75        let printer = PrettyPrinter::new().with_colors(false);
76        let display = test.pretty_with(printer);
77
78        let mut output = String::new();
79        write!(output, "{}", display).unwrap();
80
81        // Just check that it contains the field name and doesn't panic
82        assert!(output.contains("field"));
83    }
84}