1
//! Big5 encoding.
2

            
3
// Note that we need to recreate Encoder/Decoders in these functions due to this note in the
4
// encoding_rs documentation:
5
//
6
// > Once the stream has ended, the Decoder object must not be used anymore. That is, you need to
7
// > create another one to process another stream.
8

            
9
use encoding_rs::{DecoderResult, EncoderResult, BIG5};
10

            
11
pub fn unicode_to_big5(u: char) -> Option<u16> {
12
    let mut encoder = BIG5.new_encoder();
13
    let src: &mut [u8] = &mut [0, 0, 0, 0];
14
    let mut dst = [0, 0];
15
    let (res, _read, written) =
16
        encoder.encode_from_utf8_without_replacement(u.encode_utf8(src), &mut dst, true);
17
    match res {
18
        EncoderResult::InputEmpty => {
19
            match written {
20
                1 => Some(u16::from(dst[0])),
21
                2 => Some(u16::from_be_bytes(dst)),
22
                _ => None, // should not happen
23
            }
24
        }
25
        EncoderResult::OutputFull => None, // should not happen
26
        EncoderResult::Unmappable(_) => None,
27
    }
28
}
29

            
30
/// Decodes a Big5 character into a Unicode char
31
pub fn big5_to_unicode(ch: u16) -> Option<char> {
32
    // Strictly speaking, the Big5 encoding contains only double-byte character set characters.
33
    // However, in practice, the Big5 codes are always used together with an unspecified,
34
    // system-dependent single-byte character set (ASCII, or an 8-bit character set such as code
35
    // page 437), so that you will find a mix of DBCS characters and single-byte characters in
36
    // Big5-encoded text. Bytes in the range 0x00 to 0x7f that are not part of a double-byte
37
    // character are assumed to be single-byte characters.
38
    //
39
    // — https://en.wikipedia.org/wiki/Big5
40
    //
41
    // encoding_rs::Decoder for Big5 returns 0 for single-byte codes, so we handle ASCII manually.
42
    if ch < 128 {
43
        return Some(ch as u8 as char);
44
    }
45

            
46
    let mut decoder = BIG5.new_decoder_without_bom_handling();
47
    let src = ch.to_be_bytes();
48
    let mut dst = [0, 0, 0, 0];
49
    let (res, _read, written) = decoder.decode_to_utf8_without_replacement(&src, &mut dst, true);
50
    match res {
51
        DecoderResult::InputEmpty if written > 0 => {
52
            // Safety: It is assumed that decode_to_utf8_without_replacement will yield valid utf-8
53
            // output in dst. Additionally because written is > 1 we assume chars will yield a char
54
            // thus it should always be valid utf-8.
55
            let s = unsafe { std::str::from_utf8_unchecked(&dst[..written]) }
56
                .chars()
57
                .next()
58
                .unwrap();
59
            Some(s)
60
        }
61
        DecoderResult::InputEmpty |
62
        DecoderResult::OutputFull | // should not happen
63
        DecoderResult::Malformed(_, _) => None,
64
    }
65
}
66

            
67
#[cfg(test)]
68
mod tests {
69
    use super::*;
70

            
71
    #[test]
72
    fn ascii_to_big5() {
73
        for i in 0..128 {
74
            let u = char::from(i);
75
            assert_eq!(unicode_to_big5(u), Some(u16::from(i)));
76
        }
77
    }
78

            
79
    #[test]
80
    fn chinese_to_big5() {
81
        assert_eq!(unicode_to_big5('好'), Some(0xA66E));
82
    }
83

            
84
    #[test]
85
    fn greek_to_big5() {
86
        assert_eq!(unicode_to_big5('ε'), Some(0xA360));
87
    }
88

            
89
    #[test]
90
    fn hindi_to_big5() {
91
        assert_eq!(unicode_to_big5('म'), None);
92
    }
93

            
94
    #[test]
95
    fn big5_to_ascii() {
96
        for i in 0..128 {
97
            assert_eq!(big5_to_unicode(u16::from(i)), Some(char::from(i)));
98
        }
99
    }
100

            
101
    #[test]
102
    fn chinese_big5_to_unicode() {
103
        assert_eq!(big5_to_unicode(0xA66E), Some('好'));
104
    }
105

            
106
    #[test]
107
    fn greek_big5_to_unicode() {
108
        assert_eq!(big5_to_unicode(0xA360), Some('ε'));
109
    }
110

            
111
    #[test]
112
    fn graphical_big5_to_unicode() {
113
        assert_eq!(big5_to_unicode(0xA143), Some('。'));
114
    }
115
}