bamboo-core 0.2.1

Vietnamese input method engine written in Rust
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! The core engine that processes keypresses and maintains the IME state.

use crate::config::Config;
use crate::input_method::{InputMethod, Rule};
use crate::mode::{Mode, OutputOptions};

const MAX_ACTIVE_TRANS: usize = 32;

/// Represents a single keypress or a transformation derived from it (e.g., adding a mark or tone).
#[derive(Clone, Debug)]
pub struct Transformation {
    /// The rule that was applied.
    pub rule: Rule,
    /// The index of the transformation in the composition that this transformation targets (if any).
    /// For example, a tone mark transformation targets an earlier vowel.
    pub target: Option<usize>,
    /// Whether the resulting character should be uppercase.
    pub is_upper_case: bool,
}

#[inline]
fn lower(c: char) -> char {
    if c.is_ascii() {
        c.to_ascii_lowercase()
    } else {
        c.to_lowercase().next().unwrap_or(c)
    }
}

#[inline]
fn is_upper(c: char) -> bool {
    if c.is_ascii() { c.is_ascii_uppercase() } else { lower(c) != c }
}

fn uoh_tail_match(s: &str) -> bool {
    for pat in ["", "ưo"] {
        if let Some(idx) = s.find(pat) {
            let after = &s[idx + pat.len()..];
            if after.chars().next().is_some_and(|c| c.is_alphabetic()) {
                return true;
            }
        }
    }
    false
}

/// The main stateful processor of the Vietnamese Input Method Engine.
///
/// It maintains an internal buffer of transformations and produces the correctly marked Vietnamese text.
pub struct Engine {
    committed_text: String,
    /// Stack-allocated buffer for the current syllable to avoid heap allocations.
    active_buffer: [Option<Transformation>; MAX_ACTIVE_TRANS],
    active_len: usize,

    input_method: InputMethod,
    all_rules: Box<[Rule]>,
    ascii_rule_indices: [(u16, u16); 128],
    non_ascii_rule_indices: Box<[(char, (u16, u16))]>,
    ascii_effect_keys: [bool; 128],
    non_ascii_effect_keys: Vec<char>,
    config: Config,
}

impl Engine {
    /// Creates a new engine with the specified input method and default configuration.
    pub fn new(input_method: InputMethod) -> Self {
        Self::with_config(input_method, Config::default())
    }

    /// Creates a new engine with a specific input method and configuration.
    pub fn with_config(input_method: InputMethod, config: Config) -> Self {
        let mut rules_by_key: std::collections::BTreeMap<char, Vec<Rule>> =
            std::collections::BTreeMap::new();
        for rule in &input_method.rules {
            let key = lower(rule.key);
            rules_by_key.entry(key).or_default().push(rule.clone());
        }

        let total_rules: usize = rules_by_key.values().map(|v| v.len()).sum();
        let mut all_rules_vec = Vec::with_capacity(total_rules);
        let mut ascii_rule_indices = [(0u16, 0u16); 128];
        let mut non_ascii_indices_vec = Vec::new();

        for (key, rules) in rules_by_key {
            let start = all_rules_vec.len() as u16;
            all_rules_vec.extend(rules);
            let end = all_rules_vec.len() as u16;
            if key.is_ascii() {
                ascii_rule_indices[key as usize] = (start, end);
            } else {
                non_ascii_indices_vec.push((key, (start, end)));
            }
        }

        let mut ascii_effect_keys = [false; 128];
        let mut non_ascii_effect_keys: Vec<char> = Vec::new();
        for key in &input_method.keys {
            if key.is_ascii() {
                ascii_effect_keys[*key as usize] = true;
            } else {
                non_ascii_effect_keys.push(*key);
            }
        }
        non_ascii_effect_keys.sort_unstable();
        non_ascii_effect_keys.dedup();

        Self {
            committed_text: String::new(),
            active_buffer: std::array::from_fn(|_| None),
            active_len: 0,
            input_method,
            all_rules: all_rules_vec.into_boxed_slice(),
            ascii_rule_indices,
            non_ascii_rule_indices: non_ascii_indices_vec.into_boxed_slice(),
            ascii_effect_keys,
            non_ascii_effect_keys,
            config,
        }
    }

    /// Internal helper to get active composition as a slice of references.
    fn active_composition(&self) -> Vec<&Transformation> {
        self.active_buffer[..self.active_len]
            .iter()
            .map(|opt| opt.as_ref().unwrap())
            .collect()
    }

    /// Internal helper to get active composition as a Vec for mutation.
    fn active_composition_owned(&self) -> Vec<Transformation> {
        self.active_buffer[..self.active_len]
            .iter()
            .map(|opt| opt.as_ref().unwrap().clone())
            .collect()
    }

    fn set_active_composition(&mut self, comp: Vec<Transformation>) {
        self.active_len = comp.len().min(MAX_ACTIVE_TRANS);
        for (i, t) in comp.into_iter().enumerate().take(MAX_ACTIVE_TRANS) {
            self.active_buffer[i] = Some(t);
        }
    }

    pub fn config(&self) -> Config {
        self.config
    }

