chewing 0.12.0

The Chewing (酷音) intelligent Zhuyin input method.
Documentation
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use std::{
    error::Error,
    fmt::{Display, Write},
    str::FromStr,
};

/// The category of the phonetic symbols
///
/// Zhuyin, or Bopomofo, consists of 37 letters and 4 tone marks. They are
/// categorized into one of the four categories:
///
/// 1. Initial sounds: ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙ
/// 2. Medial glides: ㄧㄨㄩ
/// 3. Rimes: ㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦ
/// 4. Tonal marks: ˙ˊˇˋ
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BopomofoKind {
    /// Initial sounds: ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙ
    Initial,
    /// Medial glides: ㄧㄨㄩ
    Medial,
    /// Rimes: ㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦ
    Rime,
    /// Tonal marks: ˙ˊˇˋ
    Tone,
}

/// Zhuyin Fuhao, often shortened as zhuyin and commonly called bopomofo
///
/// <https://simple.m.wikipedia.org/wiki/Zhuyin>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Bopomofo {
    /// Zhuyin Fuhao: ㄅ
    B,
    /// Zhuyin Fuhao: ㄆ
    P,
    /// Zhuyin Fuhao: ㄇ
    M,
    /// Zhuyin Fuhao: ㄈ
    F,
    /// Zhuyin Fuhao: ㄉ
    D,
    /// Zhuyin Fuhao: ㄊ
    T,
    /// Zhuyin Fuhao: ㄋ
    N,
    /// Zhuyin Fuhao: ㄌ
    L,
    /// Zhuyin Fuhao: ㄍ
    G,
    /// Zhuyin Fuhao: ㄎ
    K,
    /// Zhuyin Fuhao: ㄏ
    H,
    /// Zhuyin Fuhao: ㄐ
    J,
    /// Zhuyin Fuhao: ㄑ
    Q,
    /// Zhuyin Fuhao: ㄒ
    X,
    /// Zhuyin Fuhao: ㄓ
    ZH,
    /// Zhuyin Fuhao: ㄔ
    CH,
    /// Zhuyin Fuhao: ㄕ
    SH,
    /// Zhuyin Fuhao: ㄖ
    R,
    /// Zhuyin Fuhao: ㄗ
    Z,
    /// Zhuyin Fuhao: ㄘ
    C,
    /// Zhuyin Fuhao: ㄙ
    S,
    /// Zhuyin Fuhao: 一
    I,
    /// Zhuyin Fuhao: ㄨ
    U,
    /// Zhuyin Fuhao: ㄩ
    IU,
    /// Zhuyin Fuhao: ㄚ
    A,
    /// Zhuyin Fuhao: ㄛ
    O,
    /// Zhuyin Fuhao: ㄜ
    E,
    /// Zhuyin Fuhao: ㄝ
    EH,
    /// Zhuyin Fuhao: ㄞ
    AI,
    /// Zhuyin Fuhao: ㄟ
    EI,
    /// Zhuyin Fuhao: ㄠ
    AU,
    /// Zhuyin Fuhao: ㄡ
    OU,
    /// Zhuyin Fuhao: ㄢ
    AN,
    /// Zhuyin Fuhao: ㄣ
    EN,
    /// Zhuyin Fuhao: ㄤ
    ANG,
    /// Zhuyin Fuhao: ㄥ
    ENG,
    /// Zhuyin Fuhao: ㄦ
    ER,
    /// Tonal mark: ˙
    TONE5,
    /// Tonal mark: ˊ
    TONE2,
    /// Tonal mark: ˇ
    TONE3,
    /// Tonal mark: ˋ
    TONE4,
    /// Tonal mark: ˉ
    TONE1,
}

use self::Bopomofo::*;

const INITIAL_MAP: [Bopomofo; 21] = [
    B, P, M, F, D, T, N, L, G, K, H, J, Q, X, ZH, CH, SH, R, Z, C, S,
];
const MEDIAL_MAP: [Bopomofo; 3] = [I, U, IU];
const RIME_MAP: [Bopomofo; 13] = [A, O, E, EH, AI, EI, AU, OU, AN, EN, ANG, ENG, ER];
const TONE_MAP: [Bopomofo; 4] = [TONE5, TONE2, TONE3, TONE4];

