Skip to main content

keyboard_codes/
utils.rs

1//! Utility functions and helpers
2
3use crate::types::Platform;
4
5/// Check if a key code is valid for the given platform
6///
7/// This is a basic validation that checks if the code is within
8/// a reasonable range for the platform.
9pub fn is_valid_key_code(code: usize, platform: Platform) -> bool {
10    match platform {
11        Platform::Windows => code <= 0xFF, // Windows uses 8-bit key codes
12        Platform::Linux => code <= 0x2FF,  // Linux uses wider range (up to 767 decimal)
13        Platform::MacOS => code <= 0x7F,   // macOS uses 7-bit key codes
14    }
15}
16
17/// Normalize a key code by masking out any extraneous bits
18///
19/// Some platforms may have additional bits set in key codes
20/// that are not part of the core key code value.
21pub fn normalize_key_code(code: usize, platform: Platform) -> usize {
22    match platform {
23        Platform::Windows => code & 0xFF, // Mask to 8 bits
24        Platform::Linux => code & 0x3FF,  // Mask to 10 bits (Linux scancodes can go up to 0x2FF)
25        Platform::MacOS => code & 0x7F,   // Mask to 7 bits
26    }
27}
28
29/// Check if a string is a valid key name
30///
31/// Valid key names are alphanumeric and start with a letter.
32pub fn is_valid_key_name(name: &str) -> bool {
33    if name.is_empty() {
34        return false;
35    }
36
37    // First character must be a letter
38    if !name.chars().next().unwrap().is_ascii_alphabetic() {
39        return false;
40    }
41
42    // All characters must be alphanumeric
43    name.chars().all(|c| c.is_ascii_alphanumeric())
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_is_valid_key_code() {
52        assert!(is_valid_key_code(0x41, Platform::Windows));
53        assert!(is_valid_key_code(0x100, Platform::Linux));
54        assert!(!is_valid_key_code(0x100, Platform::Windows));
55    }
56
57    #[test]
58    fn test_normalize_key_code() {
59        // Windows: mask to 8 bits
60        assert_eq!(normalize_key_code(0x141, Platform::Windows), 0x41);
61        assert_eq!(normalize_key_code(0x1FF, Platform::Windows), 0xFF);
62
63        // Linux: mask to 10 bits (0x3FF = 1023 decimal)
64        assert_eq!(normalize_key_code(0x341, Platform::Linux), 0x341); // 0x341 = 833 decimal
65        assert_eq!(normalize_key_code(0x7FF, Platform::Linux), 0x3FF); // Should be masked to max
66
67        // macOS: mask to 7 bits
68        assert_eq!(normalize_key_code(0x81, Platform::MacOS), 0x01);
69        assert_eq!(normalize_key_code(0xFF, Platform::MacOS), 0x7F);
70    }
71
72    #[test]
73    fn test_is_valid_key_name() {
74        assert!(is_valid_key_name("A"));
75        assert!(is_valid_key_name("Enter"));
76        assert!(is_valid_key_name("F12"));
77        assert!(!is_valid_key_name(""));
78        assert!(!is_valid_key_name("123"));
79        assert!(!is_valid_key_name("Key-Name"));
80    }
81}