facet_pretty/
ansi.rs

1//! ANSI color codes and formatting utilities for direct writing to formatters
2
3use core::fmt::Write;
4
5/// Write ANSI reset code to the formatter
6pub fn write_reset<W: Write>(f: &mut W) -> core::fmt::Result {
7    f.write_str("\x1b[0m")
8}
9
10/// Write ANSI bold formatting to the formatter
11pub fn write_bold<W: Write>(f: &mut W) -> core::fmt::Result {
12    f.write_str("\x1b[1m")
13}
14
15/// ANSI reset code
16pub const RESET: &str = "\x1b[0m";
17
18/// ANSI bold formatting code
19pub const BOLD: &str = "\x1b[1m";
20
21/// ANSI dim formatting code
22pub const DIM: &str = "\x1b[2m";
23
24/// Write ANSI dim formatting to the formatter
25pub fn write_dim<W: Write>(f: &mut W) -> core::fmt::Result {
26    f.write_str(DIM)
27}
28
29/// Write ANSI italic formatting to the formatter
30pub fn write_italic<W: Write>(f: &mut W) -> core::fmt::Result {
31    f.write_str("\x1b[3m")
32}
33
34/// Write ANSI underline formatting to the formatter
35pub fn write_underline<W: Write>(f: &mut W) -> core::fmt::Result {
36    f.write_str("\x1b[4m")
37}
38
39/// Write RGB foreground color code to the formatter
40pub fn write_rgb<W: Write>(f: &mut W, r: u8, g: u8, b: u8) -> core::fmt::Result {
41    write!(f, "\x1b[38;2;{};{};{}m", r, g, b)
42}
43
44/// Write RGB background color code to the formatter
45pub fn write_rgb_bg<W: Write>(f: &mut W, r: u8, g: u8, b: u8) -> core::fmt::Result {
46    write!(f, "\x1b[48;2;{};{};{}m", r, g, b)
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn test_write_rgb() {
55        let mut out = String::new();
56        write_rgb(&mut out, 255, 0, 0).unwrap();
57        assert_eq!(out, "\x1b[38;2;255;0;0m");
58
59        let mut out = String::new();
60        write_rgb(&mut out, 0, 255, 0).unwrap();
61        assert_eq!(out, "\x1b[38;2;0;255;0m");
62
63        let mut out = String::new();
64        write_rgb(&mut out, 0, 0, 255).unwrap();
65        assert_eq!(out, "\x1b[38;2;0;0;255m");
66    }
67
68    #[test]
69    fn test_write_rgb_bg() {
70        let mut out = String::new();
71        write_rgb_bg(&mut out, 255, 0, 0).unwrap();
72        assert_eq!(out, "\x1b[48;2;255;0;0m");
73
74        let mut out = String::new();
75        write_rgb_bg(&mut out, 0, 255, 0).unwrap();
76        assert_eq!(out, "\x1b[48;2;0;255;0m");
77
78        let mut out = String::new();
79        write_rgb_bg(&mut out, 0, 0, 255).unwrap();
80        assert_eq!(out, "\x1b[48;2;0;0;255m");
81    }
82
83    #[test]
84    fn test_write_formatting() {
85        let mut out = String::new();
86        write_bold(&mut out).unwrap();
87        assert_eq!(out, "\x1b[1m");
88
89        let mut out = String::new();
90        write_dim(&mut out).unwrap();
91        assert_eq!(out, "\x1b[2m");
92
93        let mut out = String::new();
94        write_reset(&mut out).unwrap();
95        assert_eq!(out, "\x1b[0m");
96    }
97}