Skip to main content

atmos/kernel/
ime.rs

1// src/ime.rs - IME (Input Method Editor) Foundation
2#![allow(dead_code)]
3
4extern crate alloc;
5use alloc::string::String;
6use alloc::vec::Vec;
7
8const CONNECTION_DATA: &[u8] = include_bytes!("mozc_connection.bin");
9const CONNECTION_HEADER_LEN: usize = 14;
10const CONNECTION_COST_WEIGHT: i32 = 6;
11const MISSING_CONNECTION_INDEX: u16 = 0xFFFF;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ImeMode {
15    English,
16    Japanese,
17}
18
19/// FEP(全角/日本語)モードが有効かどうかを描画側から参照するためのグローバルフラグ。
20/// カーソル色の切り替え(半角=青系 / 全角=赤系)に使用する。
21static FEP_ACTIVE: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
22
23/// FEP(全角)モードが有効かどうかを返す。
24pub fn is_fep_active() -> bool {
25    FEP_ACTIVE.load(core::sync::atomic::Ordering::Relaxed)
26}
27
28/// カーソル描画色を返す。全角モード時は赤系、半角時は従来の青系。
29pub fn cursor_color() -> u32 {
30    if is_fep_active() {
31        0xFFE03C3C // 赤系(全角/FEP 有効)
32    } else {
33        0xFF756CE0 // 従来の青系(半角)
34    }
35}
36
37#[derive(Debug, Clone)]
38pub struct DictEntry {
39    /// 埋め込み辞書(`mozc_dict.txt`)の中を指す。【2026-10-24】従来は見出し・単語を全部 `String` に
40    /// 複製し、4MB の辞書がヒープを約 18MB 使っていた(YouTube 視聴でヒープが尽きた一因)。
41    pub word: &'static str,
42    pub left_id: u16,
43    pub right_id: u16,
44    pub cost: i32,
45}
46
47#[derive(Clone)]
48struct PathState {
49    text: String,
50    cost: i32,
51    right_id: u16,
52}
53
54pub struct ImeState {
55    pub mode: ImeMode,
56    pub dictionary: alloc::collections::BTreeMap<&'static str, Vec<DictEntry>>,
57    pub dict_loaded: bool,
58    pub composing: bool,
59    pub romaji_buf: String,
60    pub kana_buf: String,
61    pub converting: bool,
62    pub candidates: alloc::vec::Vec<String>,
63    pub selected_idx: usize,
64}
65
66impl Default for ImeState {
67    fn default() -> Self {
68        Self::new()
69    }
70}
71
72impl ImeState {
73    pub const fn new() -> Self {
74        Self {
75            mode: ImeMode::English,
76            dictionary: alloc::collections::BTreeMap::new(),
77            dict_loaded: false,
78            composing: false,
79            romaji_buf: String::new(), // This should use String::new() instead of String::new() in const fn if not possible. But String::new() is const since 1.39.
80            kana_buf: String::new(),
81            converting: false,
82            candidates: alloc::vec::Vec::new(),
83            selected_idx: 0,
84        }
85    }
86
87    pub fn load_dict(&mut self) {
88        if self.dict_loaded {
89            return;
90        }
91        crate::info!("[SYS] IME: Loading Mozc-based dictionary...");
92        let s = include_str!("mozc_dict.txt");
93        for line in s.lines() {
94            let line = line.trim();
95            if line.is_empty() || line.starts_with('#') {
96                continue;
97            }
98
99            let mut cols = line.split('\t');
100            let Some(yomi) = cols.next() else {
101                continue;
102            };
103            let Some(left_id) = parse_u16(cols.next()) else {
104                continue;
105            };
106            let Some(right_id) = parse_u16(cols.next()) else {
107                continue;
108            };
109            let Some(cost) = parse_i32(cols.next()) else {
110                continue;
111            };
112            let Some(word) = cols.next() else {
113                continue;
114            };
115
116            if yomi.is_empty() || word.is_empty() {
117                continue;
118            }
119
120            self.dictionary
121                .entry(yomi)
122                .or_default()
123                .push(DictEntry {
124                    word,
125                    left_id,
126                    right_id,
127                    cost,
128                });
129        }
130        self.dict_loaded = true;
131        crate::info!(
132            "IME: Loaded Mozc-based dictionary with {} readings",
133            self.dictionary.len()
134        );
135    }
136
137    pub fn toggle_mode(&mut self, to_japanese: bool) {
138        self.load_dict(); // Ensure dict is loaded on first use
139
140        if to_japanese {
141            self.mode = ImeMode::Japanese;
142        } else {
143            self.mode = ImeMode::English;
144        }
145        FEP_ACTIVE.store(
146            self.mode == ImeMode::Japanese,
147            core::sync::atomic::Ordering::Relaxed,
148        );
149        self.clear();
150    }
151
152    pub fn clear(&mut self) {
153        self.romaji_buf.clear();
154        self.kana_buf.clear();
155        self.composing = false;
156        self.converting = false;
157        self.candidates.clear();
158        self.selected_idx = 0;
159    }
160
161    pub fn input_char(&mut self, c: char) {
162        if self.mode == ImeMode::English {
163            return;
164        }
165
166        // ローマ字入力対象: 英字 + IME テーブルに含まれる記号
167        const ROMAJI_SYMBOLS: &[char] = &[
168            '-', ',', '.', '/', '!', '?', '[', ']', '{', '}', '(', ')', '~',
169        ];
170        if c.is_ascii_alphabetic() || ROMAJI_SYMBOLS.contains(&c) {
171            self.romaji_buf.push(c.to_ascii_lowercase());
172            self.composing = true;
173            self.convert_romaji();
174        } else {
175            self.kana_buf.push(c);
176            self.composing = true;
177        }
178    }
179
180    pub fn backspace(&mut self) {
181        if !self.romaji_buf.is_empty() {
182            self.romaji_buf.pop();
183            self.convert_romaji();
184        } else if !self.kana_buf.is_empty() {
185            self.kana_buf.pop();
186        }
187        if self.kana_buf.is_empty() && self.romaji_buf.is_empty() {
188            self.composing = false;
189            self.converting = false;
190            self.candidates.clear();
191            self.selected_idx = 0;
192        }
193    }
194
195    fn convert_romaji(&mut self) {
196        let table = [
197            // ---- 拗音(3文字 → 先に判定) ----
198            ("kya", "きゃ"),
199            ("kyu", "きゅ"),
200            ("kyo", "きょ"),
201            ("sha", "しゃ"),
202            ("shu", "しゅ"),
203            ("sho", "しょ"),
204            ("sya", "しゃ"),
205            ("syu", "しゅ"),
206            ("syo", "しょ"),
207            ("shi", "し"),
208            ("cha", "ちゃ"),
209            ("chu", "ちゅ"),
210            ("cho", "ちょ"),
211            ("chi", "ち"),
212            ("tya", "ちゃ"),
213            ("tyu", "ちゅ"),
214            ("tyo", "ちょ"),
215            ("tsu", "つ"),
216            ("tu", "つ"),
217            ("nya", "にゃ"),
218            ("nyu", "にゅ"),
219            ("nyo", "にょ"),
220            ("hya", "ひゃ"),
221            ("hyu", "ひゅ"),
222            ("hyo", "ひょ"),
223            ("mya", "みゃ"),
224            ("myu", "みゅ"),
225            ("myo", "みょ"),
226            ("rya", "りゃ"),
227            ("ryu", "りゅ"),
228            ("ryo", "りょ"),
229            ("gya", "ぎゃ"),
230            ("gyu", "ぎゅ"),
231            ("gyo", "ぎょ"),
232            ("jya", "じゃ"),
233            ("jyu", "じゅ"),
234            ("jyo", "じょ"),
235            ("zya", "じゃ"),
236            ("zyu", "じゅ"),
237            ("zyo", "じょ"),
238            ("dya", "ぢゃ"),
239            ("dyu", "ぢゅ"),
240            ("dyo", "ぢょ"),
241            ("bya", "びゃ"),
242            ("byu", "びゅ"),
243            ("byo", "びょ"),
244            ("pya", "ぴゃ"),
245            ("pyu", "ぴゅ"),
246            ("pyo", "ぴょ"),
247            // 小書き仮名 (l- prefix)
248            ("la", "ぁ"),
249            ("li", "ぃ"),
250            ("lu", "ぅ"),
251            ("le", "ぇ"),
252            ("lo", "ぉ"),
253            ("lya", "ゃ"),
254            ("lyu", "ゅ"),
255            ("lyo", "ょ"),
256            ("lwa", "ゎ"),
257            ("ltu", "っ"),
258            ("ltsu", "っ"),
259            ("xa", "ぁ"),
260            ("xi", "ぃ"),
261            ("xu", "ぅ"),
262            ("xe", "ぇ"),
263            ("xo", "ぉ"),
264            ("xya", "ゃ"),
265            ("xyu", "ゅ"),
266            ("xyo", "ょ"),
267            ("xtu", "っ"),
268            ("xtsu", "っ"),
269            // ---- 母音 ----
270            ("a", "あ"),
271            ("i", "い"),
272            ("u", "う"),
273            ("e", "え"),
274            ("o", "お"),
275            // ---- か行 ----
276            ("ka", "か"),
277            ("ki", "き"),
278            ("ku", "く"),
279            ("ke", "け"),
280            ("ko", "こ"),
281            // ---- さ行 ----
282            ("sa", "さ"),
283            ("si", "し"),
284            ("su", "す"),
285            ("se", "せ"),
286            ("so", "そ"),
287            // ---- た行 ----
288            ("ta", "た"),
289            ("ti", "ち"),
290            ("te", "て"),
291            ("to", "と"),
292            // ---- な行 ----
293            ("na", "な"),
294            ("ni", "に"),
295            ("nu", "ぬ"),
296            ("ne", "ね"),
297            ("no", "の"),
298            // ---- は行 ----
299            ("ha", "は"),
300            ("hi", "ひ"),
301            ("fu", "ふ"),
302            ("hu", "ふ"),
303            ("he", "へ"),
304            ("ho", "ほ"),
305            // ---- ま行 ----
306            ("ma", "ま"),
307            ("mi", "み"),
308            ("mu", "む"),
309            ("me", "め"),
310            ("mo", "も"),
311            // ---- や行 ----
312            ("ya", "や"),
313            ("yu", "ゆ"),
314            ("yo", "よ"),
315            // ---- ら行 ----
316            ("ra", "ら"),
317            ("ri", "り"),
318            ("ru", "る"),
319            ("re", "れ"),
320            ("ro", "ろ"),
321            // ---- わ行・ん ----
322            ("wa", "わ"),
323            ("wi", "ゐ"),
324            ("we", "ゑ"),
325            ("wo", "を"),
326            ("wha", "うぁ"),
327            ("whi", "うぃ"),
328            ("whe", "うぇ"),
329            ("who", "うぉ"),
330            // ---- が行 ----
331            ("ga", "が"),
332            ("gi", "ぎ"),
333            ("gu", "ぐ"),
334            ("ge", "げ"),
335            ("go", "ご"),
336            // ---- ざ行 ----
337            ("za", "ざ"),
338            ("ji", "じ"),
339            ("zi", "じ"),
340            ("zu", "ず"),
341            ("ze", "ぜ"),
342            ("zo", "ぞ"),
343            ("ja", "じゃ"),
344            ("ju", "じゅ"),
345            ("jo", "じょ"),
346            // ---- だ行 ----
347            ("da", "だ"),
348            ("di", "ぢ"),
349            ("du", "づ"),
350            ("de", "で"),
351            ("do", "ど"),
352            // ---- ば行 ----
353            ("ba", "ば"),
354            ("bi", "び"),
355            ("bu", "ぶ"),
356            ("be", "べ"),
357            ("bo", "ぼ"),
358            // ---- ぱ行 ----
359            ("pa", "ぱ"),
360            ("pi", "ぴ"),
361            ("pu", "ぷ"),
362            ("pe", "ぺ"),
363            ("po", "ぽ"),
364            // ---- ヴ行(外来語) ----
365            ("va", "ヴぁ"),
366            ("vi", "ヴぃ"),
367            ("vu", "ヴ"),
368            ("ve", "ヴぇ"),
369            ("vo", "ヴぉ"),
370            // ---- ファ行(外来語) ----
371            ("fa", "ふぁ"),
372            ("fi", "ふぃ"),
373            ("fe", "ふぇ"),
374            ("fo", "ふぉ"),
375            // ---- ティ・ディ(外来語) ----
376            ("thi", "てぃ"),
377            ("dhi", "でぃ"),
378            ("dhu", "どぅ"),
379            ("dho", "どぉ"),
380            ("twu", "とぅ"),
381            // ---- 記号・句読点 ----
382            (",", "、"),
383            (".", "。"),
384            ("/", "・"),
385            ("!", "!"),
386            ("?", "?"),
387            ("[", "「"),
388            ("]", "」"),
389            ("{", "『"),
390            ("}", "』"),
391            ("(", "("),
392            (")", ")"),
393            // ---- 長音符・その他 ----
394            ("-", "ー"),
395            ("~", "〜"),
396        ];
397
398        let mut temp_kana = String::new();
399        let mut romaji = self.romaji_buf.clone();
400
401        loop {
402            let mut matched = false;
403            for (rom, kana) in table.iter() {
404                if romaji.starts_with(rom) {
405                    temp_kana.push_str(kana);
406                    romaji = String::from(romaji.get(rom.len()..).unwrap_or(""));
407                    matched = true;
408                    break;
409                }
410            }
411            if !matched {
412                // 促音化(っ): 同じ子音の連続。ただし 'n' は撥音(ん)扱いなので除外。
413                if romaji.len() > 1
414                    && romaji.as_bytes()[0] != b'n'
415                    && romaji.as_bytes()[0] == romaji.as_bytes()[1]
416                {
417                    temp_kana.push('っ');
418                    romaji = String::from(romaji.get(1..).unwrap_or(""));
419                } else if starts_with_n_before_consonant(&romaji) {
420                    temp_kana.push('ん');
421                    romaji = String::from(romaji.get(1..).unwrap_or(""));
422                } else {
423                    break;
424                }
425            }
426        }
427
428        if !temp_kana.is_empty() {
429            self.kana_buf.push_str(&temp_kana);
430            self.romaji_buf = romaji;
431        }
432    }
433
434    fn flush_pending_romaji(&mut self) {
435        if self.romaji_buf == "n" {
436            self.kana_buf.push('ん');
437            self.romaji_buf.clear();
438        }
439    }
440
441    pub fn handle_space(&mut self) -> bool {
442        if !self.composing {
443            return false;
444        }
445
446        self.flush_pending_romaji();
447
448        if !self.converting {
449            // First time pressing space -> start conversion
450            self.candidates.clear();
451
452            self.build_conversion_candidates();
453
454            // 変換不能でも入力を確定できるよう、元のひらがなを候補に追加
455            let hiragana = self.kana_buf.clone();
456            if !self.candidates.contains(&hiragana) {
457                self.candidates.push(hiragana);
458            }
459
460            // カタカナ変換結果を候補に追加
461            let katakana = to_katakana(&self.kana_buf);
462            if !self.candidates.contains(&katakana) {
463                self.candidates.push(katakana);
464            }
465
466            self.converting = true;
467            self.selected_idx = 0;
468        } else {
469            // Already converting -> next candidate
470            if !self.candidates.is_empty() {
471                self.selected_idx = (self.selected_idx + 1) % self.candidates.len();
472            }
473        }
474        true
475    }
476
477    fn build_conversion_candidates(&mut self) {
478        const BEAM_WIDTH: usize = 8;
479        const MAX_CANDIDATES: usize = 12;
480        const UNKNOWN_COST: i32 = 12000;
481        const SEGMENT_COST: i32 = 1000;
482
483        let input = self.kana_buf.as_str();
484        let positions = byte_positions(input);
485        if positions.len() <= 1 {
486            return;
487        }
488
489        let mut lattice: Vec<Vec<PathState>> = Vec::new();
490        for _ in 0..positions.len() {
491            lattice.push(Vec::new());
492        }
493        lattice[0].push(PathState {
494            text: String::new(),
495            cost: 0,
496            right_id: 0,
497        });
498
499        for start_idx in 0..positions.len() - 1 {
500            if lattice[start_idx].is_empty() {
501                continue;
502            }
503
504            let start_byte = positions[start_idx];
505            let states = lattice[start_idx].clone();
506
507            for end_idx in start_idx + 1..positions.len() {
508                let end_byte = positions[end_idx];
509                let yomi = input.get(start_byte..end_byte).unwrap_or("");
510
511                if let Some(entries) = self.dictionary.get(yomi) {
512                    for state in states.iter() {
513                        for entry in entries {
514                            let mut text = state.text.clone();
515                            text.push_str(entry.word);
516                            let cost = state.cost
517                                + adjusted_entry_cost(yomi, entry)
518                                + transition_cost(state.right_id, entry.left_id)
519                                + SEGMENT_COST;
520                            push_beam(
521                                &mut lattice[end_idx],
522                                PathState {
523                                    text,
524                                    cost,
525                                    right_id: entry.right_id,
526                                },
527                                BEAM_WIDTH,
528                            );
529                        }
530                    }
531                }
532            }
533
534            let next_byte = positions[start_idx + 1];
535            let unknown = input.get(start_byte..next_byte).unwrap_or("");
536            for state in states.iter() {
537                let mut text = state.text.clone();
538                text.push_str(unknown);
539                push_beam(
540                    &mut lattice[start_idx + 1],
541                    PathState {
542                        text,
543                        cost: state.cost + UNKNOWN_COST,
544                        right_id: 0,
545                    },
546                    BEAM_WIDTH,
547                );
548            }
549        }
550
551        let Some(final_states) = lattice.last_mut() else {
552            return;
553        };
554        final_states.sort_by_key(|state| state.cost);
555
556        for state in final_states.iter() {
557            if self.candidates.len() >= MAX_CANDIDATES {
558                break;
559            }
560            if !self.candidates.contains(&state.text) {
561                self.candidates.push(state.text.clone());
562            }
563        }
564    }
565
566    pub fn handle_enter(&mut self) -> Option<String> {
567        self.flush_pending_romaji();
568
569        if self.converting {
570            // 候補が空/範囲外でもパニックしないよう get で安全に取り出す。
571            let res = self
572                .candidates
573                .get(self.selected_idx)
574                .cloned()
575                .unwrap_or_else(|| self.kana_buf.clone());
576            self.clear();
577            Some(res)
578        } else if self.composing {
579            let res = self.kana_buf.clone();
580            self.clear();
581            Some(res)
582        } else {
583            None
584        }
585    }
586
587    /// Escape キー: 変換中なら変換をキャンセルしてひらがなに戻る。未変換なら全クリア。
588    pub fn cancel(&mut self) {
589        if self.converting {
590            self.converting = false;
591            self.candidates.clear();
592            self.selected_idx = 0;
593            // kana_buf はそのまま残す(ひらがな入力状態に戻る)
594        } else {
595            self.clear();
596        }
597    }
598
599    /// 数字キー(1〜9)で候補を直接選択して確定。確定テキストを返す。
600    pub fn select_candidate_by_number(&mut self, n: usize) -> Option<String> {
601        if !self.converting || self.candidates.is_empty() {
602            return None;
603        }
604        let idx = n.saturating_sub(1); // 1→0, 2→1, ...
605        if idx < self.candidates.len() {
606            let res = self.candidates[idx].clone();
607            self.clear();
608            Some(res)
609        } else {
610            None
611        }
612    }
613
614    pub fn get_display_text(&self) -> String {
615        if self.converting && !self.candidates.is_empty() {
616            self.candidates[self.selected_idx].clone()
617        } else {
618            self.kana_buf.clone() + &self.romaji_buf
619        }
620    }
621}
622
623/// IME の自己テスト。ローマ字→かな変換と、かな→漢字変換(Mozc 辞書+ラティス)を検証する。
624/// 起動時に `IME_SELFTEST: PASS n/n` を出す(CI スモークの判定マーカー)。
625pub fn selftest() -> (usize, usize) {
626    // ローマ字 → ひらがな(辞書不要・決定的)。
627    let kana_cases: &[(&str, &str)] = &[
628        ("nihon", "にほん"),
629        ("konnichiha", "こんにちは"),
630        ("gakkou", "がっこう"),
631        ("denwa", "でんわ"),
632        ("kanji", "かんじ"),
633        ("kya", "きゃ"),
634        ("sha", "しゃ"),
635        ("chi", "ち"),
636        ("tte", "って"),
637        ("shinbun", "しんぶん"),
638        ("wo", "を"),
639        ("sakka", "さっか"),
640        ("zasshi", "ざっし"),
641        ("annai", "あんない"),
642    ];
643    // かな(ローマ字入力経由)→ 漢字。候補に期待語が含まれるか。
644    let conv_cases: &[(&str, &str)] = &[
645        ("nihon", "日本"),
646        ("denwa", "電話"),
647        ("gakkou", "学校"),
648        ("kanji", "漢字"),
649    ];
650
651    let mut passed = 0;
652    let total = kana_cases.len() + conv_cases.len();
653
654    // 辞書ロードは高コスト(約 7.8 万エントリ)なので 1 度だけ行い、ケース間は clear() で再利用する。
655    let mut ime = ImeState::new();
656    ime.toggle_mode(true); // 日本語モード(辞書ロード込み・1 回のみ)
657
658    for (rom, kana) in kana_cases {
659        ime.clear();
660        for c in rom.chars() {
661            ime.input_char(c);
662        }
663        ime.flush_pending_romaji();
664        if &ime.kana_buf == kana {
665            passed += 1;
666        } else {
667            crate::println!(
668                "IME_SELFTEST FAIL: `{}` => `{}` (want `{}`)",
669                rom,
670                ime.kana_buf,
671                kana
672            );
673        }
674    }
675
676    for (rom, kanji) in conv_cases {
677        ime.clear();
678        for c in rom.chars() {
679            ime.input_char(c);
680        }
681        ime.handle_space();
682        if ime.candidates.iter().any(|c| c == kanji) {
683            passed += 1;
684        } else {
685            crate::println!(
686                "IME_SELFTEST FAIL: convert `{}` missing `{}` (got {:?})",
687                rom,
688                kanji,
689                ime.candidates
690            );
691        }
692    }
693
694    (passed, total)
695}
696
697fn parse_u16(s: Option<&str>) -> Option<u16> {
698    s?.parse::<u16>().ok()
699}
700
701fn parse_i32(s: Option<&str>) -> Option<i32> {
702    s?.parse::<i32>().ok()
703}
704
705fn byte_positions(s: &str) -> Vec<usize> {
706    let mut positions = Vec::new();
707    positions.push(0);
708    for (idx, _) in s.char_indices().skip(1) {
709        positions.push(idx);
710    }
711    positions.push(s.len());
712    positions
713}
714
715fn transition_cost(prev_right_id: u16, left_id: u16) -> i32 {
716    mozc_connection_cost(prev_right_id, left_id)
717        .map(|cost| cost / CONNECTION_COST_WEIGHT)
718        .unwrap_or_else(|| {
719            if prev_right_id == 0 || left_id == 0 {
720                0
721            } else if prev_right_id == left_id {
722                40
723            } else {
724                220
725            }
726        })
727}
728
729fn mozc_connection_cost(prev_right_id: u16, left_id: u16) -> Option<i32> {
730    if CONNECTION_DATA.len() < CONNECTION_HEADER_LEN || &CONNECTION_DATA[..8] != b"MOZCCON1" {
731        return None;
732    }
733
734    let context_count = read_u16(CONNECTION_DATA, 8)? as usize;
735    let right_count = read_u16(CONNECTION_DATA, 10)? as usize;
736    let left_count = read_u16(CONNECTION_DATA, 12)? as usize;
737    let prev_right_id = prev_right_id as usize;
738    let left_id = left_id as usize;
739
740    if prev_right_id >= context_count || left_id >= context_count {
741        return None;
742    }
743
744    let right_lookup_offset = CONNECTION_HEADER_LEN;
745    let left_lookup_offset = right_lookup_offset + context_count * 2;
746    let matrix_offset = left_lookup_offset + context_count * 2;
747    let right_index = read_u16(CONNECTION_DATA, right_lookup_offset + prev_right_id * 2)?;
748    let left_index = read_u16(CONNECTION_DATA, left_lookup_offset + left_id * 2)?;
749
750    if right_index == MISSING_CONNECTION_INDEX || left_index == MISSING_CONNECTION_INDEX {
751        return None;
752    }
753
754    let right_index = right_index as usize;
755    let left_index = left_index as usize;
756    if right_index >= right_count || left_index >= left_count {
757        return None;
758    }
759
760    let cost_offset = matrix_offset + (right_index * left_count + left_index) * 2;
761    read_u16(CONNECTION_DATA, cost_offset).map(|cost| cost as i32)
762}
763
764fn adjusted_entry_cost(yomi: &str, entry: &DictEntry) -> i32 {
765    let mut cost = entry.cost;
766    let yomi_len = yomi.chars().count() as i32;
767    if entry.word.chars().all(is_hiragana) && !prefers_hiragana(yomi) {
768        cost += 2500;
769    }
770    if yomi_len == 1 && !entry.word.chars().all(is_hiragana) {
771        cost += 1500;
772    }
773    if yomi_len > 1 && entry.word.chars().all(is_katakana) {
774        cost += 1000;
775    }
776    cost -= (yomi_len - 1).max(0) * 1000;
777    cost
778}
779
780fn push_beam(beam: &mut Vec<PathState>, state: PathState, limit: usize) {
781    if let Some(existing) = beam
782        .iter_mut()
783        .find(|candidate| candidate.text == state.text)
784    {
785        if state.cost < existing.cost {
786            *existing = state;
787        }
788    } else {
789        beam.push(state);
790    }
791
792    beam.sort_by_key(|candidate| candidate.cost);
793    if beam.len() > limit {
794        beam.truncate(limit);
795    }
796}
797
798fn starts_with_n_before_consonant(s: &str) -> bool {
799    if !s.starts_with('n') || s.len() < 2 {
800        return false;
801    }
802
803    let next = s.as_bytes()[1] as char;
804    // 母音・y 以外の子音が続けば撥音「ん」。`nn` も撥音(n を 1 つ消費し、
805    // 残り 1 つは次の母音と結合: konnichiha → こんにちは)。
806    !matches!(next, 'a' | 'i' | 'u' | 'e' | 'o' | 'y')
807}
808
809fn read_u16(bytes: &[u8], offset: usize) -> Option<u16> {
810    if offset + 1 >= bytes.len() {
811        None
812    } else {
813        Some(u16::from_le_bytes([bytes[offset], bytes[offset + 1]]))
814    }
815}
816
817fn is_hiragana(c: char) -> bool {
818    ('\u{3041}'..='\u{3096}').contains(&c)
819}
820
821fn is_katakana(c: char) -> bool {
822    ('\u{30A1}'..='\u{30FA}').contains(&c) || c == 'ー'
823}
824
825fn prefers_hiragana(s: &str) -> bool {
826    matches!(
827        s,
828        "は" | "が"
829            | "を"
830            | "に"
831            | "へ"
832            | "と"
833            | "で"
834            | "も"
835            | "の"
836            | "や"
837            | "ね"
838            | "よ"
839            | "です"
840            | "ます"
841            | "でした"
842            | "ません"
843            | "ない"
844            | "いい"
845    )
846}
847
848// ひらがなをカタカナに変換するヘルパー関数
849fn to_katakana(s: &str) -> String {
850    let mut res = String::new();
851    for c in s.chars() {
852        if ('\u{3041}'..='\u{3096}').contains(&c) {
853            if let Some(kc) = core::char::from_u32(c as u32 + 0x60) {
854                res.push(kc);
855            } else {
856                res.push(c);
857            }
858        } else {
859            res.push(c);
860        }
861    }
862    res
863}