106 lines
3.3 KiB
Rust
106 lines
3.3 KiB
Rust
extern crate termion;
|
|
|
|
use termion::color;
|
|
|
|
const COLOR_SYMBOLS: color::Fg<color::LightGreen> = color::Fg(color::LightGreen);
|
|
const COLOR_TEXT: color::Fg<color::Cyan> = color::Fg(color::Cyan);
|
|
const COLOR_NUMBERS: color::Fg<color::LightBlue> = color::Fg(color::LightBlue);
|
|
|
|
pub fn map_u8_to_color(data: u8) -> String {
|
|
if super::isatty() {
|
|
match data {
|
|
32..=47 => format!("{}{:02x}{}", COLOR_SYMBOLS, data, color::Fg(color::Reset)),
|
|
48..=57 => format!("{}{:02x}{}", COLOR_NUMBERS, data, color::Fg(color::Reset)),
|
|
58..=64 => format!("{}{:02x}{}", COLOR_SYMBOLS, data, color::Fg(color::Reset)),
|
|
65..=90 => format!("{}{:02x}{}", COLOR_TEXT, data, color::Fg(color::Reset)),
|
|
91..=96 => format!("{}{:02x}{}", COLOR_SYMBOLS, data, color::Fg(color::Reset)),
|
|
97..=122 => format!("{}{:02x}{}", COLOR_TEXT, data, color::Fg(color::Reset)),
|
|
123..=126 => format!("{}{:02x}{}", COLOR_SYMBOLS, data, color::Fg(color::Reset)),
|
|
_ => format!(
|
|
"{}{:02x}{}",
|
|
color::Fg(color::LightBlack),
|
|
data,
|
|
color::Fg(color::Reset)
|
|
),
|
|
}
|
|
} else {
|
|
format!("{:02x}", data)
|
|
}
|
|
}
|
|
|
|
pub fn map_char_to_color(data: u8) -> String {
|
|
if super::isatty() {
|
|
match data {
|
|
32..=47 => format!(
|
|
"{}{}{}",
|
|
COLOR_SYMBOLS,
|
|
(data as char),
|
|
color::Fg(color::Reset)
|
|
),
|
|
48..=57 => format!(
|
|
"{}{}{}",
|
|
COLOR_NUMBERS,
|
|
(data as char),
|
|
color::Fg(color::Reset)
|
|
),
|
|
58..=64 => format!(
|
|
"{}{}{}",
|
|
COLOR_SYMBOLS,
|
|
(data as char),
|
|
color::Fg(color::Reset)
|
|
),
|
|
65..=90 => format!(
|
|
"{}{}{}",
|
|
COLOR_TEXT,
|
|
(data as char),
|
|
color::Fg(color::Reset)
|
|
),
|
|
91..=96 => format!(
|
|
"{}{}{}",
|
|
COLOR_SYMBOLS,
|
|
(data as char),
|
|
color::Fg(color::Reset)
|
|
),
|
|
97..=122 => format!(
|
|
"{}{}{}",
|
|
COLOR_TEXT,
|
|
(data as char),
|
|
color::Fg(color::Reset)
|
|
),
|
|
123..=126 => format!(
|
|
"{}{}{}",
|
|
COLOR_SYMBOLS,
|
|
(data as char),
|
|
color::Fg(color::Reset)
|
|
),
|
|
_ => format!(
|
|
"{}.{}",
|
|
color::Fg(color::LightBlack),
|
|
color::Fg(color::Reset)
|
|
),
|
|
}
|
|
} else {
|
|
match data {
|
|
32..=126 => format!("{}", (data as char)),
|
|
_ => ".".to_string(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::{map_u8_to_color, map_char_to_color};
|
|
|
|
#[test]
|
|
fn map_u8_to_color_test() {
|
|
assert_eq!("\u{1b}[38;5;12m32\u{1b}[39m", map_u8_to_color(0x32));
|
|
assert_eq!("\u{1b}[38;5;6m64\u{1b}[39m", map_u8_to_color(0x64));
|
|
}
|
|
|
|
#[test]
|
|
fn map_char8_to_color_test() {
|
|
assert_eq!("\u{1b}[38;5;12m2\u{1b}[39m", map_char_to_color(0x32));
|
|
assert_eq!("\u{1b}[38;5;6md\u{1b}[39m", map_char_to_color(0x64));
|
|
}
|
|
}
|