impl Bopomofo {
    /// Returns [`BopomofoKind`] of the [`Bopomofo`] symbol. See [`BopomofoKind`] to know more about
    /// each kind category.
    pub const fn kind(&self) -> BopomofoKind {
        match self {
            B | P | M | F | D | T | N | L | G | K | H | J | Q | X | ZH | CH | SH | R | Z | C
            | S => BopomofoKind::Initial,
            I | U | IU => BopomofoKind::Medial,
            A | O | E | EH | AI | EI | AU | OU | AN | EN | ANG | ENG | ER => BopomofoKind::Rime,
            TONE1 | TONE2 | TONE3 | TONE4 | TONE5 => BopomofoKind::Tone,
        }
    }
    /// Returns a [`Bopomofo`] that is categorized as initial sounds based on the index. It will
    /// return [`None`] if the index is larger than 20. The index order is listed below starting
    /// from 0.
    ///
    /// - Initial sounds: ㄅㄆㄇㄈㄉㄊㄋㄌㄍㄎㄏㄐㄑㄒㄓㄔㄕㄖㄗㄘㄙ
    pub(super) const fn from_initial(index: u16) -> Option<Bopomofo> {
        if index as usize >= INITIAL_MAP.len() {
            return None;
        }
        Some(INITIAL_MAP[index as usize])
    }
    /// Returns a [`Bopomofo`] that is categorized as medial glides based on the index. It will
    /// return [`None`] if the index is larger than 2. The index order is listed below starting
    /// from 0.
    ///
    /// - Medial glides: ㄧㄨㄩ
    pub(super) const fn from_medial(index: u16) -> Option<Bopomofo> {
        if index as usize >= MEDIAL_MAP.len() {
            return None;
        }
        Some(MEDIAL_MAP[index as usize])
    }
    /// Returns a [`Bopomofo`] that is categorized as rimes based on the index. It will
    /// return [`None`] if the index is larger than 12. The index order is listed below starting
    /// from 0.
    ///
    /// - Rimes: ㄚㄛㄜㄝㄞㄟㄠㄡㄢㄣㄤㄥㄦ
    pub(super) const fn from_rime(index: u16) -> Option<Bopomofo> {
        if index as usize >= RIME_MAP.len() {
            return None;
        }
        Some(RIME_MAP[index as usize])
    }
    /// Returns a [`Bopomofo`] that is categorized as tonal marks based on the index. It will
    /// return [`None`] if the index is larger than 3. The index order is listed below starting
    /// from 0.
    ///
    /// - Tonal marks: ˙ˊˇˋ
    pub(super) const fn from_tone(index: u16) -> Option<Bopomofo> {
        if index as usize >= TONE_MAP.len() {
            return None;
        }
        Some(TONE_MAP[index as usize])
    }
    pub(super) const fn index(&self) -> u16 {
        match self {
            B | I | A | TONE5 => 1,
            P | U | O | TONE2 => 2,
            M | IU | E | TONE3 => 3,
            F | EH | TONE4 => 4,
            D | AI | TONE1 => 5,
            T | EI => 6,
            N | AU => 7,
            L | OU => 8,
            G | AN => 9,
            K | EN => 10,
            H | ANG => 11,
            J | ENG => 12,
            Q | ER => 13,
            X => 14,
            ZH => 15,
            CH => 16,
            SH => 17,
            R => 18,
            Z => 19,
            C => 20,
            S => 21,
        }
    }
}

impl Display for Bopomofo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_char((*self).into())
    }
}

impl FromStr for Bopomofo {
    type Err = ParseBopomofoError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars();
        let Some(bopomofo) = chars.next().map(|ch| ch.try_into()) else {
            return Err(ParseBopomofoError::empty());
        };
        if let Some(ch) = chars.next() {
            return Err(ParseBopomofoError::invalid_symbol(ch));
        }
        bopomofo
    }
}

impl From<Bopomofo> for char {
    fn from(bopomofo: Bopomofo) -> Self {
        match bopomofo {
            B => '',
            P => '',
            M => '',
            F => '',
            D => '',
            T => '',
            N => '',
            L => '',
            G => '',
            K => '',
            H => '',
            J => '',
            Q => '',
            X => '',
            ZH => '',
            CH => '',
            SH => '',
            R => '',
            Z => '',
            C => '',
            S => '',
            A => '',
            O => '',
            E => '',
            EH => '',
            AI => '',
            EI => '',
            AU => '',
            OU => '',
            AN => '',
            EN => '',
            ANG => '',
            ENG => '',
            ER => '',
            I => '',
            U => '',
            IU => '',
            TONE1 => 'ˉ',
            TONE5 => '˙',
            TONE2 => 'ˊ',
            TONE3 => 'ˇ',
            TONE4 => 'ˋ',
        }
    }
}