    /// Updates the engine configuration.
    pub fn set_config(&mut self, config: Config) {
        self.config = config;
    }

    /// Returns a copy of the current input method.
    pub fn input_method(&self) -> InputMethod {
        self.input_method.clone()
    }

    fn get_applicable_rules(&self, key: char) -> &[Rule] {
        let key = lower(key);
        if key.is_ascii() {
            let (start, end) = self.ascii_rule_indices[key as usize];
            &self.all_rules[start as usize..end as usize]
        } else {
            self.non_ascii_rule_indices
                .binary_search_by_key(&key, |(k, _)| *k)
                .map(|idx| {
                    let (start, end) = self.non_ascii_rule_indices[idx].1;
                    &self.all_rules[start as usize..end as usize]
                })
                .unwrap_or(&[])
        }
    }

    fn can_process_key_raw(&self, lower_key: char) -> bool {
        if crate::utils::is_alpha(lower_key)
            || (lower_key.is_ascii()
                && self.ascii_effect_keys[lower_key as usize])
            || self.non_ascii_effect_keys.binary_search(&lower_key).is_ok()
        {
            return true;
        }
        if crate::utils::is_word_break_symbol(lower_key) {
            return false;
        }
        crate::utils::is_vietnamese_rune(lower_key)
    }

    fn generate_transformations(
        &self,
        composition: &mut Vec<Transformation>,
        key: char,
        is_upper_case: bool,
    ) {
        let lower_key = lower(key);
        let refs: Vec<&Transformation> = composition.iter().collect();
        let mut transformations = crate::bamboo_util::generate_transformations(
            &refs,
            self.get_applicable_rules(lower_key),
            self.config.to_flags(),
            lower_key,
            is_upper_case,
        );

        if transformations.is_empty() {
            transformations =
                crate::bamboo_util::generate_fallback_transformations(
                    self.get_applicable_rules(lower_key),
                    lower_key,
                    is_upper_case,
                );
            let mut new_comp = composition.clone();
            new_comp.extend(transformations.clone());
            let new_refs: Vec<&Transformation> = new_comp.iter().collect();

            if !self.input_method.super_keys.is_empty() {
                let current_str = crate::flattener::flatten(
                    &new_refs,
                    OutputOptions::TONE_LESS | OutputOptions::LOWER_CASE,
                );
                if uoh_tail_match(&current_str) {
                    let (target, rule) = crate::bamboo_util::find_target(
                        &new_refs,
                        self.get_applicable_rules(
                            self.input_method.super_keys[0],
                        ),
                        self.config.to_flags(),
                    );
                    if let (Some(target), Some(mut rule)) = (target, rule) {
                        rule.key = '\0';
                        transformations.push(Transformation {
                            rule,
                            target: Some(target),
                            is_upper_case: false,
                        });
                    }
                }
            }
        }
        composition.extend(transformations);
        if self.config.to_flags() & crate::bamboo_util::EFREE_TONE_MARKING != 0
            && self.is_valid_internal(composition, false)
        {
            let extra = crate::bamboo_util::refresh_last_tone_target(
                composition,
                self.config.to_flags() & crate::bamboo_util::ESTD_TONE_STYLE
                    != 0,
            );
            composition.extend(extra);
        }
    }

    fn new_composition(
        &self,
        mut composition: Vec<Transformation>,
        key: char,
        is_upper_case: bool,
    ) -> Vec<Transformation> {
        let (prev_refs, _) = crate::bamboo_util::extract_last_syllable(
            &composition,
            Some(&self.input_method.keys),
        );
        let syllable_abs_start = prev_refs.len();
        let mut syllable = composition.split_off(syllable_abs_start);
        let mut previous = composition;

        let offset = syllable_abs_start;
        if offset != 0 {
            for t in &mut syllable {
                if let Some(target) = t.target {
                    t.target = Some(target.saturating_sub(offset));
                }
            }
        }
        self.generate_transformations(&mut syllable, key, is_upper_case);
        if offset != 0 {
            for t in &mut syllable {
                if let Some(target) = t.target {
                    t.target = Some(target + offset);
                }
            }
        }
        previous.extend(syllable);
        previous
    }

    /// Processes a string of characters and returns the current active word.
    pub fn process(&mut self, s: &str, mode: Mode) -> String {
        self.process_str(s, mode).output()
    }

    /// Processes a string of characters and returns a reference to the engine.
    pub fn process_str(&mut self, s: &str, mode: Mode) -> &Self {
        for key in s.chars() {
            self.process_key(key, mode);
        }
        self
    }

    /// Processes a single character.
    ///
    /// The `mode` determines whether to apply Vietnamese transformation rules.
    pub fn process_key(&mut self, key: char, mode: Mode) {
        let lower_key = lower(key);
        let is_upper_case = is_upper(key);

        if mode == Mode::English || !self.can_process_key_raw(lower_key) {
            if crate::utils::is_word_break_symbol(lower_key) {
                self.commit();
            }
            let trans = crate::bamboo_util::new_appending_trans(
                lower_key,
                is_upper_case,
            );
            self.push_active(trans);
            if crate::utils::is_word_break_symbol(lower_key) {
                self.commit();
            }
            return;
        }

        let current = self.active_composition_owned();
        let next = self.new_composition(current, lower_key, is_upper_case);
        self.set_active_composition(next);
    }

