// autocorrect: false
use regex::Regex;
use std::collections::HashMap;
lazy_static! {
static ref CHAR_WIDTH_MAP: HashMap<&'static str, &'static str> = map!(
"a" => "a", "b" => "b", "c" => "c", "d" => "d", "e" => "e", "f" => "f", "g" => "g", "h" => "h", "i" => "i", "j" => "j", "k" => "k", "l" => "l", "m" => "m", "n" => "n", "o" => "o", "p" => "p", "q" => "q", "r" => "r", "s" => "s", "t" => "t", "u" => "u", "v" => "v", "w" => "w", "x" => "x", "y" => "y", "z" => "z", "A" => "A", "B" => "B", "C" => "C", "D" => "D", "E" => "E", "F" => "F", "G" => "G", "H" => "H", "I" => "I", "J" => "J", "K" => "K", "L" => "L", "M" => "M", "N" => "N", "O" => "O", "P" => "P", "Q" => "Q", "R" => "R", "S" => "S", "T" => "T", "U" => "U", "V" => "V", "W" => "W", "X" => "X", "Y" => "Y", "Z" => "Z", "1" => "1", "2" => "2", "3" => "3", "4" => "4", "5" => "5", "6" => "6", "7" => "7", "8" => "8", "9" => "9", "0" => "0", " " => " "
);
static ref HALF_TIME_RE: Regex = regexp!("{}", r"(\d)(:)(\d)");
}
pub fn halfwidth(text: &str) -> String {
let mut out = String::new();
for str in text.split("") {
let new_str = CHAR_WIDTH_MAP.get(str);
if new_str != None {
out.push_str(new_str.unwrap())
} else {
out.push_str(str)
}
}
// Fix 12:00 -> 12:00
out = HALF_TIME_RE
.replace_all(&out, |cap: ®ex::Captures| cap[0].replace(':', ":"))
.to_string();
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_halfwidth() {
let source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
assert_eq!(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
halfwidth(source)
);
assert_eq!(
"他说:我们将在16:32分出发去CBD中心。",
halfwidth("他说:我们将在16:32分出发去CBD中心。")
);
// Fullwidth space
assert_eq!(
"ジョイフル-後場売り気配 200 店舗を閉鎖へ 7 月以降、不採算店中心に",
halfwidth("ジョイフル-後場売り気配 200 店舗を閉鎖へ 7 月以降、不採算店中心に")
);
}
}