use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyCode {
Char(char),
Enter,
Tab,
Escape,
Backspace,
Delete,
Insert,
Up,
Down,
Left,
Right,
Home,
End,
PageUp,
PageDown,
F(u8),
Unidentified,
}
impl KeyCode {
pub fn display(&self) -> String {
match self {
KeyCode::Char(c) => c.to_string(),
KeyCode::Enter => "Enter".to_string(),
KeyCode::Tab => "Tab".to_string(),
KeyCode::Escape => "Esc".to_string(),
KeyCode::Backspace => "Backspace".to_string(),
KeyCode::Delete => "Delete".to_string(),
KeyCode::Insert => "Insert".to_string(),
KeyCode::Up => "↑".to_string(),
KeyCode::Down => "↓".to_string(),
KeyCode::Left => "←".to_string(),
KeyCode::Right => "→".to_string(),
KeyCode::Home => "Home".to_string(),
KeyCode::End => "End".to_string(),
KeyCode::PageUp => "PgUp".to_string(),
KeyCode::PageDown => "PgDn".to_string(),
KeyCode::F(n) => format!("F{n}"),
KeyCode::Unidentified => "?".to_string(),
}
}
}
impl fmt::Display for KeyCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.display())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_covers_named_keys() {
assert_eq!(KeyCode::Enter.to_string(), "Enter");
assert_eq!(KeyCode::Escape.to_string(), "Esc");
assert_eq!(KeyCode::Backspace.to_string(), "Backspace");
assert_eq!(KeyCode::Delete.to_string(), "Delete");
assert_eq!(KeyCode::Up.to_string(), "↑");
assert_eq!(KeyCode::Left.to_string(), "←");
assert_eq!(KeyCode::F(5).to_string(), "F5");
assert_eq!(KeyCode::F(12).to_string(), "F12");
}
#[test]
fn display_chars_verbatim() {
assert_eq!(KeyCode::Char('a').to_string(), "a");
assert_eq!(KeyCode::Char(' ').to_string(), " ");
assert_eq!(KeyCode::Char('?').to_string(), "?");
}
#[test]
fn display_unidentified_is_placeholder() {
assert_eq!(KeyCode::Unidentified.to_string(), "?");
}
}