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_core::Facet;
7
8/// Display wrapper for any type that implements Facet
9pub struct PrettyDisplay<'a, T: Facet<'a> + ?Sized> {
10    pub(crate) value: &'a T,
11    pub(crate) printer: PrettyPrinter,
12}
13
14impl<'a, T: Facet<'a>> Display for PrettyDisplay<'a, 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<'a>: Facet<'a> {
22    /// Get a displayable wrapper that pretty-prints this value
23    fn pretty(&'a self) -> PrettyDisplay<'a, Self>;
24
25    /// Get a displayable wrapper with custom printer settings
26    fn pretty_with(&'a self, printer: PrettyPrinter) -> PrettyDisplay<'a, Self>;
27}
28
29impl<'a, T: Facet<'a>> FacetPretty<'a> for T {
30    fn pretty(&'a self) -> PrettyDisplay<'a, Self> {
31        PrettyDisplay {
32            value: self,
33            printer: PrettyPrinter::default(),
34        }
35    }
36
37    fn pretty_with(&'a self, printer: PrettyPrinter) -> PrettyDisplay<'a, Self> {
38        PrettyDisplay {
39            value: self,
40            printer,
41        }
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use core::fmt::Write;
49    use facet::Facet;
50
51    // Use the derive macro from facet
52    #[derive(Facet)]
53    struct TestStruct {
54        field: u32,
55    }
56
57    #[test]
58    fn test_pretty_display() {
59        let test = TestStruct { field: 42 };
60        let display = test.pretty();
61
62        let mut output = String::new();
63        write!(output, "{}", display).unwrap();
64
65        // Just check that it contains the field name and doesn't panic
66        assert!(output.contains("field"));
67    }
68
69    #[test]
70    fn test_pretty_with_custom_printer() {
71        let test = TestStruct { field: 42 };
72        let printer = PrettyPrinter::new().with_colors(false);
73        let display = test.pretty_with(printer);
74
75        let mut output = String::new();
76        write!(output, "{}", display).unwrap();
77
78        // Just check that it contains the field name and doesn't panic
79        assert!(output.contains("field"));
80    }
81}