Skip to main content

badterm_core/
cp437.rs

1//! IBM code page 437 <-> Unicode conversion.
2//!
3//! Glyph indices on screen are always CP437 bytes; these tables are used for
4//! UTF-8 sessions, keyboard input and copying text out of the terminal.
5
6/// Unicode equivalent of every CP437 glyph, including the "graphic" control
7/// range 0x00-0x1F shown by the PC video BIOS.
8#[rustfmt::skip]
9pub const TO_UNICODE: [char; 256] = [
10    '\u{0000}', '☺', '☻', '♥', '♦', '♣', '♠', '•', '◘', '○', '◙', '♂', '♀', '♪', '♫', '☼',
11    '►', '◄', '↕', '‼', '¶', '§', '▬', '↨', '↑', '↓', '→', '←', '∟', '↔', '▲', '▼',
12    ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/',
13    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
14    '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
15    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_',
16    '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
17    'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '⌂',
18    'Ç', 'ü', 'é', 'â', 'ä', 'à', 'å', 'ç', 'ê', 'ë', 'è', 'ï', 'î', 'ì', 'Ä', 'Å',
19    'É', 'æ', 'Æ', 'ô', 'ö', 'ò', 'û', 'ù', 'ÿ', 'Ö', 'Ü', '¢', '£', '¥', '₧', 'ƒ',
20    'á', 'í', 'ó', 'ú', 'ñ', 'Ñ', 'ª', 'º', '¿', '⌐', '¬', '½', '¼', '¡', '«', '»',
21    '░', '▒', '▓', '│', '┤', '╡', '╢', '╖', '╕', '╣', '║', '╗', '╝', '╜', '╛', '┐',
22    '└', '┴', '┬', '├', '─', '┼', '╞', '╟', '╚', '╔', '╩', '╦', '╠', '═', '╬', '╧',
23    '╨', '╤', '╥', '╙', '╘', '╒', '╓', '╫', '╪', '┘', '┌', '█', '▄', '▌', '▐', '▀',
24    'α', 'ß', 'Γ', 'π', 'Σ', 'σ', 'µ', 'τ', 'Φ', 'Θ', 'Ω', 'δ', '∞', 'φ', 'ε', '∩',
25    '≡', '±', '≥', '≤', '⌠', '⌡', '÷', '≈', '°', '∙', '·', '√', 'ⁿ', '²', '■', '\u{00A0}',
26];
27
28/// Convert a CP437 glyph to Unicode.
29pub fn to_unicode(b: u8) -> char {
30    TO_UNICODE[b as usize]
31}
32
33/// Convert a Unicode scalar to its CP437 glyph, if one exists.
34///
35/// ASCII maps to itself; a few common look-alikes (e.g. U+00B7 vs U+2219) are
36/// accepted in both directions.
37pub fn from_unicode(c: char) -> Option<u8> {
38    if (c as u32) < 0x80 {
39        return Some(c as u8);
40    }
41    match c {
42        '\u{00B7}' => return Some(0xFA),
43        '\u{03B2}' => return Some(0xE1),
44        '\u{03A3}' => return Some(0xE4),
45        '\u{220E}' | '\u{25A0}' => return Some(0xFE),
46        _ => {}
47    }
48    TO_UNICODE[0x80..]
49        .iter()
50        .position(|&u| u == c)
51        .map(|i| (i + 0x80) as u8)
52        .or_else(|| TO_UNICODE[1..0x20].iter().position(|&u| u == c).map(|i| (i + 1) as u8))
53}
54
55/// Decode a CP437 byte string into a Unicode `String`.
56pub fn decode(bytes: &[u8]) -> String {
57    bytes.iter().map(|&b| to_unicode(b)).collect()
58}
59
60/// Encode a string as CP437, replacing unmappable characters with `?`.
61pub fn encode(s: &str) -> Vec<u8> {
62    s.chars().map(|c| from_unicode(c).unwrap_or(b'?')).collect()
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn round_trip_high_half() {
71        for b in 0x80..=0xFFu8 {
72            assert_eq!(from_unicode(to_unicode(b)), Some(b), "byte {b:#x}");
73        }
74    }
75
76    #[test]
77    fn ascii_identity() {
78        assert_eq!(encode("Hello"), b"Hello");
79        assert_eq!(decode(&[0xDB, 0xB0]), "█░");
80    }
81}