1
//! Unicode script detection and language identification for text shaping
2
// Taken from: https://github.com/greyblake/whatlang-rs/blob/master/src/scripts/detect.rs
3
//
4
// See: https://github.com/greyblake/whatlang-rs/pull/67
5

            
6
// License:
7
//
8
// (The MIT License)
9
//
10
// Copyright (c) 2017 Sergey Potapov <blake131313@gmail.com>
11
// Copyright (c) 2014 Titus Wormer <tituswormer@gmail.com>
12
// Copyright (c) 2008 Kent S Johnson
13
// Copyright (c) 2006 Jacob R Rideout <kde@jacobrideout.net>
14
// Copyright (c) 2004 Maciej Ceglowski
15
//
16
// Permission is hereby granted, free of charge, to any person obtaining
17
// a copy of this software and associated documentation files (the
18
// 'Software'), to deal in the Software without restriction, including
19
// without limitation the rights to use, copy, modify, merge, publish,
20
// distribute, sublicense, and/or sell copies of the Software, and to
21
// permit persons to whom the Software is furnished to do so, subject to
22
// the following conditions:
23
//
24
// The above copyright notice and this permission notice shall be
25
// included in all copies or substantial portions of the Software.
26
//
27
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
28
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
30
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
31
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
32
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
33
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34

            
35
#[cfg(feature = "text_layout_hyphenation")]
36
use hyphenation::Language as HyphenationLanguage;
37
#[cfg(feature = "text_layout_hyphenation")]
38
pub use hyphenation::Language;
39

            
40
/// Stub Language enum for when hyphenation is not enabled.
41
/// This mirrors the variants used in script detection functions.
42
#[cfg(not(feature = "text_layout_hyphenation"))]
43
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44
#[allow(dead_code)]
45
pub enum Language {
46
    // Latin script languages
47
    EnglishUS,
48
    French,
49
    German1996,
50
    Spanish,
51
    Portuguese,
52
    Estonian,
53
    Hungarian,
54
    Polish,
55
    Czech,
56
    Slovak,
57
    Latvian,
58
    Lithuanian,
59
    Romanian,
60
    Turkish,
61
    Croatian,
62
    Icelandic,
63
    Welsh,
64
    NorwegianBokmal,
65
    Swedish,
66
    // Cyrillic script languages
67
    Russian,
68
    Ukrainian,
69
    Belarusian,
70
    Bulgarian,
71
    Macedonian,
72
    SerbianCyrillic,
73
    Mongolian,
74
    SlavonicChurch,
75
    // Greek script languages
76
    GreekMono,
77
    GreekPoly,
78
    Coptic,
79
    // Indic script languages
80
    Hindi,
81
    Bengali,
82
    Assamese,
83
    Marathi,
84
    Sanskrit,
85
    Gujarati,
86
    Panjabi,
87
    Kannada,
88
    Malayalam,
89
    Oriya,
90
    Tamil,
91
    Telugu,
92
    // Other scripts
93
    Georgian,
94
    Ethiopic,
95
    Thai,
96
    Chinese,
97
}
98

            
99
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
100
pub enum Script {
101
    // Keep this in alphabetic order (for C bindings)
102
    Arabic,
103
    Bengali,
104
    Cyrillic,
105
    Devanagari,
106
    Ethiopic,
107
    Georgian,
108
    Greek,
109
    Gujarati,
110
    Gurmukhi,
111
    Hangul,
112
    Hebrew,
113
    Hiragana,
114
    Kannada,
115
    Katakana,
116
    Khmer,
117
    Latin,
118
    Malayalam,
119
    Mandarin,
120
    Myanmar,
121
    Oriya,
122
    Sinhala,
123
    Tamil,
124
    Telugu,
125
    Thai,
126
}
127

            
128
// Is it space, punctuation or digit?
129
// Stop character is a character that does not give any value for script
130
// or language detection.
131
#[inline]
132
#[must_use]
133
2311550
pub const fn is_stop_char(ch: char) -> bool {
134
2311550
    matches!(ch, '\u{0000}'..='\u{0040}' | '\u{005B}'..='\u{0060}' | '\u{007B}'..='\u{007E}')
135
2311550
}
136

            
137
type ScriptChecker = (Script, fn(char) -> bool);
138
type ScriptCounter = (Script, fn(char) -> bool, usize);
139

            
140
const SCRIPT_CHECKERS: [ScriptChecker; 24] = [
141
    (Script::Latin, is_latin),
142
    (Script::Cyrillic, is_cyrillic),
143
    (Script::Arabic, is_arabic),
144
    (Script::Mandarin, is_mandarin),
145
    (Script::Devanagari, is_devanagari),
146
    (Script::Hebrew, is_hebrew),
147
    (Script::Ethiopic, is_ethiopic),
148
    (Script::Georgian, is_georgian),
149
    (Script::Bengali, is_bengali),
150
    (Script::Hangul, is_hangul),
151
    (Script::Hiragana, is_hiragana),
152
    (Script::Katakana, is_katakana),
153
    (Script::Greek, is_greek),
154
    (Script::Kannada, is_kannada),
155
    (Script::Tamil, is_tamil),
156
    (Script::Thai, is_thai),
157
    (Script::Gujarati, is_gujarati),
158
    (Script::Gurmukhi, is_gurmukhi),
159
    (Script::Telugu, is_telugu),
160
    (Script::Malayalam, is_malayalam),
161
    (Script::Oriya, is_oriya),
162
    (Script::Myanmar, is_myanmar),
163
    (Script::Sinhala, is_sinhala),
164
    (Script::Khmer, is_khmer),
165
];
166

            
167
/// Detect only a script by a given text
168
/// # Panics
169
///
170
/// Panics only if the internal script-counter table were empty, which cannot happen (it is a
171
/// fixed-size array).
172
133898
pub fn detect_script(text: &str) -> Option<Script> {
173
3213552
    let mut script_counters: [ScriptCounter; 24] = SCRIPT_CHECKERS.map(|(s, f)| (s, f, 0));
174

            
175
133898
    let half = text.chars().count() / 2;
176

            
177
2248023
    for ch in text.chars() {
178
2248023
        if is_stop_char(ch) {
179
365863
            continue;
180
1882160
        }
181

            
182
        // For performance reasons, we need to mutate script_counters by calling
183
        // `swap` function, it would not be possible to do using normal iterator.
184
8277340
        for i in 0..script_counters.len() {
185
8166733
            let found = {
186
8277340
                let (script, check_fn, ref mut count) = script_counters[i];
187
8277340
                if check_fn(ch) {
188
1631857
                    *count += 1;
189
1631857
                    if *count > half {
190
110607
                        return Some(script);
191
1521250
                    }
192
1521250
                    true
193
                } else {
194
6645483
                    false
195
                }
196
            };
197
            // Have to let borrow of count fall out of scope before doing swapping, or we could
198
            // do this above.
199
8166733
            if found {
200
                // If script was found, move it closer to the front.
201
                // If the text contains largely 1 or 2 scripts, this will
202
                // cause these scripts to be eventually checked first.
203
1521250
                if i > 0 {
204
401341
                    script_counters.swap(i - 1, i);
205
1119909
                }
206
1521250
                break;
207
6645483
            }
208
        }
209
    }
210

            
211
23291
    let (script, _, count) = script_counters
212
23291
        .iter()
213
23291
        .copied()
214
23291
        .max_by_key(|&(_, _, count)| count)
215
23291
        .unwrap();
216
23291
    if count != 0 {
217
1003
        Some(script)
218
    } else {
219
22288
        None
220
    }
221
133898
}
222

            
223
#[must_use]
224
254811
pub fn detect_char_script(ch: char) -> Option<Script> {
225
2846707
    for &(script, check_fn) in &SCRIPT_CHECKERS {
226
2777257
        if check_fn(ch) {
227
185361
            return Some(script);
228
2591896
        }
229
    }
230
69450
    None
231
254811
}
232

            
233
/// Iterates through the text once and returns as soon as an Assamese-specific character is found.
234
44
fn detect_bengali_language(text: &str) -> Language {
235
408104
    for c in text.chars() {
236
        // These characters are specific to Assamese in the Bengali script block.
237
        // We can return immediately as this is the highest priority check.
238
408104
        if matches!(c, '\u{09F0}' | '\u{09F1}') {
239
            // ৰ, ৱ
240
10
            return Language::Assamese;
241
408094
        }
242
    }
243
    // If we finish the loop without finding any Assamese characters, it's Bengali.
244
34
    Language::Bengali
245
44
}
246

            
247
52
fn detect_cyrillic_language(text: &str) -> Language {
248
408107
    for c in text.chars() {
249
408107
        match c {
250
            // Highest priority: Old Cyrillic characters for Slavonic Church. Return immediately.
251
8003
            '\u{0460}'..='\u{047F}' => return Language::SlavonicChurch,
252
            // Set flags for other languages. We don't return yet because a higher-priority
253
            // character (like the one above) could still appear.
254
1
            'ѓ' | 'ќ' | 'ѕ' => return Language::Macedonian,
255
2
            'ў' => return Language::Belarusian,
256
1
            'є' | 'і' | 'ї' | 'ґ' => return Language::Ukrainian,
257
1
            'ө' | 'ү' | 'һ' => return Language::Mongolian,
258
2
            'ј' | 'љ' | 'њ' | 'ћ' | 'ђ' | 'џ' => return Language::SerbianCyrillic,
259
            // Bulgarian 'ъ' is also in Russian, but 'щ' is a stronger indicator.
260
            // The logic implies that if either is present, it might be Bulgarian.
261
8
            'щ' => return Language::Bulgarian,
262
408088
            _ => {}
263
        }
264
    }
265

            
266
33
    Language::Russian
267
52
}
268

            
269
43
fn detect_devanagari_language(text: &str) -> Language {
270
208082
    for c in text.chars() {
271
208082
        match c {
272
            // Marathi has higher priority in the original logic. Return immediately.
273
6
            '\u{0933}' => return Language::Marathi, // ळ
274
            // Flag for Sanskrit Vedic extensions.
275
7964
            '\u{1CD0}'..='\u{1CFF}' => return Language::Sanskrit,
276
208073
            _ => (),
277
        }
278
    }
279

            
280
34
    Language::Hindi
281
43
}
282

            
283
54
fn detect_greek_language(text: &str) -> Language {
284
204545
    for c in text.chars() {
285
204545
        match c {
286
            // Coptic has higher priority. Return immediately.
287
4400
            '\u{2C80}'..='\u{2CFF}' => return Language::Coptic,
288
            // Flag for Greek Extended (Polytonic) characters.
289
4414
            '\u{1F00}'..='\u{1FFF}' => return Language::GreekPoly,
290
204533
            _ => {}
291
        }
292
    }
293

            
294
42
    Language::GreekMono
295
54
}
296

            
297
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
298
                                  // (or cross-type bindings that can't merge)
