use indexmap::IndexMap;
use lazy_static::lazy_static;
lazy_static! {
#[rustfmt::skip]
pub static ref CP437_TO_UTF8: &'static [char] = &[
'\0', '☺', '☻', '♥', '♦', '♣', '♠', '•', '◘', '○', '\n', '♂', '♀', '\r', '♫', '☼',
'►', '◄', '↕', '‼', '¶', '§', '▬', '↨', '↑', '↓', '', '', '∟', '↔', '▲', '▼',
' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
'@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
'`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '⌂',
'Ç', 'ü', 'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å',
'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', '¢', '£', '¥', '₧', 'ƒ',
'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '⌐', '¬', '½', '¼', '¡', '«', '»',
'░', '▒', '▓', '│', '┤', '╡', '╢', '╖', '╕', '╣', '║', '╗', '╝', '╜', '╛', '┐',
'└', '┴', '┬', '├', '─', '┼', '╞', '╟', '╚', '╔', '╩', '╦', '╠', '═', '╬', '╧',
'╨', '╤', '╥', '╙', '╘', '╒', '╓', '╫', '╪', '┘', '┌', '█', '▄', '▌', '▐', '▀',
'α', 'ß', 'Γ', 'π', 'Σ', 'σ', 'µ', 'τ', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩',
'≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'ⁿ', '²', '■', ' ',
];
pub static ref UTF8_TO_CP437: IndexMap<char, u8> =
IndexMap::from_iter(
CP437_TO_UTF8
.iter()
.enumerate()
.map(|(a, b)| return (*b, a as u8))
);
}
pub fn to_utf8(cp437: Vec<u8>) -> String {
return cp437
.iter()
.map(|byte| return CP437_TO_UTF8[*byte as usize])
.collect();
}
pub fn to_cp437(utf8: String) -> Result<Vec<u8>, String> {
return utf8
.chars()
.map(|r#char| {
return UTF8_TO_CP437
.get(&r#char)
.map(|byte| return *byte)
.ok_or_else(|| {
return format!(
"{} (U+{:X}) is not a valid CP437 character",
r#char, r#char as u32
);
});
})
.collect::<Result<Vec<u8>, String>>();
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn cp437_to_utf8() {
for i in 0x00..=0xFF {
assert_eq!(UTF8_TO_CP437.get(&CP437_TO_UTF8[i]), Some(i as u8).as_ref());
}
}
#[test]
fn utf8_to_cp437() {
for c in &CP437_TO_UTF8[0x00..=0xFF] {
assert_eq!(CP437_TO_UTF8[*UTF8_TO_CP437.get(c).unwrap() as usize], *c);
}
}
#[test]
fn vec_to_utf8() {
assert_eq!(to_utf8(vec![0x01]), "☺");
}
#[test]
fn str_to_cp437_ok() {
let result = to_cp437(String::from("☺"));
assert!(result.is_ok());
assert_eq!(result.unwrap(), vec![0x01]);
}
#[test]
fn str_to_cp437_err() {
let result = to_cp437(String::from("🚫"));
assert!(result.is_err());
assert_eq!(
result.unwrap_err(),
"🚫 (U+1F6AB) is not a valid CP437 character"
);
}
}