rust_colors/
lib.rs

1//! # rust-colors
2//! `rust-colors` is a library for parsing ANSI Strings to colors.
3//!
4//! ## Example
5//! ```rust
6//! use rust_colors::{Ansi, Color, Colors};
7//!
8//! fn my_function() {
9//!     let colors = Ansi;
10//!    
11//!     println!(
12//!         "The sky is {}, apples can be {}, do you like to touch {} grass?",
13//!         colors.color("blue", Colors::Blue),
14//!         colors.bold_color("red", Colors::Red),
15//!         colors.underline_color("green", Colors::Green),
16//!     );
17//! }
18//!
19//! ```
20//!
21//! # Github
22//! [Git repo RedIsGaming rust-colors](https://github.com/RedIsGaming/rust-colors)
23
24pub use self::ansi::{Ansi, Color};
25pub use self::colors::Colors;
26
27mod colors;
28mod ansi {
29    use std::fmt;
30
31    use crate::colors::Colors;
32
33    #[derive(Debug)]
34    pub struct Ansi;
35
36    pub trait Color<T: fmt::Debug> {
37        type Transform;
38
39        fn color(&self, txt: T, color: Colors) -> Self::Transform;
40        fn bold_color(&self, txt: T, bold_color: Colors) -> Self::Transform;
41        fn underline_color(&self, txt: T, underline_color: Colors) -> Self::Transform;
42    }
43
44    impl<T: fmt::Debug> Color<T> for Ansi {
45        type Transform = String;
46
47        fn color(&self, txt: T, color: Colors) -> Self::Transform {
48            format!(
49                "\x1b{}{:?}\x1b{}",
50                Colors::assign(&color),
51                txt,
52                Colors::assign(&Colors::Default)
53            )
54        }
55
56        fn bold_color(&self, txt: T, bold_color: Colors) -> Self::Transform {
57            format!(
58                "\x1b[1;{}{:?}\x1b{}",
59                Colors::assign(&bold_color).replace('[', ""),
60                txt,
61                Colors::assign(&Colors::Default)
62            )
63        }
64
65        fn underline_color(&self, txt: T, underline_color: Colors) -> Self::Transform {
66            format!(
67                "\x1b[4;{}{:?}\x1b{}",
68                Colors::assign(&underline_color).replace('[', ""),
69                txt,
70                Colors::assign(&Colors::Default)
71            )
72        }
73    }
74}