1#[derive(Copy, Clone)]
3pub enum Color {
4 Ansi(u8),
5 TrueColor(u8, u8, u8),
6}
7
8impl Color {
9 pub fn as_rgb(&self) -> u32 {
10 let encode_rgb = |r: u8, g: u8, b: u8| -> u32 {
11 0xFF000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32)
12 };
13
14 match *self {
15 Color::TrueColor(r, g, b) => encode_rgb(r, g, b),
16 Color::Ansi(value) => match value {
17 0 => encode_rgb(0x00, 0x00, 0x00),
18 1 => encode_rgb(0x80, 0x00, 0x00),
19 2 => encode_rgb(0x00, 0x80, 0x00),
20 3 => encode_rgb(0x80, 0x80, 0x00),
21 4 => encode_rgb(0x00, 0x00, 0x80),
22 5 => encode_rgb(0x80, 0x00, 0x80),
23 6 => encode_rgb(0x00, 0x80, 0x80),
24 7 => encode_rgb(0xc0, 0xc0, 0xc0),
25 8 => encode_rgb(0x80, 0x80, 0x80),
26 9 => encode_rgb(0xff, 0x00, 0x00),
27 10 => encode_rgb(0x00, 0xff, 0x00),
28 11 => encode_rgb(0xff, 0xff, 0x00),
29 12 => encode_rgb(0x00, 0x00, 0xff),
30 13 => encode_rgb(0xff, 0x00, 0xff),
31 14 => encode_rgb(0x00, 0xff, 0xff),
32 15 => encode_rgb(0xff, 0xff, 0xff),
33 16 ... 231 => {
34 let convert = |value: u8| -> u8 {
35 match value {
36 0 => 0,
37 _ => value * 0x28 + 0x28
38 }
39 };
40
41 let r = convert((value - 16) / 36 % 6);
42 let g = convert((value - 16) / 6 % 6);
43 let b = convert((value - 16) % 6);
44 encode_rgb(r, g, b)
45 },
46 232 ... 255 => {
47 let gray = (value - 232) * 10 + 8;
48 encode_rgb(gray, gray, gray)
49 },
50 _ => encode_rgb(0, 0, 0)
51 }
52 }
53 }
54}