    fn push_active(&mut self, trans: Transformation) {
        if self.active_len < MAX_ACTIVE_TRANS {
            self.active_buffer[self.active_len] = Some(trans);
            self.active_len += 1;
        }
    }

    /// Clears the active syllable buffer.
    pub fn commit(&mut self) {
        if self.active_len == 0 {
            return;
        }
        let word = self.output();
        self.committed_text.push_str(&word);
        self.active_len = 0;
    }

    /// Returns the currently active syllable as a string.
    pub fn output(&self) -> String {
        let comp = self.active_composition_owned();
        crate::flattener::flatten_slice(&comp, OutputOptions::NONE)
    }

    /// Returns the processed string according to the specified options.
    ///
    /// This can be used to get the full text (committed + active) or variations like toneless text.
    pub fn get_processed_str(&self, options: OutputOptions) -> String {
        let active_comp = self.active_composition_owned();
        if options.contains(OutputOptions::FULL_TEXT) {
            let mut result = self.committed_text.clone();
            result.push_str(&crate::flattener::flatten_slice(
                &active_comp,
                options,
            ));
            return result;
        }
        if options.contains(OutputOptions::PUNCTUATION_MODE) {
            let refs = self.active_composition();
            let (_, tail) = crate::bamboo_util::extract_last_word_with_punctuation_marks_refs(&refs, &self.input_method.keys);
            return crate::flattener::flatten(&tail, OutputOptions::NONE);
        }
        crate::flattener::flatten_slice(&active_comp, options)
    }

    /// Checks if the current composition forms a valid Vietnamese syllable.
    pub fn is_valid(&self, input_is_full_complete: bool) -> bool {
        let comp = self.active_composition_owned();
        self.is_valid_internal(&comp, input_is_full_complete)
    }

    fn is_valid_internal(
        &self,
        composition: &[Transformation],
        input_is_full_complete: bool,
    ) -> bool {
        let refs: Vec<&Transformation> = composition.iter().collect();
        crate::bamboo_util::is_valid(&refs, input_is_full_complete)
    }

    /// Restores the last word in the composition.
    ///
    /// If `to_vietnamese` is true, it attempts to re-apply Vietnamese transformations.
    pub fn restore_last_word(&mut self, to_vietnamese: bool) {
        let comp = self.active_composition_owned();
        let refs: Vec<&Transformation> = comp.iter().collect();
        let (prev_refs, _) = crate::bamboo_util::extract_last_word(
            &refs,
            Some(&self.input_method.keys),
        );
        let prev_len = prev_refs.len();

        let mut active = comp;
        let last = active.split_off(prev_len);
        let mut previous = active;

        if last.is_empty() {
            self.set_active_composition(previous);
            return;
        }
        if !to_vietnamese {
            previous.extend(crate::bamboo_util::break_composition_slice(&last));
            self.set_active_composition(previous);
            return;
        }

        let mut new_comp: Vec<Transformation> = Vec::new();
        for t in last {
            if t.rule.key == '\0' {
                continue;
            }
            new_comp =
                self.new_composition(new_comp, t.rule.key, t.is_upper_case);
        }
        previous.extend(new_comp);
        self.set_active_composition(previous);
    }

    pub fn remove_last_char(&mut self, refresh_last_tone_target: bool) {
        let comp = self.active_composition_owned();
        let last_appending_idx =
            crate::bamboo_util::find_last_appending_trans_idx(&comp);
        let Some(last_idx) = last_appending_idx else {
            return;
        };

        let last_appending_key = comp[last_idx].rule.key;
        if !self.can_process_key_raw(last_appending_key) {
            let mut next = comp;
            next.pop();
            self.set_active_composition(next);
            return;
        }

        let refs: Vec<&Transformation> = comp.iter().collect();
        let (previous_slice, _) = crate::bamboo_util::extract_last_word(
            &refs,
            Some(&self.input_method.keys),
        );
        let prev_len = previous_slice.len();

        let mut previous = comp;
        let last_comb = previous.split_off(prev_len);

        let mut new_comb: Vec<Transformation> = Vec::new();
        for (i, t) in last_comb.into_iter().enumerate() {
            let actual_idx = prev_len + i;
            if actual_idx == last_idx {
                continue;
            }
            if let Some(target) = t.target
                && target == last_idx
            {
                continue;
            }
            new_comb.push(t);
        }

        if refresh_last_tone_target {
            let extra = crate::bamboo_util::refresh_last_tone_target(
                &mut new_comb,
                self.config.to_flags() & crate::bamboo_util::ESTD_TONE_STYLE
                    != 0,
            );
            new_comb.extend(extra);
        }

        previous.extend(new_comb);
        self.set_active_composition(previous);
    }

    pub fn reset(&mut self) {
        self.committed_text.clear();
        self.active_len = 0;
    }
}