1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
use encoding_rs::{DecoderResult, EncoderResult, BIG5};
pub fn unicode_to_big5(u: char) -> Option<u16> {
let mut encoder = BIG5.new_encoder();
let src: &mut [u8] = &mut [0, 0, 0, 0];
let mut dst = [0, 0];
let (res, _read, written) =
encoder.encode_from_utf8_without_replacement(u.encode_utf8(src), &mut dst, true);
match res {
EncoderResult::InputEmpty => {
match written {
1 => Some(u16::from(dst[0])),
2 => Some(u16::from_be_bytes(dst)),
_ => None,
}
}
EncoderResult::OutputFull => None,
EncoderResult::Unmappable(_) => None,
}
}
pub fn big5_to_unicode(ch: u16) -> Option<char> {
if ch < 128 {
return Some(ch as u8 as char);
}
let mut decoder = BIG5.new_decoder_without_bom_handling();
let src = ch.to_be_bytes();
let mut dst = [0, 0, 0, 0];
let (res, _read, written) = decoder.decode_to_utf8_without_replacement(&src, &mut dst, true);
match res {
DecoderResult::InputEmpty if written > 0 => {
let s = unsafe { std::str::from_utf8_unchecked(&dst[..written]) }
.chars()
.next()
.unwrap();
Some(s)
}
DecoderResult::InputEmpty |
DecoderResult::OutputFull |
DecoderResult::Malformed(_, _) => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ascii_to_big5() {
for i in 0..128 {
let u = char::from(i);
assert_eq!(unicode_to_big5(u), Some(u16::from(i)));
}
}
#[test]
fn chinese_to_big5() {
assert_eq!(unicode_to_big5('好'), Some(0xA66E));
}
#[test]
fn greek_to_big5() {
assert_eq!(unicode_to_big5('ε'), Some(0xA360));
}
#[test]
fn hindi_to_big5() {
assert_eq!(unicode_to_big5('म'), None);
}
#[test]
fn big5_to_ascii() {
for i in 0..128 {
assert_eq!(big5_to_unicode(u16::from(i)), Some(char::from(i)));
}
}
#[test]
fn chinese_big5_to_unicode() {
assert_eq!(big5_to_unicode(0xA66E), Some('好'));
}
#[test]
fn greek_big5_to_unicode() {
assert_eq!(big5_to_unicode(0xA360), Some('ε'));
}
#[test]
fn graphical_big5_to_unicode() {
assert_eq!(big5_to_unicode(0xA143), Some('。'));
}
}