Skip to main content

msime_engine/wubi/
code.rs

1//! 构建补充表与个人新词学习共用的五笔词组取码规则。
2
3/// 为两个及以上汉字取词组码;回调必须返回该字所有最长全码一致的前缀。
4/// 无法取码时返回对应字,空串或单字返回 `None`。
5pub fn phrase_code(
6    word: &str,
7    mut prefix: impl FnMut(char, usize) -> Option<String>,
8) -> Option<std::result::Result<String, char>> {
9    let chars: Vec<char> = word.chars().collect();
10    let parts = match chars.len() {
11        0 | 1 => return None,
12        2 => vec![(chars[0], 2), (chars[1], 2)],
13        3 => vec![(chars[0], 1), (chars[1], 1), (chars[2], 2)],
14        n => vec![
15            (chars[0], 1),
16            (chars[1], 1),
17            (chars[2], 1),
18            (chars[n - 1], 1),
19        ],
20    };
21    let mut result = String::with_capacity(4);
22    for (character, length) in parts {
23        let Some(code) = prefix(character, length) else {
24            return Some(Err(character));
25        };
26        if code.len() != length || !code.bytes().all(|byte| byte.is_ascii_lowercase()) {
27            return Some(Err(character));
28        }
29        result.push_str(&code);
30    }
31    Some(Ok(result))
32}