Skip to main content

keyrill_core/
mapping.rs

1//! Key-position maps between US QWERTY and Russian ЙЦУКЕН.
2//!
3//! A layout mistake changes which character a key types, not which key was pressed, so
4//! correction is a lookup per key rather than a transliteration: `g` and `п` share a key, and so
5//! do `[` and `х`. The map covers the 33 keys that type a Russian letter, unshifted and shifted:
6//! 32 keys that both Russian layout variants share, and the ё key, which the variants put in
7//! different places (see [`Keyboard`]).
8//!
9//! Every conversion works one UTF-16 unit at a time and passes a unit outside the map unchanged,
10//! so the output has the length of the input. Digits, the remaining punctuation, other scripts
11//! and unpaired surrogates come through as they were; nothing is normalized or decoded.
12
13const EN: &str = "qwertyuiop[]asdfghjkl;'zxcvbnm,.";
14const RU: &str = "йцукенгшщзхъфывапролджэячсмитьбю";
15const EN_SHIFT: &str = "QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>";
16const RU_SHIFT: &str = "ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";
17
18/// Russian layout variant. In this map the two variants differ only in the key that types ё.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub enum Keyboard {
21    /// Apple's Russian layout, with ё at the US backslash key.
22    #[default]
23    Apple,
24    /// Russian PC layout, with ё at the US backtick key.
25    Pc,
26}
27
28/// Direction of a conversion.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum Mapping {
31    /// Convert every EN/RU letter to the character on the same key in the other layout, in
32    /// either direction, and leave every other unit unchanged. A Russian letter can map to
33    /// punctuation (`х` to `[`), which a second pass then leaves alone, so `Manual` is not an
34    /// involution.
35    Manual,
36    /// Read each US character in the map as the Russian character on the same key.
37    EnToRu,
38    /// Read each Russian character in the map as the US character on the same key.
39    RuToEn,
40}
41
42/// Whether a unit is an EN/RU letter: `A`-`Z`, `a`-`z`, `А`-`я`, `Ё` or `ё`. [`Mapping::Manual`],
43/// the word session and language context detection all use this letter set.
44pub fn is_letter(unit: u16) -> bool {
45    matches!(unit, 0x41..=0x5a | 0x61..=0x7a | 0x410..=0x44f | 0x401 | 0x451)
46}
47
48/// Convert `text` unit by unit. The result has the same length, and a unit the map does not
49/// cover is copied unchanged.
50///
51/// ```
52/// use keyrill_core::mapping::{convert, Keyboard, Mapping};
53///
54/// let text = |s: &str| s.encode_utf16().collect::<Vec<u16>>();
55/// assert_eq!(convert(&text("ghbdtn"), Keyboard::Apple, Mapping::EnToRu), text("привет"));
56/// assert_eq!(convert(&text("руддщ"), Keyboard::Apple, Mapping::RuToEn), text("hello"));
57/// // Manual mapping converts letters only and keeps punctuation.
58/// assert_eq!(convert(&text("Ghbdtn, vbh!"), Keyboard::Apple, Mapping::Manual), text("Привет, мир!"));
59/// ```
60pub fn convert(text: &[u16], keyboard: Keyboard, mapping: Mapping) -> Vec<u16> {
61    text.iter()
62        .map(|&unit| convert_unit(unit, keyboard, mapping))
63        .collect()
64}
65
66fn convert_unit(unit: u16, keyboard: Keyboard, mapping: Mapping) -> u16 {
67    if mapping == Mapping::Manual && !is_letter(unit) {
68        return unit;
69    }
70    let extra = match keyboard {
71        Keyboard::Apple => ('\\', '|'),
72        Keyboard::Pc => ('`', '~'),
73    };
74    for (en, ru) in EN
75        .chars()
76        .zip(RU.chars())
77        .chain(EN_SHIFT.chars().zip(RU_SHIFT.chars()))
78        .chain([(extra.0, 'ё'), (extra.1, 'Ё')])
79    {
80        if mapping != Mapping::RuToEn && unit == en as u16 {
81            return ru as u16;
82        }
83        if mapping != Mapping::EnToRu && unit == ru as u16 {
84            return en as u16;
85        }
86    }
87    unit
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn manual_preserves_unsupported_units_and_punctuation() {
96        let input: Vec<_> = "Ghbdtn, vbh!"
97            .encode_utf16()
98            .chain([0xd800, 0xdc00, 0xffff])
99            .collect();
100        let expected: Vec<_> = "Привет, мир!"
101            .encode_utf16()
102            .chain([0xd800, 0xdc00, 0xffff])
103            .collect();
104        assert_eq!(convert(&input, Keyboard::Apple, Mapping::Manual), expected);
105    }
106
107    #[test]
108    fn defined_physical_positions_round_trip() {
109        for keyboard in [Keyboard::Apple, Keyboard::Pc] {
110            for unit in EN.encode_utf16().chain(EN_SHIFT.encode_utf16()) {
111                let ru = convert(&[unit], keyboard, Mapping::EnToRu);
112                assert_eq!(convert(&ru, keyboard, Mapping::RuToEn), [unit]);
113            }
114        }
115    }
116
117    #[test]
118    fn unsupported_units_are_preserved_exhaustively() {
119        for unit in 0..=u16::MAX {
120            if !is_letter(unit) {
121                assert_eq!(convert(&[unit], Keyboard::Apple, Mapping::Manual), [unit]);
122            }
123        }
124    }
125}