impl TryFrom<char> for Bopomofo {
    type Error = ParseBopomofoError;

    fn try_from(c: char) -> Result<Bopomofo, ParseBopomofoError> {
        match c {
            '' => Ok(B),
            '' => Ok(P),
            '' => Ok(M),
            '' => Ok(F),
            '' => Ok(D),
            '' => Ok(T),
            '' => Ok(N),
            '' => Ok(L),
            '' => Ok(G),
            '' => Ok(K),
            '' => Ok(H),
            '' => Ok(J),
            '' => Ok(Q),
            '' => Ok(X),
            '' => Ok(ZH),
            '' => Ok(CH),
            '' => Ok(SH),
            '' => Ok(R),
            '' => Ok(Z),
            '' => Ok(C),
            '' => Ok(S),
            '' => Ok(A),
            '' => Ok(O),
            '' => Ok(E),
            '' => Ok(EH),
            '' => Ok(AI),
            '' => Ok(EI),
            '' => Ok(AU),
            '' => Ok(OU),
            '' => Ok(AN),
            '' => Ok(EN),
            '' => Ok(ANG),
            '' => Ok(ENG),
            '' => Ok(ER),
            '' => Ok(I),
            '' => Ok(U),
            '' => Ok(IU),
            'ˉ' => Ok(TONE1),
            '˙' => Ok(TONE5),
            'ˊ' => Ok(TONE2),
            'ˇ' => Ok(TONE3),
            'ˋ' => Ok(TONE4),
            _ => Err(ParseBopomofoError::invalid_symbol(c)),
        }
    }
}

/// Enum to store the various types of errors that can cause parsing a bopomofo
/// symbol to fail.
///
/// # Example
///
/// ```
/// # use std::str::FromStr;
/// # use chewing::zhuyin::Bopomofo;
/// if let Err(e) = Bopomofo::from_str("a12") {
///     println!("Failed conversion to bopomofo: {e}");
/// }
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BopomofoErrorKind {
    /// Value being parsed is empty.
    Empty,
    /// Contains an invalid symbol.
    InvalidSymbol(char),
}

/// An error which can be returned when parsing an bopomofo symbol.
///
/// # Potential causes
///
/// Among other causes, `ParseBopomofoError` can be thrown because of leading or trailing whitespace
/// in the string e.g., when it is obtained from the standard input.
/// Using the [`str::trim()`] method ensures that no whitespace remains before parsing.
///
/// # Example
///
/// ```
/// # use std::str::FromStr;
/// # use chewing::zhuyin::Bopomofo;
/// if let Err(e) = Bopomofo::from_str("a12") {
///     println!("Failed conversion to bopomofo: {e}");
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParseBopomofoError {
    kind: BopomofoErrorKind,
}

impl ParseBopomofoError {
    fn empty() -> ParseBopomofoError {
        Self {
            kind: BopomofoErrorKind::Empty,
        }
    }
    fn invalid_symbol(ch: char) -> ParseBopomofoError {
        Self {
            kind: BopomofoErrorKind::InvalidSymbol(ch),
        }
    }
    /// Outputs the detailed cause of parsing an bopomofo failing.
    pub fn kind(&self) -> &BopomofoErrorKind {
        &self.kind
    }
}

impl Display for ParseBopomofoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Parse bopomofo error: {:?}", self.kind)
    }
}

impl Error for ParseBopomofoError {}

#[cfg(test)]
mod tests {
    use super::Bopomofo;
    use crate::zhuyin::{BopomofoErrorKind, ParseBopomofoError};

    #[test]
    fn parse() {
        assert_eq!(Ok(Bopomofo::B), "".parse())
    }

    #[test]
    fn parse_empty() {
        assert_eq!(Err(ParseBopomofoError::empty()), "".parse::<Bopomofo>());
        assert_eq!(
            &BopomofoErrorKind::Empty,
            ParseBopomofoError::empty().kind()
        );
    }

    #[test]
    fn parse_invalid() {
        assert_eq!(
            Err(ParseBopomofoError::invalid_symbol('b')),
            "abc".parse::<Bopomofo>()
        );
        assert_eq!(
            &BopomofoErrorKind::InvalidSymbol('c'),
            ParseBopomofoError::invalid_symbol('c').kind()
        );
    }

    #[test]
    fn to_string() {
        assert_eq!(Bopomofo::B.to_string(), "")
    }
}