1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use std::convert::From;
use std::fmt;
use std::fmt::{Display, Formatter};
extern crate hsl;
pub use hsl::HSL as Hsl;
#[derive(Debug, Clone, PartialEq)]
pub struct Rgb(pub u8, pub u8, pub u8);
#[derive(Debug, Clone)]
pub enum RGB<'a> {
Fg(Rgb, &'a str),
Bg(Rgb, &'a str),
FgBg(Rgb, Rgb, &'a str),
}
impl Rgb {
pub fn fg<'a>(&self, txt: &'a str) -> RGB<'a> {
RGB::Fg(self.clone(), txt)
}
pub fn bg<'a>(&self, txt: &'a str) -> RGB<'a> {
RGB::Bg(self.clone(), txt)
}
pub fn fgbg<'a>(&self, bg_col: &Rgb, txt: &'a str) -> RGB<'a> {
RGB::FgBg(self.clone(), bg_col.clone(), txt)
}
}
impl<'a> Display for RGB<'a> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
RGB::Fg(c, txt) => write!(f, "\x1B[38;2;{};{};{}m{}\x1B[39m", c.0, c.1, c.2, txt),
RGB::Bg(c, txt) => write!(f, "\x1B[48;2;{};{};{}m{}\x1B[49m", c.0, c.1, c.2, txt),
RGB::FgBg(fg, bg, txt) => write!(
f,
"\x1B[38;2;{};{};{}m\x1B[48;2;{};{};{}m{}\x1B[49m\x1B[39m",
fg.0, fg.1, fg.2, bg.0, bg.1, bg.2, txt
),
}
}
}
impl From<Hsl> for Rgb {
fn from(x: Hsl) -> Self {
let (r, g, b) = x.to_rgb();
Rgb(r, g, b)
}
}
#[cfg(test)]
mod test {
use crate::colour::{Rgb, RGB};
use std::io::Write;
#[test]
fn fg_rgb() {
let s = "\x1B[38;2;255;255;255mblaaa\x1B[39m";
let mut su = vec![];
write!(su, "{}", RGB::Fg(Rgb(255, 255, 255), "blaaa")).unwrap();
assert_eq!(s, String::from_utf8(su).unwrap());
}
}