299
59542
fn detect_latin_language(text: &str) -> Language {
300
    // Flags for languages checked near the end of the original if-else chain.
301
59542
    let mut has_french_c = false;
302
59542
    let mut has_portuguese_o = false;
303
59542
    let mut has_portuguese_a = false;
304

            
305
2214473
    for c in text.chars() {
306
2214473
        match c {
307
            // --- Early Return Cases (in order of priority) ---
308
9
            'ß' => return Language::German1996,
309
2
            'ő' | 'ű' => return Language::Hungarian,
310
3
            'ł' => return Language::Polish,
311
2
            'ř' | 'ů' => return Language::Czech,
312
2
            'ľ' | 'ĺ' | 'ŕ' => return Language::Slovak,
313
            'ā' | 'ē' | 'ģ' | 'ī' | 'ķ' | 'ļ' | 'ņ' | 'ō' | 'ū' => {
314
2
                return Language::Latvian
315
            }
316
2
            'ą' | 'ę' | 'ė' | 'į' | 'ų' => return Language::Lithuanian,
317
2
            'ă' | 'ș' | 'ț' => return Language::Romanian,
318
2
            'ğ' | 'ı' | 'ş' => return Language::Turkish,
319
2
            'đ' => return Language::Croatian, /* Also used in Vietnamese, but Croatian is the */
320
            // original's intent
321
2
            'þ' | 'ð' => return Language::Icelandic,
322
2
            'ŵ' | 'ŷ' => return Language::Welsh,
323
3
            'æ' | 'ø' => return Language::NorwegianBokmal, // And Danish
324
3
            'å' => return Language::Swedish,               // And Norwegian, Finnish
325
2
            'ñ' => return Language::Spanish,
326
32
            'ä' | 'ö' | 'ü' => return Language::German1996,
327

            
328
            // NOTE: 'õ' is used by both Estonian and Portuguese
329
            // Since Estonian is checked first, it takes precedence.
330
5
            'õ' => has_portuguese_o = true,
331
5
            'ã' => has_portuguese_a = true,
332

            
333
            // --- Flag-setting Cases ---
334
7
            'ç' => has_french_c = true, // Also in Portuguese
335
5
            'á' | 'é' | 'í' | 'ó' | 'ú' => return Language::Spanish,
336

            
337
2214379
            _ => (),
338
        }
339
    }
340

            
341
    // decide between portuguese, estonian and french
342

            
343
59465
    if has_french_c && !has_portuguese_o && !has_portuguese_a {
344
3
        return Language::French;
345
59462
    }
346

            
347
59462
    if has_portuguese_o && !has_french_c && !has_portuguese_a {
348
2
        return Language::Estonian;
349
59460
    }
350

            
351
59460
    if has_portuguese_o || has_portuguese_a || has_french_c {
352
6
        return Language::Portuguese;
353
59454
    }
354

            
355
59454
    Language::EnglishUS
356
59542
}
357

            
358
#[allow(clippy::match_same_arms)]
359
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
360
// merge)
361
#[must_use]
362
60394
pub fn script_to_language(script: Script, text: &str) -> Language {
363
60394
    match script {
364
19
        Script::Ethiopic => Language::Ethiopic,
365
19
        Script::Georgian => Language::Georgian,
366
19
        Script::Gujarati => Language::Gujarati,
367
19
        Script::Gurmukhi => Language::Panjabi,
368
20
        Script::Kannada => Language::Kannada,
369
19
        Script::Malayalam => Language::Malayalam,
370
110
        Script::Mandarin => Language::Chinese,
371
19
        Script::Oriya => Language::Oriya,
372
19
        Script::Tamil => Language::Tamil,
373
19
        Script::Telugu => Language::Telugu,
374
20
        Script::Thai => Language::Thai,
375
23
        Script::Bengali => detect_bengali_language(text),
376
25
        Script::Cyrillic => detect_cyrillic_language(text),
377
23
        Script::Devanagari => detect_devanagari_language(text),
378
33
        Script::Greek => detect_greek_language(text),
379
59476
        Script::Latin => detect_latin_language(text),
380

            
381
        // not directly matchable
382
19
        Script::Myanmar => Language::Thai,
383
19
        Script::Khmer => Language::Thai,
384
19
        Script::Sinhala => Language::Hindi,
385

            
386
        // no classical hyphenation behaviour
387
119
        Script::Arabic => Language::Chinese,
388
279
        Script::Hebrew => Language::Chinese,
389
19
        Script::Hangul => Language::Chinese,
390
19
        Script::Hiragana => Language::Chinese,
391
19
        Script::Katakana => Language::Chinese,
392
    }
393
60394
}
394

            
395
#[must_use]
396
1026896
pub const fn is_cyrillic(ch: char) -> bool {
397
1026896
    matches!(ch,
398
823994
        '\u{0400}'..='\u{0484}'
399
623001
        | '\u{0487}'..='\u{052F}'
400
553705
        | '\u{2DE0}'..='\u{2DFF}'
401
365798
        | '\u{A640}'..='\u{A69D}'
402
        | '\u{1D2B}'
403
        | '\u{1D78}'
404
        | '\u{A69F}'
405
    )
406
1026896
}
407

            
408
// https://en.wikipedia.org/wiki/Latin_script_in_Unicode
409
#[must_use]
410
2219585
pub const fn is_latin(ch: char) -> bool {
411
2219585
    matches!(ch,
412
2119479
        'a'..='z'
413
935894
        | 'A'..='Z'
414
836208
        | '\u{0080}'..='\u{00FF}'
415
835041
        | '\u{0100}'..='\u{017F}'
416
834144
        | '\u{0180}'..='\u{024F}'
417
832681
        | '\u{0250}'..='\u{02AF}'
418
587291
        | '\u{1D00}'..='\u{1D7F}'
419
586385
        | '\u{1D80}'..='\u{1DBF}'
420
585482
        | '\u{1E00}'..='\u{1EFF}'
421
578987
        | '\u{2100}'..='\u{214F}'
422
558278
        | '\u{2C60}'..='\u{2C7F}'
423
366284
        | '\u{A720}'..='\u{A7FF}'
424
359081
        | '\u{AB30}'..='\u{AB6F}'
425
    )
426
2219585
}
427

            
428
// Based on https://en.wikipedia.org/wiki/Arabic_script_in_Unicode
429
#[must_use]
430
625362
pub const fn is_arabic(ch: char) -> bool {
431
625362
    matches!(ch,
432
620471
        '\u{0600}'..='\u{06FF}'
433
617763
        | '\u{0750}'..='\u{07FF}'
434
615394
        | '\u{08A0}'..='\u{08FF}'
435
242196
        | '\u{FB50}'..='\u{FDFF}'
436
236569
        | '\u{FE70}'..='\u{FEFF}'
437
231007
        | '\u{10E60}'..='\u{10E7F}'
438
227705
        | '\u{1EE00}'..='\u{1EEFF}'
439
    )
440
625362
}
441

            
442
// Based on https://en.wikipedia.org/wiki/Devanagari#Unicode
443
#[must_use]
444
443932
pub const fn is_devanagari(ch: char) -> bool {
445
443932
    matches!(ch, '\u{0900}'..='\u{097F}' | '\u{A8E0}'..='\u{A8FF}' | '\u{1CD0}'..='\u{1CFF}')
446
443932
}
447

            
448
// Based on https://www.key-shortcut.com/en/writing-systems/ethiopian-script/
449
#[must_use]
450
442062
pub const fn is_ethiopic(ch: char) -> bool {
451
442062
    matches!(ch, '\u{1200}'..='\u{139F}' | '\u{2D80}'..='\u{2DDF}' | '\u{AB00}'..='\u{AB2F}')
452
442062
}
453

            
454
// Based on https://en.wikipedia.org/wiki/Hebrew_(Unicode_block)
455
#[must_use]
456
442917
pub const fn is_hebrew(ch: char) -> bool {
457
442917
    matches!(ch, '\u{0590}'..='\u{05FF}')
458
442917
}
459

            
460
#[must_use]
461
438203
pub const fn is_georgian(ch: char) -> bool {
462
438203
    matches!(ch, '\u{10A0}'..='\u{10FF}')
463
438203
}
464

            
465
#[must_use]
466
643699
pub const fn is_mandarin(ch: char) -> bool {
467
643699
    matches!(ch,
468
575124
        '\u{2E80}'..='\u{2E99}'
469
574931
        | '\u{2E9B}'..='\u{2EF3}'
470
574220
        | '\u{2F00}'..='\u{2FD5}'
471
        | '\u{3005}'
472
        | '\u{3007}'
473
572181
        | '\u{3021}'..='\u{3029}'
474
572017
        | '\u{3038}'..='\u{303B}'
475
565498
        | '\u{3400}'..='\u{4DB5}'
476
518710
        | '\u{4E00}'..='\u{9FCC}'
477
239364
        | '\u{F900}'..='\u{FA6D}'
478
236772
        | '\u{FA70}'..='\u{FAD9}'
479
    )
480
643699
}
481

            
482
#[must_use]
483
437643
pub const fn is_bengali(ch: char) -> bool {
484
437643
    matches!(ch, '\u{0980}'..='\u{09FF}')
485
437643
}
486

            
487
#[must_use]
488
366575
pub const fn is_hiragana(ch: char) -> bool {
489
366575
    matches!(ch, '\u{3040}'..='\u{309F}')
490
366575
}
491

            
492
#[must_use]
493
366177
pub const fn is_katakana(ch: char) -> bool {
494
366177
    matches!(ch,
495
305198
        '\u{30A0}'..='\u{30FF}'
496
        // Halfwidth Katakana (part of the Halfwidth and Fullwidth Forms block).
497
        // U+FF66..=FF9F are katakana; U+FF61..=FF65 are halfwidth CJK punctuation.
498
233477
        | '\u{FF66}'..='\u{FF9F}'
499
    )
500
366177
}
501

            
502
// Hangul is Korean Alphabet. Unicode ranges are taken from: https://en.wikipedia.org/wiki/Hangul
503
#[must_use]
504
449105
pub const fn is_hangul(ch: char) -> bool {
505
449105
    matches!(ch,
506
360271
        '\u{AC00}'..='\u{D7AF}'
507
354563
        | '\u{1100}'..='\u{11FF}'
508
306171
        | '\u{3130}'..='\u{318F}'
509
285634
        | '\u{A960}'..='\u{A97F}'
510
281688
        | '\u{D7B0}'..='\u{D7FF}'
511
        // Halfwidth Hangul variants only. The rest of the Halfwidth and Fullwidth
512
        // Forms block (U+FF00..=FF60 fullwidth ASCII/Latin, U+FF61..=FF9F halfwidth
513
        // katakana/punct, U+FFE0..=FFEF fullwidth/halfwidth symbols) and Enclosed CJK
514
        // Letters and Months (U+3200..=32FF) are NOT Hangul and were previously
515
        // swallowed here, misclassifying halfwidth kana and fullwidth Latin as Hangul.
516
233379
        | '\u{FFA0}'..='\u{FFDC}'
517
    )
518
449105
}
519

            
520
// Taken from: https://en.wikipedia.org/wiki/Greek_and_Coptic
521
#[must_use]
522
365108
pub const fn is_greek(ch: char) -> bool {
523
365108
    matches!(ch, '\u{0370}'..='\u{03FF}')
524
365108
}
525

            
526
// Based on: https://en.wikipedia.org/wiki/Kannada_(Unicode_block)
527
#[must_use]
528
364206
pub const fn is_kannada(ch: char) -> bool {
529
364206
    matches!(ch, '\u{0C80}'..='\u{0CFF}')
530
364206
}
531

            
532
// Based on: https://en.wikipedia.org/wiki/Tamil_(Unicode_block)
533
#[must_use]
534
363430
pub const fn is_tamil(ch: char) -> bool {
535
363430
    matches!(ch, '\u{0B80}'..='\u{0BFF}')
536
363430
}
537

            
538
// Based on: https://en.wikipedia.org/wiki/Thai_(Unicode_block)
539
#[must_use]
540
362663
pub const fn is_thai(ch: char) -> bool {
541
362663
    matches!(ch, '\u{0E00}'..='\u{0E7F}')
542
362663
}
543

            
544
// Based on: https://en.wikipedia.org/wiki/Gujarati_(Unicode_block)
545
#[must_use]
546
361883
pub const fn is_gujarati(ch: char) -> bool {
547
361883
    matches!(ch, '\u{0A80}'..='\u{0AFF}')
548
361883
}
549

            
550
// Gurmukhi is the script for Punjabi language.
551
// Based on: https://en.wikipedia.org/wiki/Gurmukhi_(Unicode_block)
552
#[must_use]
553
361113
pub const fn is_gurmukhi(ch: char) -> bool {
554
361113
    matches!(ch, '\u{0A00}'..='\u{0A7F}')
555
361113
}
556

            
557
#[must_use]
558
360337
pub const fn is_telugu(ch: char) -> bool {
559
360337
    matches!(ch, '\u{0C00}'..='\u{0C7F}')
560
360337
}
561

            
562
// Based on: https://en.wikipedia.org/wiki/Malayalam_(Unicode_block)
563
#[must_use]
564
359565
pub const fn is_malayalam(ch: char) -> bool {
565
359565
    matches!(ch, '\u{0D00}'..='\u{0D7F}')
566
359565
}
567

            
568
// Based on: https://en.wikipedia.org/wiki/Oriya_(Unicode_block)
569
#[must_use]
570
358796
pub const fn is_oriya(ch: char) -> bool {
571
358796
    matches!(ch, '\u{0B00}'..='\u{0B7F}')
572
358796
}
573

            
574
// Based on: https://en.wikipedia.org/wiki/Myanmar_(Unicode_block)
575
#[must_use]
576
358048
pub const fn is_myanmar(ch: char) -> bool {
577
358048
    matches!(ch, '\u{1000}'..='\u{109F}')
578
358048
}
579

            
580
// Based on: https://en.wikipedia.org/wiki/Sinhala_(Unicode_block)
581
#[must_use]
582
357042
pub const fn is_sinhala(ch: char) -> bool {
583
357042
    matches!(ch, '\u{0D80}'..='\u{0DFF}')
584
357042
}
585

            
586
// Based on: https://en.wikipedia.org/wiki/Khmer_alphabet
587
#[must_use]
588
356309
pub const fn is_khmer(ch: char) -> bool {
589
356309
    matches!(ch, '\u{1780}'..='\u{17FF}' | '\u{19E0}'..='\u{19FF}')
590
356309
}
591

            
592
#[cfg(test)]
593
mod script_class_tests {
594
    use super::{detect_script, is_hangul, is_katakana, Script};
595

            
596
    #[test]
597
1
    fn halfwidth_katakana_is_not_hangul() {
598
        // U+FF71..FF73 = halfwidth katakana アイウ — must classify as Katakana, not Hangul.
599
4
        for ch in ['\u{FF71}', '\u{FF72}', '\u{FF73}'] {
600
3
            assert!(!is_hangul(ch), "{ch:?} wrongly matched is_hangul");
601
3
            assert!(is_katakana(ch), "{ch:?} should match is_katakana");
602
        }
603
1
        assert_eq!(
604
1
            detect_script("\u{FF71}\u{FF72}\u{FF73}"),
605
            Some(Script::Katakana)
606
        );
607
1
    }
608

            
609
    #[test]
610
1
    fn fullwidth_latin_is_not_hangul() {
611
        // U+FF21..FF23 = fullwidth ABC — must not be classified as Hangul.
612
4
        for ch in ['\u{FF21}', '\u{FF22}', '\u{FF23}'] {
613
3
            assert!(!is_hangul(ch), "{ch:?} wrongly matched is_hangul");
614
        }
615
1
        assert_ne!(
616
1
            detect_script("\u{FF21}\u{FF22}\u{FF23}"),
617
            Some(Script::Hangul)
618
        );
619
1
    }
620

            
621
    #[test]
622
1
    fn real_hangul_still_detected() {
623
1
        assert!(is_hangul('\u{AC00}')); // 가
624
1
        assert_eq!(detect_script("\u{AC00}\u{AC01}"), Some(Script::Hangul));
625
1
    }
626
}
627

            
628
#[cfg(test)]
629
#[allow(clippy::unicode_not_nfc, clippy::non_ascii_literal)]
630
mod autotest_generated {
631
    use super::*;
632

            
633
    // ---------------------------------------------------------------------
634
    // Helpers
635
    // ---------------------------------------------------------------------
636

            
637
    /// Every `Script` variant, in declaration order.
638
    const ALL_SCRIPTS: [Script; 24] = [
639
        Script::Arabic,
640
        Script::Bengali,
641
        Script::Cyrillic,
642
        Script::Devanagari,
643
        Script::Ethiopic,
644
        Script::Georgian,
645
        Script::Greek,
646
        Script::Gujarati,
647
        Script::Gurmukhi,
648
        Script::Hangul,
649
        Script::Hebrew,
650
        Script::Hiragana,
651
        Script::Kannada,
652
        Script::Katakana,
653
        Script::Khmer,
654
        Script::Latin,
655
        Script::Malayalam,
656
        Script::Mandarin,
657
        Script::Myanmar,
658
        Script::Oriya,
659
        Script::Sinhala,
660
        Script::Tamil,
661
        Script::Telugu,
662
        Script::Thai,
663
    ];
664

            
665
    /// `Script` has no `Hash`/`Ord`, so index it by hand for set-like bookkeeping.
666
    fn script_index(s: Script) -> usize {
667
        ALL_SCRIPTS
668
            .iter()
669
            .position(|&x| x == s)
670
            .expect("ALL_SCRIPTS must list every Script variant")
671
    }
672

            
673
    /// The first checker in `SCRIPT_CHECKERS` that claims `ch` — i.e. exactly what
674
    /// both `detect_char_script` and (for a 1-char text) `detect_script` must return.
675
    fn first_checker_hit(ch: char) -> Option<Script> {
676
        SCRIPT_CHECKERS
677
            .iter()
678
            .find(|(_, check_fn)| check_fn(ch))
679
            .map(|&(script, _)| script)
680
    }
681

            
682
    /// Iterate every scalar value in the BMP (surrogates are not `char`s).
683
    fn bmp_chars() -> impl Iterator<Item = char> {
684
        (0u32..=0xFFFF).filter_map(char::from_u32)
685
    }
686

            
687
    /// Deterministic pseudo-random scalar values — no `rand` dependency, and the
688
    /// sequence is identical on every run so a failure is always reproducible.
689
    fn lcg_chars(count: usize, seed: u64) -> String {
690
        let mut state = seed;
691
        let mut out = String::with_capacity(count * 4);
692
        let mut pushed = 0usize;
693
        while pushed < count {
694
            state = state
695
                .wrapping_mul(6_364_136_223_846_793_005)
696
                .wrapping_add(1_442_695_040_888_963_407);
697
            let cp = (state >> 16) as u32 % 0x0011_0000;
698
            if let Some(ch) = char::from_u32(cp) {
699
                out.push(ch);
700
                pushed += 1;
701
            }
702
        }
703
        out
704
    }
705

            
706
    // ---------------------------------------------------------------------
707
    // is_stop_char (predicate)
708
    // ---------------------------------------------------------------------
709

            
710
    // Const-evaluability is part of the API: these must fold at compile time.
711
    const _: bool = is_stop_char(' ');
712
    const _: bool = is_latin('a');
713
    const _: bool = is_khmer('\u{1780}');
714

            
715
    #[test]
716
    fn is_stop_char_basic_true_false() {
717
        for ch in [
718
            '\u{0000}', '\t', '\n', '\r', ' ', '!', '0', '9', '@', '[', '\\', ']', '^', '_', '`',
719
            '{', '|', '}', '~',
720
        ] {
721
            assert!(is_stop_char(ch), "{ch:?} should be a stop char");
722
        }
723
        for ch in ['a', 'z', 'A', 'Z', '\u{007F}', 'é', 'あ', 'م', '\u{10FFFF}'] {
724
            assert!(!is_stop_char(ch), "{ch:?} should not be a stop char");
725
        }
726
    }
727

            
728
    #[test]
729
    fn is_stop_char_range_boundaries_are_exact() {
730
        // '\u{0000}'..='\u{0040}'
731
        assert!(is_stop_char('\u{0040}'));
732
        assert!(!is_stop_char('\u{0041}')); // 'A' — first char past the first range
733
                                            // '\u{005B}'..='\u{0060}'
734
        assert!(!is_stop_char('\u{005A}')); // 'Z'
735
        assert!(is_stop_char('\u{005B}'));
736
        assert!(is_stop_char('\u{0060}'));
737
        assert!(!is_stop_char('\u{0061}')); // 'a'
738
                                            // '\u{007B}'..='\u{007E}'
739
        assert!(!is_stop_char('\u{007A}')); // 'z'
740
        assert!(is_stop_char('\u{007B}'));
741
        assert!(is_stop_char('\u{007E}'));
742
        // U+007F (DEL) is deliberately *outside* every stop range and every script
743
        // range: it is counted toward `half` in detect_script but never scores.
744
        assert!(!is_stop_char('\u{007F}'));
745
        assert_eq!(detect_char_script('\u{007F}'), None);
746
        assert!(!is_stop_char('\u{0080}'));
747
    }
748

            
749
    #[test]
750
    fn stop_chars_never_carry_a_script() {
751
        // Invariant the whole detector rests on: a stop char scores for nothing,
752
        // so a stop-only text can never produce a Some(script).
753
        for ch in bmp_chars() {
754
            if is_stop_char(ch) {
755
                assert_eq!(
756
                    detect_char_script(ch),
757
                    None,
758
                    "stop char {ch:?} (U+{:04X}) also matched a script checker",
759
                    ch as u32
760
                );
761
            }
762
        }
763
    }
764

            
765
    // ---------------------------------------------------------------------
766
    // detect_script (parser)
767
    // ---------------------------------------------------------------------
768

            
769
    #[test]
770
    fn detect_script_empty_input_returns_none() {
771
        assert_eq!(detect_script(""), None);
772
    }
773

            
774
    #[test]
775
    fn detect_script_whitespace_only_returns_none() {
776
        for text in ["   ", "\t\n", "\r\n\r\n", "\t \t \n", "\u{0000}\u{0000}"] {
777
            assert_eq!(detect_script(text), None, "whitespace {text:?}");
778
        }
779
    }
780

            
781
    #[test]
782
    fn detect_script_non_ascii_whitespace_scores_nothing() {
783
        // U+2003 EM SPACE / U+2028 LINE SEPARATOR are *not* stop chars (they are
784
        // above U+007E) but no checker claims them either — so still None.
785
        assert_eq!(detect_script("\u{2003}\u{2003}"), None);
786
        assert_eq!(detect_script("\u{2028}"), None);
787
    }
788

            
789
    #[test]
790
    fn detect_script_garbage_returns_none_without_panicking() {
791
        for text in [
792
            "\u{0001}\u{0002}\u{0003}",
793
            "\u{007F}\u{007F}\u{007F}",
794
            "!@#$%^&*()_+-=[]{}|;':\",./<>?",
795
            "\u{FFFD}\u{FFFD}",
796
            "\u{200B}\u{200C}\u{200D}", // zero-width space / non-joiner / joiner
797
        ] {
798
            assert_eq!(detect_script(text), None, "garbage {text:?}");
799
        }
800
    }
801

            
802
    #[test]
803
    fn detect_script_boundary_number_strings() {
804
        // Digits, signs and dots are all stop chars → nothing to score.
805
        for text in [
806
            "0",
807
            "-0",
808
            "9223372036854775807",  // i64::MAX
809
            "-9223372036854775808", // i64::MIN
810
            "18446744073709551615", // u64::MAX
811
            "1e309",                // f64 overflow literal — 'e' is Latin though
812
            "0.0000000000000000001",
813
        ] {
814
            let got = detect_script(text);
815
            let expected = if text.chars().any(|c| c.is_ascii_alphabetic()) {
816
                Some(Script::Latin)
817
            } else {
818
                None
819
            };
820
            assert_eq!(got, expected, "numeric text {text:?}");
821
        }
822
        // "NaN" / "inf" are pure ASCII letters → Latin, not a crash.
823
        assert_eq!(detect_script("NaN"), Some(Script::Latin));
824
        assert_eq!(detect_script("inf"), Some(Script::Latin));
825
        assert_eq!(detect_script("-inf"), Some(Script::Latin));
826
    }
827

            
828
    #[test]
829
    fn detect_script_leading_trailing_junk_is_skipped() {
830
        assert_eq!(detect_script("  hello  "), Some(Script::Latin));
831
        assert_eq!(detect_script("valid;garbage"), Some(Script::Latin));
832
        assert_eq!(detect_script("\t\nПривет\t\n"), Some(Script::Cyrillic));
833
    }
834

            
835
    #[test]
836
    fn detect_script_minority_script_still_wins_over_stop_chars() {
837
        // "a!!!!!!!!" is 9 chars → half == 4, so the single Latin char never crosses
838
        // the early-exit threshold. It must still win via the max-count fallback
839
        // (count != 0), not fall through to None.
840
        assert_eq!(detect_script("a!!!!!!!!"), Some(Script::Latin));
841
        assert_eq!(detect_script("!!!!!!!!!"), None);
842
    }
843

            
844
    #[test]
845
    fn detect_script_unicode_input_does_not_panic() {
846
        for text in [
847
            "\u{1F600}",                           // emoji, matches no script
848
            "\u{1F600}\u{1F468}\u{200D}\u{1F469}", // ZWJ sequence
849
            "e\u{0301}",                           // 'e' + combining acute
850
            "\u{0301}\u{0302}\u{0303}",            // bare combining marks
851
            "\u{10FFFF}",                          // char::MAX
852
            "\u{FFFF}",                            // BMP noncharacter
853
        ] {
854
            let got = detect_script(text);
855
            assert_eq!(got, detect_script(text), "not deterministic for {text:?}");
856
        }
857
        assert_eq!(detect_script("\u{1F600}"), None);
858
        assert_eq!(detect_script("\u{0301}\u{0302}"), None);
859
        assert_eq!(detect_script("\u{10FFFF}"), None);
860
        assert_eq!(detect_script("e\u{0301}"), Some(Script::Latin));
861
    }
862

            
863
    #[test]
864
    fn detect_script_deeply_nested_brackets_do_not_stack_overflow() {
865
        // 10_000 nested brackets: the detector is iterative, and every bracket is a
866
        // stop char, so this must terminate with None rather than recursing.
867
        let depth = 10_000;
868
        let mut text = String::with_capacity(depth * 2);
869
        for _ in 0..depth {
870
            text.push('(');
871
        }
872
        for _ in 0..depth {
873
            text.push(')');
874
        }
875
        assert_eq!(detect_script(&text), None);
876

            
877
        let mut nested = String::new();
878
        for _ in 0..depth {
879
            nested.push_str("{[");
880
        }
881
        for _ in 0..depth {
882
            nested.push_str("]}");
883
        }
884
        assert_eq!(detect_script(&nested), None);
885
    }
886

            
887
    #[test]
888
    fn detect_script_extremely_long_input_terminates() {
889
        // 1M identical Latin chars: must early-exit once count > half.
890
        let long_latin = "a".repeat(1_000_000);
891
        assert_eq!(detect_script(&long_latin), Some(Script::Latin));
892

            
893
        // 200k chars that match *no* checker: worst case — all 24 checkers run for
894
        // every char and there is no early exit. Must still finish, returning None.
895
        let long_junk = "\u{1F600}".repeat(200_000);
896
        assert_eq!(detect_script(&long_junk), None);
897

            
898
        // 200k stop chars: skipped, but still walked.
899
        let long_stops = " ".repeat(200_000);
900
        assert_eq!(detect_script(&long_stops), None);
901
    }
902

            
903
    #[test]
904
    fn detect_script_long_mixed_script_input_is_deterministic() {
905
        // Alternating scripts defeat the "move winner to the front" heuristic and
906
        // never cross the half threshold. It must still terminate and be stable.
907
        let mixed = "aб".repeat(100_000);
908
        let first = detect_script(&mixed);
909
        let second = detect_script(&mixed);
910
        assert_eq!(first, second, "detect_script is not deterministic");
911
        assert!(
912
            first == Some(Script::Latin) || first == Some(Script::Cyrillic),
913
            "expected one of the two present scripts, got {first:?}"
914
        );
915
    }
916

            
917
    #[test]
918
    fn detect_script_pseudo_random_garbage_never_panics() {
919
        for seed in [1u64, 0xDEAD_BEEF, u64::MAX] {
920
            let text = lcg_chars(5_000, seed);
921
            let first = detect_script(&text);
922
            let second = detect_script(&text);
923
            assert_eq!(first, second, "non-deterministic for seed {seed}");
924
        }
925
    }
926

            
927
    #[test]
928
    fn detect_script_majority_wins() {
929
        assert_eq!(detect_script("aaaaaб"), Some(Script::Latin));
930
        assert_eq!(detect_script("бббббa"), Some(Script::Cyrillic));
931
        // Latin body with a couple of CJK chars mixed in.
932
        assert_eq!(detect_script("hello 世界"), Some(Script::Latin));
933
        assert_eq!(detect_script("世界世界 hi"), Some(Script::Mandarin));
934
    }
935

            
936
    #[test]
937
    fn detect_script_valid_minimal_positive_controls() {
938
        let cases: [(&str, Script); 16] = [
939
            ("hello", Script::Latin),
940
            ("Привет", Script::Cyrillic),
941
            ("مرحبا", Script::Arabic),
942
            ("你好世界", Script::Mandarin),
943
            ("नमस्ते", Script::Devanagari),
944
            ("שלום", Script::Hebrew),
945
            ("ሰላም", Script::Ethiopic),
946
            ("გამარჯობა", Script::Georgian),
947
            ("আমার", Script::Bengali),
948
            ("안녕하세요", Script::Hangul),
949
            ("こんにちは", Script::Hiragana),
950
            ("カタカナ", Script::Katakana),
951
            ("Γειά", Script::Greek),
952
            ("ಕನ್ನಡ", Script::Kannada),
953
            ("தமிழ்", Script::Tamil),
954
            ("สวัสดี", Script::Thai),
955
        ];
956
        for (text, expected) in cases {
957
            assert_eq!(detect_script(text), Some(expected), "text {text:?}");
958
        }
959
    }
960

            
961
    #[test]
962
    fn detect_script_is_pure_no_state_leaks_between_calls() {
963
        // detect_script mutates (swaps) its counter table; that table must be local.
964
        // Priming it with Cyrillic must not change the verdict for a later Latin text.
965
        assert_eq!(detect_script("ббббб"), Some(Script::Cyrillic));
966
        assert_eq!(detect_script("aaaaa"), Some(Script::Latin));
967
        assert_eq!(detect_script("ббббб"), Some(Script::Cyrillic));
968
        assert_eq!(detect_script("aaaaa"), Some(Script::Latin));
969
    }
970

            
971
    #[test]
972
    fn detect_script_single_char_agrees_with_detect_char_script() {
973
        // Strong cross-check over the whole BMP: a 1-char text has half == 0, so the
974
        // first checker that claims the char wins immediately — exactly what
975
        // detect_char_script returns. Any divergence is a table-ordering bug.
976
        for ch in bmp_chars() {
977
            let expected = first_checker_hit(ch);
978
            assert_eq!(
979
                detect_char_script(ch),
980
                expected,
981
                "detect_char_script disagrees with SCRIPT_CHECKERS for U+{:04X}",
982
                ch as u32
983
            );
984
            let text = ch.to_string();
985
            assert_eq!(
986
                detect_script(&text),
987
                expected,
988
                "detect_script disagrees with detect_char_script for U+{:04X}",
989
                ch as u32
990
            );
991
        }
992
    }
993

            
994
    // ---------------------------------------------------------------------
995
    // detect_char_script (dispatch table)
996
    // ---------------------------------------------------------------------
997

            
998
    #[test]
999
    fn detect_char_script_extreme_inputs() {
        assert_eq!(detect_char_script('\u{0000}'), None);
        assert_eq!(detect_char_script('\u{10FFFF}'), None); // char::MAX
        assert_eq!(detect_char_script(char::MAX), None);
        assert_eq!(detect_char_script('\u{FFFF}'), None); // noncharacter
        assert_eq!(detect_char_script('\u{E000}'), None); // private use area
        assert_eq!(detect_char_script('a'), Some(Script::Latin));
        assert_eq!(detect_char_script('\u{1EE00}'), Some(Script::Arabic)); // astral Arabic
        assert_eq!(detect_char_script('\u{10E60}'), Some(Script::Arabic)); // Rumi digits
    }
    #[test]
    fn detect_char_script_astral_planes_agree_with_the_table() {
        // The two astral Arabic ranges plus the surrounding gaps, which the BMP
        // sweep above cannot reach.
        for cp in (0x1_0E00u32..=0x1_0F00)
            .chain(0x1_ED00..=0x1_EF00)
            .chain([0x1_F600, 0x2_0000, 0x10_FFFF])
        {
            let Some(ch) = char::from_u32(cp) else {
                continue;
            };
            assert_eq!(
                detect_char_script(ch),
                first_checker_hit(ch),
                "astral U+{cp:05X} disagrees with SCRIPT_CHECKERS"
            );
            assert_eq!(
                detect_script(&ch.to_string()),
                first_checker_hit(ch),
                "astral U+{cp:05X}: detect_script != detect_char_script"
            );
        }
    }
    #[test]
    fn detect_char_script_none_implies_no_checker_matched() {
        for ch in bmp_chars() {
            if detect_char_script(ch).is_none() {
                for (script, check_fn) in SCRIPT_CHECKERS {
                    assert!(
                        !check_fn(ch),
                        "U+{:04X} is unclassified yet {script:?}'s checker claims it",
                        ch as u32
                    );
                }
            }
        }
    }
    #[test]
    fn detect_char_script_some_implies_that_scripts_checker_matched() {
        for ch in bmp_chars() {
            if let Some(script) = detect_char_script(ch) {
                let (_, check_fn) = SCRIPT_CHECKERS[script_index_in_table(script)];
                assert!(
                    check_fn(ch),
                    "detect_char_script said {script:?} for U+{:04X} but its checker says no",
                    ch as u32
                );
            }
        }
    }
    fn script_index_in_table(script: Script) -> usize {
        SCRIPT_CHECKERS
            .iter()
            .position(|&(s, _)| s == script)
            .expect("every Script must appear in SCRIPT_CHECKERS")
    }
    #[test]
    fn script_checkers_table_covers_every_script_exactly_once() {
        assert_eq!(SCRIPT_CHECKERS.len(), ALL_SCRIPTS.len());
        let mut seen = [0usize; 24];
        for (script, _) in SCRIPT_CHECKERS {
            seen[script_index(script)] += 1;
        }
        for (i, count) in seen.iter().enumerate() {
            assert_eq!(
                *count, 1,
                "{:?} appears {count} times in SCRIPT_CHECKERS",
                ALL_SCRIPTS[i]
            );
        }
    }
    #[test]
    fn every_script_is_reachable_from_some_bmp_char() {
        // Guards against a checker being fully shadowed by an earlier, broader one:
        // if some script can never be produced, the table order has swallowed it.
        let mut reachable = [false; 24];
        for ch in bmp_chars() {
            if let Some(script) = detect_char_script(ch) {
                reachable[script_index(script)] = true;
            }
        }
        for (i, ok) in reachable.iter().enumerate() {
            assert!(
                *ok,
                "{:?} is unreachable — shadowed by an earlier checker",
                ALL_SCRIPTS[i]
            );
        }
    }
    #[test]
    fn overlapping_ranges_resolve_to_the_first_checker_in_the_table() {
        // U+1D2B (CYRILLIC LETTER SMALL CAPITAL EL) and U+1D78 (MODIFIER LETTER
        // CYRILLIC EN) are listed by *both* is_latin (via U+1D00..=U+1D7F) and
        // is_cyrillic. Latin is checked first, so Latin wins. Pinned here because a
        // reordering of SCRIPT_CHECKERS would silently flip these to Cyrillic.
        for ch in ['\u{1D2B}', '\u{1D78}'] {
            assert!(is_latin(ch), "{ch:?} in is_latin's U+1D00..=U+1D7F range");
            assert!(
                is_cyrillic(ch),
                "{ch:?} is explicitly listed by is_cyrillic"
            );
            assert_eq!(detect_char_script(ch), Some(Script::Latin));
            assert_eq!(detect_script(&ch.to_string()), Some(Script::Latin));
        }
    }
    // ---------------------------------------------------------------------
    // is_* predicates: exact range boundaries
    // ---------------------------------------------------------------------
    /// Assert a predicate accepts both ends and the midpoint of `[lo, hi]`. The chars
    /// bracketing the range are checked separately with `assert_rejects`, because a
    /// neighbour may legitimately belong to another range of the *same* predicate.
    fn assert_range(name: &str, f: fn(char) -> bool, lo: u32, hi: u32) {
        for cp in [lo, hi] {
            let ch = char::from_u32(cp).unwrap_or_else(|| panic!("{name}: U+{cp:04X} not a char"));
            assert!(f(ch), "{name} should accept its boundary U+{cp:04X}");
        }
        let mid = char::from_u32(lo + (hi - lo) / 2).unwrap();
        assert!(f(mid), "{name} should accept its midpoint {mid:?}");
    }
    fn assert_rejects(name: &str, f: fn(char) -> bool, cps: &[u32]) {
        for &cp in cps {
            let Some(ch) = char::from_u32(cp) else {
                continue;
            };
            assert!(!f(ch), "{name} should reject U+{cp:04X}");
        }
    }
    #[test]
    fn single_range_predicates_have_exact_boundaries() {
        // (name, fn, start, end): each of these is a single contiguous block, so the
        // chars immediately before/after must be rejected.
        let cases: [(&str, fn(char) -> bool, u32, u32); 12] = [
            ("is_hebrew", is_hebrew, 0x0590, 0x05FF),
            ("is_georgian", is_georgian, 0x10A0, 0x10FF),
            ("is_bengali", is_bengali, 0x0980, 0x09FF),
            ("is_hiragana", is_hiragana, 0x3040, 0x309F),
            ("is_greek", is_greek, 0x0370, 0x03FF),
            ("is_kannada", is_kannada, 0x0C80, 0x0CFF),
            ("is_tamil", is_tamil, 0x0B80, 0x0BFF),
            ("is_thai", is_thai, 0x0E00, 0x0E7F),
            ("is_gujarati", is_gujarati, 0x0A80, 0x0AFF),
            ("is_gurmukhi", is_gurmukhi, 0x0A00, 0x0A7F),
            ("is_telugu", is_telugu, 0x0C00, 0x0C7F),
            ("is_malayalam", is_malayalam, 0x0D00, 0x0D7F),
        ];
        for (name, f, lo, hi) in cases {
            assert_range(name, f, lo, hi);
            assert_rejects(name, f, &[lo - 1, hi + 1, 0x0000, 0x0041, 0x10_FFFF]);
        }
        // The two remaining single-range predicates, spelled out (0x0B00-1 etc. all
        // land in neighbouring script blocks, which is exactly what we want to check).
        assert_range("is_oriya", is_oriya, 0x0B00, 0x0B7F);
        assert_rejects("is_oriya", is_oriya, &[0x0AFF, 0x0B80]);
        assert_range("is_myanmar", is_myanmar, 0x1000, 0x109F);
        assert_rejects("is_myanmar", is_myanmar, &[0x0FFF, 0x10A0]);
        assert_range("is_sinhala", is_sinhala, 0x0D80, 0x0DFF);
        assert_rejects("is_sinhala", is_sinhala, &[0x0D7F, 0x0E00]);
    }
    #[test]
    fn is_latin_boundaries() {
        assert!(is_latin('a') && is_latin('z') && is_latin('A') && is_latin('Z'));
        // The chars bracketing the ASCII letter ranges are all stop chars.
        assert_rejects(
            "is_latin",
            is_latin,
            &[0x0040, 0x005B, 0x0060, 0x007B, 0x007F],
        );
        assert_range("is_latin", is_latin, 0x0080, 0x024F); // Latin-1 Sup .. Latin Ext-B
        assert_range("is_latin", is_latin, 0x0250, 0x02AF); // IPA extensions
        assert_rejects("is_latin", is_latin, &[0x02B0, 0x0300, 0x0400, 0x1CFF]);
        assert_range("is_latin", is_latin, 0x1D00, 0x1DBF);
        assert_rejects("is_latin", is_latin, &[0x1DC0]);
        assert_range("is_latin", is_latin, 0x1E00, 0x1EFF);
        assert_rejects("is_latin", is_latin, &[0x1DFF, 0x1F00]);
        assert_range("is_latin", is_latin, 0x2100, 0x214F);
        assert_rejects("is_latin", is_latin, &[0x20FF, 0x2150]);
        assert_range("is_latin", is_latin, 0x2C60, 0x2C7F);
        assert_rejects("is_latin", is_latin, &[0x2C5F, 0x2C80]);
        assert_range("is_latin", is_latin, 0xA720, 0xA7FF);
        assert_rejects("is_latin", is_latin, &[0xA71F, 0xA800]);
        assert_range("is_latin", is_latin, 0xAB30, 0xAB6F);
        assert_rejects("is_latin", is_latin, &[0xAB2F, 0xAB70]);
    }
    #[test]
    fn is_latin_swallows_latin1_symbols_and_letterlike_forms() {
        // Pinned quirk, not an endorsement: is_latin's U+0080..=U+00FF and
        // U+2100..=U+214F ranges are whole *blocks*, so NBSP, ©, ×, ÷, ™ and ℃ all
        // report as Latin and score for Latin in detect_script.
        for ch in [
            '\u{00A0}', '\u{00A9}', '\u{00D7}', '\u{00F7}', '\u{2122}', '\u{2103}',
        ] {
            assert!(
                is_latin(ch),
                "U+{:04X} is inside is_latin's block ranges",
                ch as u32
            );
            assert_eq!(detect_script(&ch.to_string()), Some(Script::Latin));
        }
    }
    #[test]
    fn is_cyrillic_boundaries_including_the_titlo_gap() {
        assert_range("is_cyrillic", is_cyrillic, 0x0400, 0x0484);
        // U+0485/U+0486 (combining Cyrillic titlo) are deliberately excluded.
        assert_rejects(
            "is_cyrillic",
            is_cyrillic,
            &[0x03FF, 0x0485, 0x0486, 0x0530],
        );
        assert_range("is_cyrillic", is_cyrillic, 0x0487, 0x052F);
        assert_range("is_cyrillic", is_cyrillic, 0x2DE0, 0x2DFF);
        assert_rejects("is_cyrillic", is_cyrillic, &[0x2DDF, 0x2E00]);
        assert_range("is_cyrillic", is_cyrillic, 0xA640, 0xA69D);
        assert!(is_cyrillic('\u{A69F}'));
        assert_rejects("is_cyrillic", is_cyrillic, &[0xA63F, 0xA69E, 0xA6A0]);
        assert!(is_cyrillic('\u{1D2B}') && is_cyrillic('\u{1D78}'));
    }
    #[test]
    fn is_arabic_boundaries_and_the_bom() {
        assert_range("is_arabic", is_arabic, 0x0600, 0x06FF);
        assert_rejects(
            "is_arabic",
            is_arabic,
            &[0x05FF, 0x0700, 0x074F, 0x0800, 0x089F],
        );
        assert_range("is_arabic", is_arabic, 0x0750, 0x07FF);
        assert_range("is_arabic", is_arabic, 0x08A0, 0x08FF);
        assert_range("is_arabic", is_arabic, 0xFB50, 0xFDFF);
        assert_range("is_arabic", is_arabic, 0xFE70, 0xFEFF);
        assert_rejects("is_arabic", is_arabic, &[0xFB4F, 0xFE00, 0xFE6F, 0xFF00]);
        assert_range("is_arabic", is_arabic, 0x1_0E60, 0x1_0E7F);
        assert_range("is_arabic", is_arabic, 0x1_EE00, 0x1_EEFF);
        assert_rejects(
            "is_arabic",
            is_arabic,
            &[0x1_0E5F, 0x1_0E80, 0x1_EDFF, 0x1_EF00],
        );
        // BUG PIN: U+FEFF is the byte-order mark / ZERO WIDTH NO-BREAK SPACE, whose
        // Unicode script is Common — but it sits at the top of the Arabic
        // Presentation Forms-B block, so is_arabic claims it. A BOM-prefixed text is
        // therefore scored as containing one Arabic char. Behaviour pinned as-is;
        // see the report.
        assert!(is_arabic('\u{FEFF}'));
        assert_eq!(detect_script("\u{FEFF}"), Some(Script::Arabic));
        // The BOM is not enough to beat a real majority, at least.
        assert_eq!(detect_script("\u{FEFF}hello"), Some(Script::Latin));
    }
    #[test]
    fn is_devanagari_boundaries() {
        assert_range("is_devanagari", is_devanagari, 0x0900, 0x097F);
        assert_range("is_devanagari", is_devanagari, 0xA8E0, 0xA8FF);
        assert_range("is_devanagari", is_devanagari, 0x1CD0, 0x1CFF); // Vedic extensions
        assert_rejects(
            "is_devanagari",
            is_devanagari,
            &[0x08FF, 0x0980, 0xA8DF, 0xA900, 0x1CCF, 0x1D00],
        );
    }
    #[test]
    fn is_ethiopic_boundaries() {
        assert_range("is_ethiopic", is_ethiopic, 0x1200, 0x139F);
        assert_range("is_ethiopic", is_ethiopic, 0x2D80, 0x2DDF);
        assert_range("is_ethiopic", is_ethiopic, 0xAB00, 0xAB2F);
        assert_rejects(
            "is_ethiopic",
            is_ethiopic,
            &[0x11FF, 0x13A0, 0x2D7F, 0xAAFF],
        );
        // U+2DE0 is where Cyrillic Extended-A starts — must NOT be Ethiopic.
        assert!(!is_ethiopic('\u{2DE0}'));
        assert!(is_cyrillic('\u{2DE0}'));
        // U+AB30 is where is_latin's Latin Extended-E range starts.
        assert!(!is_ethiopic('\u{AB30}'));
        assert!(is_latin('\u{AB30}'));
    }
    #[test]
    fn is_mandarin_boundaries_and_gaps() {
        assert_range("is_mandarin", is_mandarin, 0x2E80, 0x2E99);
        assert!(!is_mandarin('\u{2E9A}')); // documented hole in the CJK Radicals block
        assert_range("is_mandarin", is_mandarin, 0x2E9B, 0x2EF3);
        assert_range("is_mandarin", is_mandarin, 0x2F00, 0x2FD5);
        assert!(is_mandarin('\u{3005}') && is_mandarin('\u{3007}'));
        assert!(!is_mandarin('\u{3006}')); // U+3006 IDEOGRAPHIC CLOSING MARK is excluded
        assert_range("is_mandarin", is_mandarin, 0x3021, 0x3029);
        assert_range("is_mandarin", is_mandarin, 0x3038, 0x303B);
        assert_range("is_mandarin", is_mandarin, 0x3400, 0x4DB5);
        assert_range("is_mandarin", is_mandarin, 0x4E00, 0x9FCC);
        assert_range("is_mandarin", is_mandarin, 0xF900, 0xFA6D);
        assert_range("is_mandarin", is_mandarin, 0xFA70, 0xFAD9);
        assert_rejects(
            "is_mandarin",
            is_mandarin,
            &[
                0x2E7F, 0x2EF4, 0x2FD6, 0x3004, 0x4DB6, 0x9FCD, 0xF8FF, 0xFA6E, 0xFADA,
            ],
        );
    }
    #[test]
    fn is_katakana_and_is_hangul_do_not_overlap_in_halfwidth_forms() {
        assert_range("is_katakana", is_katakana, 0x30A0, 0x30FF);
        assert_range("is_katakana", is_katakana, 0xFF66, 0xFF9F);
        assert_rejects(
            "is_katakana",
            is_katakana,
            &[0x309F, 0x3100, 0xFF65, 0xFFA0],
        );
        assert_range("is_hangul", is_hangul, 0xAC00, 0xD7AF);
        assert_range("is_hangul", is_hangul, 0x1100, 0x11FF);
        assert_range("is_hangul", is_hangul, 0x3130, 0x318F);
        assert_range("is_hangul", is_hangul, 0xA960, 0xA97F);
        assert_range("is_hangul", is_hangul, 0xD7B0, 0xD7FF);
        assert_range("is_hangul", is_hangul, 0xFFA0, 0xFFDC);
        assert_rejects(
            "is_hangul",
            is_hangul,
            &[
                0x10FF, 0x1200, 0x312F, 0x3190, 0x3200, 0xABFF, 0xFF66, 0xFF9F, 0xFFDD, 0xFFE0,
            ],
        );
        // The two halfwidth ranges must stay disjoint.
        for cp in 0xFF61u32..=0xFFDCu32 {
            let ch = char::from_u32(cp).unwrap();
            assert!(
                !(is_katakana(ch) && is_hangul(ch)),
                "U+{cp:04X} claimed by both is_katakana and is_hangul"
            );
        }
    }
    #[test]
    fn is_khmer_boundaries() {
        assert_range("is_khmer", is_khmer, 0x1780, 0x17FF);
        assert_range("is_khmer", is_khmer, 0x19E0, 0x19FF);
        assert_rejects("is_khmer", is_khmer, &[0x177F, 0x1800, 0x19DF, 0x1A00]);
    }
    #[test]
    fn predicates_reject_the_extremes_and_are_pure() {
        for (script, check_fn) in SCRIPT_CHECKERS {
            for ch in ['\u{0000}', ' ', '0', '\u{007F}', '\u{10FFFF}'] {
                let first = check_fn(ch);
                assert_eq!(
                    first,
                    check_fn(ch),
                    "{script:?} checker is not pure for {ch:?}"
                );
                assert!(!first, "{script:?} checker claims the non-letter {ch:?}");
            }
        }
    }
    // ---------------------------------------------------------------------
    // detect_bengali_language
    // ---------------------------------------------------------------------
    #[test]
    fn detect_bengali_language_defaults_to_bengali() {
        assert_eq!(detect_bengali_language(""), Language::Bengali);
        assert_eq!(detect_bengali_language("   "), Language::Bengali);
        assert_eq!(detect_bengali_language("আমার সোনার বাংলা"), Language::Bengali);
        // Out-of-script text is not validated — it still falls through to Bengali.
        assert_eq!(detect_bengali_language("hello"), Language::Bengali);
        assert_eq!(detect_bengali_language("\u{1F600}"), Language::Bengali);
    }
    #[test]
    fn detect_bengali_language_finds_assamese_at_any_position() {
        for text in [
            "\u{09F0}",
            "\u{09F1}",
            "\u{09F0}আমার",
            "আমার\u{09F0}",
            "আ\u{09F1}র",
        ] {
            assert_eq!(
                detect_bengali_language(text),
                Language::Assamese,
                "text {text:?}"
            );
        }
        // Boundary: the code points either side of the ৰ/ৱ pair are plain Bengali.
        assert_eq!(detect_bengali_language("\u{09EF}"), Language::Bengali);
        assert_eq!(detect_bengali_language("\u{09F2}"), Language::Bengali);
    }
    #[test]
    fn detect_bengali_language_long_input_terminates() {
        let long = "আ".repeat(200_000);
        assert_eq!(detect_bengali_language(&long), Language::Bengali);
        // Assamese marker at the very end — worst case for the early-return scan.
        let mut with_marker = long.clone();
        with_marker.push('\u{09F0}');
        assert_eq!(detect_bengali_language(&with_marker), Language::Assamese);
    }
    // ---------------------------------------------------------------------
    // detect_cyrillic_language
    // ---------------------------------------------------------------------
    #[test]
    fn detect_cyrillic_language_defaults_to_russian() {
        assert_eq!(detect_cyrillic_language(""), Language::Russian);
        assert_eq!(detect_cyrillic_language("Привет мир"), Language::Russian);
        assert_eq!(detect_cyrillic_language("hello"), Language::Russian);
        assert_eq!(detect_cyrillic_language("\u{1F600}"), Language::Russian);
    }
    #[test]
    fn detect_cyrillic_language_markers() {
        let cases: [(&str, Language); 7] = [
            ("\u{0460}", Language::SlavonicChurch),
            ("ѓ", Language::Macedonian),
            ("ў", Language::Belarusian),
            ("ї", Language::Ukrainian),
            ("ө", Language::Mongolian),
            ("ј", Language::SerbianCyrillic),
            ("щ", Language::Bulgarian),
        ];
        for (text, expected) in cases {
            assert_eq!(detect_cyrillic_language(text), expected, "text {text:?}");
        }
        // Old-Cyrillic block boundaries: U+0460..=U+047F inclusive, nothing outside.
        assert_eq!(
            detect_cyrillic_language("\u{047F}"),
            Language::SlavonicChurch
        );
        assert_eq!(detect_cyrillic_language("\u{0480}"), Language::Russian);
        // U+045F sits one below the Old-Cyrillic range — and it is 'џ', so it falls
        // through to the Serbian arm rather than to the Russian default.
        assert_eq!(
            detect_cyrillic_language("\u{045F}"),
            Language::SerbianCyrillic
        );
    }
    #[test]
    fn detect_cyrillic_language_is_positional_not_priority_ordered() {
        // The comments in the function claim Old-Cyrillic is the "highest priority"
        // check, but every arm returns immediately, so the *first marker char in the
        // text* wins regardless of its claimed rank. Pinned; see the report.
        assert_eq!(detect_cyrillic_language("щ\u{0460}"), Language::Bulgarian);
        assert_eq!(
            detect_cyrillic_language("\u{0460}щ"),
            Language::SlavonicChurch
        );
        assert_eq!(detect_cyrillic_language("ўщ"), Language::Belarusian);
        assert_eq!(detect_cyrillic_language("щў"), Language::Bulgarian);
    }
    #[test]
    fn detect_cyrillic_language_long_input_terminates() {
        let long = "а".repeat(200_000);
        assert_eq!(detect_cyrillic_language(&long), Language::Russian);
        let mut trailing = long;
        trailing.push('\u{0460}');
        assert_eq!(
            detect_cyrillic_language(&trailing),
            Language::SlavonicChurch
        );
    }
    // ---------------------------------------------------------------------
    // detect_devanagari_language
    // ---------------------------------------------------------------------
    #[test]
    fn detect_devanagari_language_defaults_to_hindi() {
        assert_eq!(detect_devanagari_language(""), Language::Hindi);
        assert_eq!(detect_devanagari_language("नमस्ते"), Language::Hindi);
        assert_eq!(detect_devanagari_language("hello"), Language::Hindi);
    }
    #[test]
    fn detect_devanagari_language_markers_and_boundaries() {
        assert_eq!(detect_devanagari_language("\u{0933}"), Language::Marathi); // ळ
        assert_eq!(detect_devanagari_language("\u{1CD0}"), Language::Sanskrit);
        assert_eq!(detect_devanagari_language("\u{1CFF}"), Language::Sanskrit);
        assert_eq!(detect_devanagari_language("\u{1CCF}"), Language::Hindi);
        assert_eq!(detect_devanagari_language("\u{1D00}"), Language::Hindi);
        assert_eq!(detect_devanagari_language("\u{0932}"), Language::Hindi);
        assert_eq!(detect_devanagari_language("\u{0934}"), Language::Hindi);
        // Positional, not priority-ordered — whichever marker comes first wins.
        assert_eq!(
            detect_devanagari_language("\u{1CD0}\u{0933}"),
            Language::Sanskrit
        );
        assert_eq!(
            detect_devanagari_language("\u{0933}\u{1CD0}"),
            Language::Marathi
        );
    }
    #[test]
    fn detect_devanagari_language_long_input_terminates() {
        let long = "न".repeat(200_000);
        assert_eq!(detect_devanagari_language(&long), Language::Hindi);
    }
    // ---------------------------------------------------------------------
    // detect_greek_language
    // ---------------------------------------------------------------------
    #[test]
    fn detect_greek_language_defaults_to_monotonic() {
        assert_eq!(detect_greek_language(""), Language::GreekMono);
        assert_eq!(detect_greek_language("Γειά σου"), Language::GreekMono);
        assert_eq!(detect_greek_language("hello"), Language::GreekMono);
    }
    #[test]
    fn detect_greek_language_markers_and_boundaries() {
        assert_eq!(detect_greek_language("\u{2C80}"), Language::Coptic);
        assert_eq!(detect_greek_language("\u{2CFF}"), Language::Coptic);
        assert_eq!(detect_greek_language("\u{2C7F}"), Language::GreekMono);
        assert_eq!(detect_greek_language("\u{2D00}"), Language::GreekMono);
        assert_eq!(detect_greek_language("\u{1F00}"), Language::GreekPoly);
        assert_eq!(detect_greek_language("\u{1FFF}"), Language::GreekPoly);
        assert_eq!(detect_greek_language("\u{1EFF}"), Language::GreekMono);
        assert_eq!(detect_greek_language("\u{2000}"), Language::GreekMono);
        // Positional, not priority-ordered.
        assert_eq!(
            detect_greek_language("\u{1F00}\u{2C80}"),
            Language::GreekPoly
        );
        assert_eq!(detect_greek_language("\u{2C80}\u{1F00}"), Language::Coptic);
    }
    #[test]
    fn detect_greek_language_long_input_terminates() {
        let long = "α".repeat(200_000);
        assert_eq!(detect_greek_language(&long), Language::GreekMono);
    }
    // ---------------------------------------------------------------------
    // detect_latin_language
    // ---------------------------------------------------------------------
    #[test]
    fn detect_latin_language_defaults_to_english() {
        assert_eq!(detect_latin_language(""), Language::EnglishUS);
        assert_eq!(
            detect_latin_language("the quick brown fox"),
            Language::EnglishUS
        );
        assert_eq!(
            detect_latin_language("0123456789 !@#$%"),
            Language::EnglishUS
        );
        assert_eq!(detect_latin_language("\u{1F600}"), Language::EnglishUS);
        // Non-Latin text is not validated — it still falls through to English.
        assert_eq!(detect_latin_language("你好"), Language::EnglishUS);
    }
    #[test]
    fn detect_latin_language_single_char_markers() {
        let cases: [(char, Language); 17] = [
            ('ß', Language::German1996),
            ('ä', Language::German1996),
            ('ő', Language::Hungarian),
            ('ł', Language::Polish),
            ('ř', Language::Czech),
            ('ľ', Language::Slovak),
            ('ā', Language::Latvian),
            ('ą', Language::Lithuanian),
            ('ă', Language::Romanian),
            ('ğ', Language::Turkish),
            ('đ', Language::Croatian),
            ('þ', Language::Icelandic),
            ('ŵ', Language::Welsh),
            ('æ', Language::NorwegianBokmal),
            ('å', Language::Swedish),
            ('ñ', Language::Spanish),
            ('á', Language::Spanish),
        ];
        for (ch, expected) in cases {
            assert_eq!(
                detect_latin_language(&ch.to_string()),
                expected,
                "char {ch:?}"
            );
            // Position within the text must not matter for early-return markers.
            assert_eq!(detect_latin_language(&format!("word {ch} word")), expected);
        }
    }
    #[test]
    fn detect_latin_language_flag_combinations() {
        // The three deferred flags (ç / õ / ã) drive the French-Estonian-Portuguese
        // tie-break at the end of the scan.
        assert_eq!(detect_latin_language("ç"), Language::French);
        assert_eq!(detect_latin_language("garçon"), Language::French);
        assert_eq!(detect_latin_language("õ"), Language::Estonian);
        assert_eq!(detect_latin_language("õhtu"), Language::Estonian);
        assert_eq!(detect_latin_language("ã"), Language::Portuguese);
        assert_eq!(detect_latin_language("çõ"), Language::Portuguese);
        assert_eq!(detect_latin_language("çã"), Language::Portuguese);
        assert_eq!(detect_latin_language("õã"), Language::Portuguese);
        assert_eq!(detect_latin_language("çõã"), Language::Portuguese);
        assert_eq!(detect_latin_language("informação"), Language::Portuguese);
    }
    #[test]
    fn detect_latin_language_accented_vowel_short_circuits_the_flags() {
        // BUG PIN: 'á'|'é'|'í'|'ó'|'ú' return Spanish *immediately*, so any French or
        // Portuguese word carrying an accented vowel before its ç/õ/ã is reported as
        // Spanish — the flag tie-break never runs. Pinned as-is; see the report.
        assert_eq!(detect_latin_language("café"), Language::Spanish);
        assert_eq!(detect_latin_language("présentation"), Language::Spanish);
        assert_eq!(detect_latin_language("é ç"), Language::Spanish);
        // Order matters: with the ç first, the flag survives to the tie-break — but
        // only because no accented vowel is seen at all.
        assert_eq!(detect_latin_language("ç e"), Language::French);
    }
    #[test]
    fn detect_latin_language_first_marker_wins() {
        assert_eq!(detect_latin_language("ßä"), Language::German1996);
        assert_eq!(detect_latin_language("łß"), Language::Polish);
        assert_eq!(detect_latin_language("åæ"), Language::Swedish);
        assert_eq!(detect_latin_language("æå"), Language::NorwegianBokmal);
    }
    #[test]
    fn detect_latin_language_long_input_terminates() {
        let long = "a".repeat(500_000);
        assert_eq!(detect_latin_language(&long), Language::EnglishUS);
        // Marker at the very end — no early return until the last char.
        let mut trailing = long;
        trailing.push('ß');
        assert_eq!(detect_latin_language(&trailing), Language::German1996);
    }
    // ---------------------------------------------------------------------
    // script_to_language
    // ---------------------------------------------------------------------
    #[test]
    fn script_to_language_is_total_over_every_script() {
        // No script/text combination may panic, and the result must be deterministic.
        let texts = [
            "",
            " ",
            "hello",
            "\u{1F600}",
            "\u{0000}\u{FFFF}\u{10FFFF}",
            "ß ç õ ã щ ळ \u{09F0} \u{2C80}",
        ];
        for script in ALL_SCRIPTS {
            for text in texts {
                let first = script_to_language(script, text);
                let second = script_to_language(script, text);
                assert_eq!(first, second, "{script:?} + {text:?} is not deterministic");
            }
        }
    }
    #[test]
    fn script_to_language_direct_mappings_ignore_the_text() {
        // These 19 scripts map to a fixed language; the text argument must not matter,
        // not even for text stuffed with every other script's marker chars.
        let cases: [(Script, Language); 19] = [
            (Script::Ethiopic, Language::Ethiopic),
            (Script::Georgian, Language::Georgian),
            (Script::Gujarati, Language::Gujarati),
            (Script::Gurmukhi, Language::Panjabi),
            (Script::Kannada, Language::Kannada),
            (Script::Malayalam, Language::Malayalam),
            (Script::Mandarin, Language::Chinese),
            (Script::Oriya, Language::Oriya),
            (Script::Tamil, Language::Tamil),
            (Script::Telugu, Language::Telugu),
            (Script::Thai, Language::Thai),
            (Script::Myanmar, Language::Thai),
            (Script::Khmer, Language::Thai),
            (Script::Sinhala, Language::Hindi),
            (Script::Arabic, Language::Chinese),
            (Script::Hebrew, Language::Chinese),
            (Script::Hangul, Language::Chinese),
            (Script::Hiragana, Language::Chinese),
            (Script::Katakana, Language::Chinese),
        ];
        let long = "x".repeat(10_000);
        for (script, expected) in cases {
            for text in ["", "ß щ ळ \u{09F0} \u{2C80} \u{1F600}", long.as_str()] {
                assert_eq!(
                    script_to_language(script, text),
                    expected,
                    "{script:?} must map to {expected:?} regardless of the text"
                );
            }
        }
    }
    #[test]
    fn script_to_language_delegates_the_five_text_sensitive_scripts() {
        let probes = ["", "hello", "ß", "щ", "\u{0933}", "\u{2C80}", "\u{09F0}"];
        for text in probes {
            assert_eq!(
                script_to_language(Script::Bengali, text),
                detect_bengali_language(text),
                "Bengali delegation broke for {text:?}"
            );
            assert_eq!(
                script_to_language(Script::Cyrillic, text),
                detect_cyrillic_language(text),
                "Cyrillic delegation broke for {text:?}"
            );
            assert_eq!(
                script_to_language(Script::Devanagari, text),
                detect_devanagari_language(text),
                "Devanagari delegation broke for {text:?}"
            );
            assert_eq!(
                script_to_language(Script::Greek, text),
                detect_greek_language(text),
                "Greek delegation broke for {text:?}"
            );
            assert_eq!(
                script_to_language(Script::Latin, text),
                detect_latin_language(text),
                "Latin delegation broke for {text:?}"
            );
        }
    }
    #[test]
    fn detect_script_then_script_to_language_end_to_end() {
        let cases: [(&str, Script, Language); 6] = [
            ("straße", Script::Latin, Language::German1996),
            ("Привет", Script::Cyrillic, Language::Russian),
            ("Здравейте, щастие", Script::Cyrillic, Language::Bulgarian),
            ("你好世界", Script::Mandarin, Language::Chinese),
            ("สวัสดี", Script::Thai, Language::Thai),
            ("ಕನ್ನಡ", Script::Kannada, Language::Kannada),
        ];
        for (text, script, language) in cases {
            let detected = detect_script(text).unwrap_or_else(|| panic!("no script for {text:?}"));
            assert_eq!(detected, script, "script for {text:?}");
            assert_eq!(
                script_to_language(detected, text),
                language,
                "language for {text:?}"
            );
        }
    }
    #[test]
    fn script_to_language_survives_pseudo_random_text() {
        for seed in [7u64, 0x1234_5678_9ABC_DEF0] {
            let text = lcg_chars(2_000, seed);
            for script in ALL_SCRIPTS {
                let lang = script_to_language(script, &text);
                assert_eq!(lang, script_to_language(script, &text));
            }
        }
    }
}