Convert string to key code

rc keymaps list keycodes as strings. These need to be converted to
numeric keycodes before the keymap can be loaded. So, add a function
to convert a string to keycode.

Signed-off-by: Sean Young <sean@mess.org>
This commit is contained in:
Sean Young 2021-06-27 10:04:44 +01:00 committed by Jeff Hiner
parent f93ca1f13f
commit d694443d53
3 changed files with 25 additions and 0 deletions

View file

@ -182,6 +182,20 @@ macro_rules! evdev_enum {
impl $t { impl $t {
$($(#[$attr])* pub const $c: Self = Self($val);)* $($(#[$attr])* pub const $c: Self = Self($val);)*
} }
impl std::str::FromStr for $t {
type Err = crate::EnumParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let map: &[(&'static str, $t)] = &[
$((stringify!($c), Self::$c),)*
];
match map.iter().find(|e| e.0 == s) {
Some(e) => Ok(e.1),
None => Err(crate::EnumParseError(())),
}
}
}
impl std::fmt::Debug for $t { impl std::fmt::Debug for $t {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self { match *self {

View file

@ -290,3 +290,6 @@ pub(crate) fn nix_err(err: nix::Error) -> io::Error {
pub(crate) unsafe fn cast_to_bytes<T: ?Sized>(mem: &T) -> &[u8] { pub(crate) unsafe fn cast_to_bytes<T: ?Sized>(mem: &T) -> &[u8] {
std::slice::from_raw_parts(mem as *const T as *const u8, std::mem::size_of_val(mem)) std::slice::from_raw_parts(mem as *const T as *const u8, std::mem::size_of_val(mem))
} }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumParseError(());

View file

@ -555,3 +555,11 @@ evdev_enum!(
BTN_TRIGGER_HAPPY39 = 0x2e6, BTN_TRIGGER_HAPPY39 = 0x2e6,
BTN_TRIGGER_HAPPY40 = 0x2e7, BTN_TRIGGER_HAPPY40 = 0x2e7,
); );
#[test]
fn from_str() {
use std::str::FromStr;
assert_eq!(Key::from_str("KEY_A"), Ok(Key::KEY_A));
assert!(Key::from_str("KEY_FOOBAR").is_err());
}