ctb_formats_unicode/
character_description.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND Unicode-3.0
2// SPDX-License-Identifier for parts derived from Unicode data: Unicode-3.0
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// See additional licensing details at end of file.
22
23//! Independent reimplementation of Andrew West's "What Unicode Character is This" tool.
24
25#[allow(
26    unused_imports,
27    clippy::wildcard_imports,
28    reason = "Standard workspace module prelude"
29)]
30use crate::utilities::*;
31
32pub use crate::data::UnicodeVersion;
33use crate::data::{
34    KHITAN_DATA, UNIHAN_DATA, UnicodeDataTables, find_block_with_version,
35    get_tables, is_noncharacter,
36};
37
38const HANGUL_S_BASE: u32 = 0xAC00;
39const HANGUL_T_COUNT: u32 = 28;
40const HANGUL_N_COUNT: u32 = 588; // 21 * 28
41const HANGUL_S_COUNT: u32 = 11172; // 19 * 588
42
43const JAMO_L_TABLE: [&str; 19] = [
44    "G", "GG", "N", "D", "DD", "R", "M", "B", "BB", "S", "SS", "", "J", "JJ",
45    "C", "K", "T", "P", "H",
46];
47const JAMO_V_TABLE: [&str; 21] = [
48    "A", "AE", "YA", "YAE", "EO", "E", "YEO", "YE", "O", "WA", "WAE", "OE",
49    "YO", "U", "WEO", "WE", "WI", "YU", "EU", "YI", "I",
50];
51const JAMO_T_TABLE: [&str; 28] = [
52    "", "G", "GG", "GS", "N", "NJ", "NH", "D", "L", "LG", "LM", "LB", "LS",
53    "LT", "LP", "LH", "M", "B", "BS", "S", "SS", "NG", "J", "C", "K", "T", "P",
54    "H",
55];
56
57/// Computes the algorithmic Hangul syllable name for a code point if applicable.
58pub(crate) fn hangul_syllable_name(cp: u32) -> Option<String> {
59    if (HANGUL_S_BASE..HANGUL_S_BASE.saturating_add(HANGUL_S_COUNT))
60        .contains(&cp)
61    {
62        let s_index = cp.saturating_sub(HANGUL_S_BASE);
63        let l_index =
64            usize::try_from(s_index.checked_div(HANGUL_N_COUNT)?).ok()?;
65        let v_index = usize::try_from(
66            (s_index.checked_rem(HANGUL_N_COUNT)?)
67                .checked_div(HANGUL_T_COUNT)?,
68        )
69        .ok()?;
70        let t_index =
71            usize::try_from(s_index.checked_rem(HANGUL_T_COUNT)?).ok()?;
72        let l = JAMO_L_TABLE.get(l_index)?;
73        let v = JAMO_V_TABLE.get(v_index)?;
74        let t = JAMO_T_TABLE.get(t_index)?;
75        Some(format!("HANGUL SYLLABLE {l}{v}{t}"))
76    } else {
77        None
78    }
79}
80
81/// Checks if a codepoint is in a Private Use Area.
82fn is_private_use(cp: u32) -> bool {
83    (0xE000..=0xF8FF).contains(&cp)
84        || (0xF0000..=0xFFFFD).contains(&cp)
85        || (0x100000..=0x10FFFD).contains(&cp)
86}
87
88/// Description formatting mode.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
90pub enum DescriptionMode {
91    /// Standard enhanced format: concise reserved/PUA/surrogates, multi-alias annotations, Unihan readings.
92    #[default]
93    Standard,
94    /// Exact WUC compatibility format (matches `unicode_untrimmed_descriptions.txt`).
95    WucCompat,
96}
97
98/// Format for control character names and abbreviations.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
100pub enum ControlNameFormat {
101    /// Official UCD `NameAliases` (e.g. ALERT [BEL], END OF LINE [EOL]).
102    #[default]
103    NameAliases,
104    /// Legacy `NamesList` names (e.g. BELL [BEL], LINE FEED [LF], [EOM]).
105    NamesList,
106    /// "What Unicode Character is This" format
107    Wuc,
108}
109
110/// Options controlling character description generation.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct DescriptionOptions {
113    pub mode: DescriptionMode,
114    pub control_name_format: ControlNameFormat,
115    pub unicode_version: UnicodeVersion,
116    pub include_unihan_readings: bool,
117}
118
119impl Default for DescriptionOptions {
120    fn default() -> Self {
121        Self {
122            mode: DescriptionMode::Standard,
123            control_name_format: ControlNameFormat::NameAliases,
124            unicode_version: UnicodeVersion::V17_0,
125            include_unihan_readings: true,
126        }
127    }
128}
129
130impl DescriptionOptions {
131    #[must_use]
132    pub const fn standard() -> Self {
133        Self {
134            mode: DescriptionMode::Standard,
135            control_name_format: ControlNameFormat::NameAliases,
136            unicode_version: UnicodeVersion::V17_0,
137            include_unihan_readings: true,
138        }
139    }
140
141    #[must_use]
142    pub const fn wuc_compat() -> Self {
143        Self {
144            mode: DescriptionMode::WucCompat,
145            control_name_format: ControlNameFormat::Wuc,
146            unicode_version: UnicodeVersion::V16_0,
147            include_unihan_readings: false,
148        }
149    }
150}
151
152/// Returns true if a code point is a control character according to UCD data
153/// or C0/C1 ranges.
154#[must_use]
155pub(crate) fn is_control_codepoint(
156    tables: &UnicodeDataTables,
157    cp: u32,
158) -> bool {
159    tables
160        .char_data
161        .get(&cp)
162        .is_some_and(|info| info.is_control)
163        || (0x0000..=0x001F).contains(&cp)
164        || (0x007F..=0x009F).contains(&cp)
165}
166
167/// Resolves the canonical Unicode character name for a code point using the
168/// provided UCD tables and description mode.
169///
170/// This handles control character names (from `NamesList` or `NameAliases`),
171/// algorithmic character names (Hangul syllables, CJK unified ideographs,
172/// Tangut ideographs, Khitan small script characters, Egyptian hieroglyphs),
173/// and standard character names from UnicodeData.txt / NamesList.txt.
174#[must_use]
175pub(crate) fn get_unicode_character_name(
176    tables: &UnicodeDataTables,
177    cp: u32,
178    mode: DescriptionMode,
179) -> Option<String> {
180    if cp > 0x10_FFFF {
181        return None;
182    }
183
184    let char_info = tables.char_data.get(&cp);
185    let alias_entry = tables.name_aliases.get(&cp);
186
187    // Control characters
188    if is_control_codepoint(tables, cp) {
189        let base_name = if let Some(info) = char_info {
190            info.nameslist_control_name.as_deref()
191        } else {
192            None
193        }
194        .or_else(|| alias_entry.and_then(|entry| entry.control.as_deref()));
195
196        let prefix = if matches!(cp, 0x0009..=0x000D | 0x001C..=0x001F | 0x0085)
197        {
198            "<control, Unicode-semantic-defined>"
199        } else {
200            "<control>"
201        };
202
203        return match base_name {
204            Some(name) => Some(format!("{prefix} {name}")),
205            None => Some(format!("{prefix} <control-{cp:04X}>")),
206        };
207    }
208
209    if let Some(hangul) = hangul_syllable_name(cp) {
210        return Some(hangul);
211    }
212    if tables.is_cjk_unified_ideograph(cp) {
213        if mode == DescriptionMode::WucCompat
214            && ((0xF900..=0xFAFF).contains(&cp)
215                || (0x2F800..=0x2FA1F).contains(&cp))
216        {
217            return Some(format!("CJK COMPATIBILITY IDEOGRAPH-{cp:04X}"));
218        }
219        return Some(format!("CJK UNIFIED IDEOGRAPH-{cp:04X}"));
220    }
221    if tables.is_tangut_ideograph(cp) {
222        return Some(format!("TANGUT IDEOGRAPH-{cp:04X}"));
223    }
224    if tables.is_khitan_character(cp) {
225        return Some(format!("KHITAN SMALL SCRIPT CHARACTER-{cp:04X}"));
226    }
227    if (0x13460..=0x143FA).contains(&cp) {
228        if mode == DescriptionMode::Standard {
229            if let Some(entry) = tables.unikemet_data.get(&cp) {
230                if let Some(ref unik) = entry.unik_code {
231                    return Some(format!("EGYPTIAN HIEROGLYPH {unik}"));
232                }
233            }
234        }
235        if let Some(info) = char_info {
236            if !info.name.is_empty() && !info.name.starts_with('<') {
237                return Some(info.name.clone());
238            }
239        }
240    }
241    if let Some(info) = char_info {
242        if !info.name.is_empty() && !info.name.starts_with('<') {
243            return Some(info.name.clone());
244        }
245    }
246
247    None
248}
249
250/// Formats a single Unicode code point into a detailed description string using default options.
251pub fn describe_codepoint(cp: u32) -> String {
252    describe_codepoint_with_options(cp, DescriptionOptions::default())
253}
254
255/// Formats a single Unicode code point with the given options.
256pub fn describe_codepoint_with_options(
257    cp: u32,
258    options: DescriptionOptions,
259) -> String {
260    // 1. High and Low Surrogates
261    if (0xD800..=0xDBFF).contains(&cp) {
262        if options.mode == DescriptionMode::WucCompat {
263            return format!("U+{cp:04X} : <surrogate>");
264        }
265        return format!("U+{cp:04X} : <surrogate> (high surrogate)");
266    }
267    if (0xDC00..=0xDFFF).contains(&cp) {
268        if options.mode == DescriptionMode::WucCompat {
269            return format!("U+{cp:04X} : <surrogate>");
270        }
271        return format!("U+{cp:04X} : <surrogate> (low surrogate)");
272    }
273
274    // 2. Noncharacter Code Points
275    if is_noncharacter(cp) {
276        return format!("U+{cp:04X} : <noncharacter>");
277    }
278
279    // 3. Private Use Area
280    if is_private_use(cp) {
281        if options.mode == DescriptionMode::WucCompat {
282            return format!("U+{cp:04X} : <private-use>");
283        }
284        if let Some(block) =
285            find_block_with_version(options.unicode_version, cp)
286        {
287            return format!("U+{cp:04X} : <private-use> ({block} block)");
288        }
289        return format!("U+{cp:04X} : <private-use>");
290    }
291
292    let tables = get_tables(options.unicode_version);
293
294    // In WUC compatibility mode, characters newly assigned in Unicode 17.0+ (and late 16.0 additions) were reserved
295    if options.mode == DescriptionMode::WucCompat
296        && (get_tables(UnicodeVersion::V17_0).is_v17_or_later(cp)
297            || matches!(cp, 0x1F8B2..=0x1F8BB | 0x1F8C0..=0x1F8C1 | 0x2B739))
298    {
299        return format!("U+{cp:04X} : <reserved>");
300    }
301
302    let char_info = tables.char_data.get(&cp);
303    let alias_entry = tables.name_aliases.get(&cp);
304
305    // 4. Control Characters
306    if is_control_codepoint(tables, cp) {
307        let (control_name, abbr) = match options.control_name_format {
308            ControlNameFormat::Wuc => {
309                let name = char_info
310                    .and_then(|info| info.nameslist_control_name.as_deref());
311                let ab =
312                    if matches!(cp, 0x000B | 0x001C | 0x001D | 0x001E | 0x001F)
313                    {
314                        None
315                    } else if cp == 0x0009 {
316                        Some("TAB")
317                    } else if cp == 0x0019 {
318                        Some("EOM")
319                    } else {
320                        char_info
321                            .and_then(|info| {
322                                info.nameslist_control_abbr.as_deref()
323                            })
324                            .or_else(|| {
325                                alias_entry
326                                    .and_then(|a| a.abbreviation.as_deref())
327                            })
328                    };
329                (name, ab)
330            }
331            ControlNameFormat::NamesList => {
332                let name = char_info
333                    .and_then(|info| info.nameslist_control_name.as_deref());
334                let ab = char_info
335                    .and_then(|info| info.nameslist_control_abbr.as_deref())
336                    .or_else(|| {
337                        alias_entry.and_then(|a| a.abbreviation.as_deref())
338                    });
339                (name, ab)
340            }
341            ControlNameFormat::NameAliases => {
342                let name = alias_entry.and_then(|a| a.control.as_deref());
343                let ab = alias_entry.and_then(|a| a.abbreviation.as_deref());
344                (name, ab)
345            }
346        };
347
348        let mut res = match (control_name, abbr) {
349            (Some(name), Some(ab)) => {
350                format!("U+{cp:04X} : <control> {name} [{ab}]")
351            }
352            (Some(name), None) => format!("U+{cp:04X} : <control> {name}"),
353            (None, Some(ab)) => {
354                if options.mode == DescriptionMode::WucCompat {
355                    format!("U+{cp:04X} : <control>")
356                } else {
357                    format!("U+{cp:04X} : <control> [{ab}]")
358                }
359            }
360            (None, None) => format!("U+{cp:04X} : <control>"),
361        };
362
363        if let Some(info) = char_info {
364            if !info.informative_aliases.is_empty() {
365                let joined = info.informative_aliases.join("; ");
366                res.push_str(&format!(" {{{joined}}}"));
367            }
368        }
369        return res;
370    }
371
372    // 5. Named Unicode Characters & Algorithmic Ranges
373    let primary_name = get_unicode_character_name(tables, cp, options.mode);
374
375    // 6. Unassigned / Reserved Code Points
376    let Some(mut name) = primary_name else {
377        if options.mode == DescriptionMode::WucCompat {
378            return format!("U+{cp:04X} : <reserved>");
379        }
380        if let Some(block) =
381            find_block_with_version(options.unicode_version, cp)
382        {
383            return format!("U+{cp:04X} : <reserved> ({block} block)");
384        }
385        return format!("U+{cp:04X} : <reserved> (unassigned region)");
386    };
387
388    if options.mode == DescriptionMode::WucCompat {
389        // Name adjustments (omitted hyphens in Arabic/Uyghur/Cypro-Minoan/Minnan/Znamenny/X-Ray names)
390        if matches!(
391            cp,
392            0x0898
393                | 0x10F72
394                | 0x12F90..=0x12FF2
395                | 0x1AFF0..=0x1AFF3
396                | 0x1AFF5..=0x1AFFB
397                | 0x1AFFD..=0x1AFFE
398                | 0x1CF42..=0x1CF43
399                | 0x1FA7B
400                | 0xFD46..=0xFD4E
401        ) {
402            name = name.replace('-', "");
403        }
404        // NamesList leading-space quirk in Devanagari, Kawi, Kaktovik, Cyrillic Ext-D, Nag Mundari
405        if matches!(
406            cp,
407            0x11B00..=0x11B09
408                | 0x11F00..=0x11F59
409                | 0x1D2C0..=0x1D2D3
410                | 0x1E030..=0x1E06D
411                | 0x1E08F
412                | 0x1E4D0..=0x1E4F9
413        ) {
414            name = format!(" {name}");
415        }
416        // Typo in Tamil sign - this was corrected to UZHAKKU very shortly before the Unicode 12 release in which it was added.
417        if cp == 0x11FD8 {
418            name = "TAMIL SIGN UZHAAKKU".to_string();
419        }
420    }
421
422    let mut result = format!("U+{cp:04X} : {name}");
423
424    // 7. Graphic Character Abbreviation from NameAliases.txt
425    if let Some(abbr) = alias_entry.and_then(|a| a.abbreviation.as_deref()) {
426        if !name.ends_with(&format!("[{abbr}]")) {
427            result.push_str(&format!(" [{abbr}]"));
428        }
429    }
430
431    // 8. Formal Correction Alias
432    if options.mode == DescriptionMode::WucCompat {
433        if cp == 0xFEFF {
434            result.push_str(" (alias BYTE ORDER MARK [BOM])");
435        } else if !matches!(
436            cp,
437            0x0616 | 0x1BBD | 0x12327 | 0x1680B | 0x1E899 | 0x1E89A
438        ) {
439            if let Some(alias) =
440                alias_entry.and_then(|a| a.correction.as_deref())
441            {
442                result.push_str(&format!(" (alias {alias})"));
443            }
444        }
445    } else if let Some(alias) =
446        alias_entry.and_then(|a| a.correction.as_deref())
447    {
448        result.push_str(&format!(" (alias {alias})"));
449    }
450
451    // 9. Tangut Source Reference
452    if let Some(src) = tables
453        .tangut_data
454        .get(&cp)
455        .and_then(|t| t.source_ref.as_deref())
456    {
457        result.push_str(&format!(" ({src})"));
458    }
459
460    // 10. Standardized Variation Sequence (CJK Compatibility Ideographs)
461    if let Some(variant) = tables.standardized_variants.get(&cp) {
462        result.push_str(&format!(" {variant}"));
463    }
464
465    // 11. Informative Annotations & Meanings
466    if options.mode == DescriptionMode::WucCompat {
467        match cp {
468            0x002C => result.push_str(" {decimal separator}"),
469            0x0040 => result.push_str(" {at sign}"),
470            0x0060 | 0x0195 | 0x025C | 0x2C6D | 0xA729 | 0xA7FB..=0xA7FD | 0x12326 | 0x187F0..=0x187F6 => {}
471            0x018E => result.push_str(" {turned e}"),
472            0x0190 => result.push_str(" {epsilon}"),
473            0x01C2 => result.push_str(" {double-barred pipe; palatoalveolar click (IPA)}"),
474            0x01C3 => result.push_str(" {(post)alveolar click (IPA)}"),
475            0x0292 => result.push_str(" {dram}"),
476            0x13158 => result.push_str(" {A saharan helmeted guinea fowl (Numida meleagris), with a lappet}"),
477            0x131D8 => result.push_str(" {A forearm, with the palm of the hand facing upwards (D36), written over a desert plant, with four branches, with flowers on every branch, on a horizontal base (M26)}"),
478            0x132D6 => result.push_str(" {The union of the red crown of Lower Egypt and the white crown of Upper Egypt, with the white crown worn within the red crown (i.e., the double crown)}"),
479            0x132D7 => result.push_str(" {The union of the red crown of Lower Egypt and the white crown of Upper Egypt, with the white crown worn within the red crown (i.e., the double crown, S5), on top of a wickerwork basket (V30)}"),
480            0x134BB => result.push_str(" {Man, naked, written horizontally, facing upwards, with the head looking downwards, with knees and hips bend, lower arm bend beside the body, elbow downwards, hand upwards, facing outwards, upper arm hanging loosely beside the body}"),
481            0x13509 => result.push_str(" {Man, standing, both arms towards the front, holding an key for a tumbler lock consisting of a slightly bend vertical line with two shorter horizontal lines attached to the top akin to a flag, pointing outwards, as if to strike with it}"),
482            0x135A5 => result.push_str(" {Man, seated on heel, right knee raised, with a feather on the head (angled backwards), right arm raised, left arm in front of body}"),
483            0x135AD => result.push_str(" {Man, seated, both knees down, right arm forward, forearm horizontal, holding a bow or shield, left arm in front of the body, holding multiple sticks or arrows, angling backwards, leaning against the left shoulder}"),
484            0x135DC => result.push_str(" {3 men, kneeling/walking on knees, gound together around the neck, first man, right knee before left knee, both arms raised in front, handpalms outward, second man, right knee just in front of left knee, both arms behind the back, as if bound, third man, right knee and foot in front of the left knee, left lower leg raised at 45°, right arm in front, hand against the head of the second man, left arm behind the back, hand visible in front of the waist}"),
485            0x13977 => result.push_str(" {An eye with a painted lower lid, and two lines at the top forming a V shape}"),
486            0x13CF1 => result.push_str(" {A saharan helmeted guinea fowl (Numida meleagris), without a lappet}"),
487            0x13CF2 => result.push_str(" {A saharan helmeted guinea fowl (Numida meleagris), with a lappet, without the two protruding feathers on its head}"),
488            0x13CF4 => result.push_str(" {A saharan helmeted guinea fowl (Numida meleagris), without a lappet, without the two protruding feathers on its head}"),
489            0x13E06 => result.push_str(" {A tree without foliage, or a branch with many side branches}"),
490            0x13E9B => result.push_str(" {A forearm, with the palm of the hand facing upwards (D36), written over a desert plant with a flower, without branches, }"),
491            0x13FEB => result.push_str(" {A column resembling a stem of papyrus with a bud (M13), on a base, with a }"),
492            0x140C6 => result.push_str(" { A brazier resembling a wide cup (W10), with a flame rising from it, flame angling towards the front}"),
493            0x140C7 => result.push_str(" { A brazier with a flame rising from it, flame angling towards the front, represented as dots}"),
494            0x140C8 => result.push_str(" { A brazier with a flame rising from it, flame curving forwards}"),
495            0x1415B => result.push_str(" {The union of the red crown of Lower Egypt and the white crown of Upper Egypt, with the white crown worn within the red crown (i.e., the double crown), with an Uraeus at the front}"),
496            0x14343 => result.push_str(" { A wickerwork basket with a handle at either side}"),
497            _ => {
498                if let Some(desc) = tables
499                    .unikemet_data
500                    .get(&cp)
501                    .and_then(|u| u.description.as_deref())
502                {
503                    result.push_str(&format!(" {{{desc}}}"));
504                } else if let Some(meaning) = tables
505                    .tangut_data
506                    .get(&cp)
507                    .and_then(|t| t.meaning.as_deref())
508                {
509                    result.push_str(&format!(" {{{meaning}}}"));
510                } else if let Some(meaning) = KHITAN_DATA.get(&cp) {
511                    result.push_str(&format!(" {{{meaning}}}"));
512                } else if let Some(info) = char_info {
513                    if !info.informative_aliases.is_empty() {
514                        let joined = info.informative_aliases.join("; ");
515                        result.push_str(&format!(" {{{joined}}}"));
516                    }
517                }
518            }
519        }
520    } else if let Some(desc) = tables
521        .unikemet_data
522        .get(&cp)
523        .and_then(|u| u.description.as_deref())
524    {
525        result.push_str(&format!(" {{{desc}}}"));
526    } else if let Some(meaning) = tables
527        .tangut_data
528        .get(&cp)
529        .and_then(|t| t.meaning.as_deref())
530    {
531        result.push_str(&format!(" {{{meaning}}}"));
532    } else if let Some(meaning) = KHITAN_DATA.get(&cp) {
533        result.push_str(&format!(" {{{meaning}}}"));
534    } else if let Some(info) = char_info {
535        if !info.informative_aliases.is_empty() {
536            let joined = info.informative_aliases.join("; ");
537            result.push_str(&format!(" {{{joined}}}"));
538        }
539    }
540
541    // 12. Unihan Readings & Definitions
542    if options.include_unihan_readings {
543        if let Some(unihan) = UNIHAN_DATA.get(&cp) {
544            let mut parts = Vec::new();
545            if let Some(ref def) = unihan.definition {
546                parts.push(format!("def: {def}"));
547            }
548            if let Some(ref man) = unihan.mandarin {
549                parts.push(format!("Mandarin: {man}"));
550            }
551            if let Some(ref can) = unihan.cantonese {
552                parts.push(format!("Cantonese: {can}"));
553            }
554            if let Some(ref jap) = unihan.japanese {
555                parts.push(format!("Japanese: {jap}"));
556            }
557            if let Some(ref kor) = unihan.korean {
558                parts.push(format!("Korean: {kor}"));
559            }
560            if let Some(ref viet) = unihan.vietnamese {
561                parts.push(format!("Vietnamese: {viet}"));
562            }
563            if !parts.is_empty() {
564                let joined = parts.join("; ");
565                result.push_str(&format!(" {{{joined}}}"));
566            }
567        }
568    }
569
570    result
571}
572
573/// Describes each character in a Unicode string line by line using default options.
574pub fn describe(input: &str) -> String {
575    describe_with_options(input, DescriptionOptions::default())
576}
577
578/// Describes each character in a Unicode string line by line with given options.
579pub fn describe_with_options(
580    input: &str,
581    options: DescriptionOptions,
582) -> String {
583    let mut out = String::new();
584    for ch in input.chars() {
585        let cp = u32::from(ch);
586        let line = describe_codepoint_with_options(cp, options);
587        out.push_str(&line);
588        out.push('\n');
589    }
590    out
591}
592
593#[cfg(test)]
594#[allow(
595    clippy::panic,
596    clippy::expect_used,
597    clippy::unwrap_used,
598    clippy::unwrap_in_result,
599    clippy::panic_in_result_fn,
600    clippy::indexing_slicing,
601    clippy::arithmetic_side_effects,
602    reason = "Standard repository test boilerplate"
603)]
604mod tests {
605    use super::*;
606
607    #[crate::ctb_test]
608    fn can_describe_string_standard() {
609        let input = "द्ध्र्य︘ꡀ𓉔A 😂\u{0004}𗿼선𘮝";
610        let out = describe(input);
611        assert!(out.contains("U+0926 : DEVANAGARI LETTER DA"));
612        assert!(out.contains("U+094D : DEVANAGARI SIGN VIRAMA {halant (the preferred Hindi name)}"));
613        assert!(out.contains("U+FE18 : PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRAKCET (alias PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRACKET)"));
614        assert!(out.contains("U+13254 : EGYPTIAN HIEROGLYPH O004 {A plan of a courtyard or reed shelter}"));
615        assert!(out.contains("U+0041 : LATIN CAPITAL LETTER A"));
616        assert!(out.contains("U+0020 : SPACE [SP]"));
617        assert!(out.contains("U+1F602 : FACE WITH TEARS OF JOY"));
618        assert!(out.contains("U+0004 : <control> END OF TRANSMISSION [EOT]"));
619        assert!(
620            out.contains(
621                "U+17FFC : TANGUT IDEOGRAPH-17FFC (L2008-2262) {bird}"
622            )
623        );
624        assert!(out.contains("U+C120 : HANGUL SYLLABLE SEON"));
625        assert!(
626            out.contains(
627                "U+18B9D : KHITAN SMALL SCRIPT CHARACTER-18B9D {GOLD}"
628            )
629        );
630
631        let input = "द्ध्र्य︘ꡀ𓉔A字😂\u{0004}𗿼선𘮝\u{F9FA}";
632        let expected = "U+0926 : DEVANAGARI LETTER DA
633U+094D : DEVANAGARI SIGN VIRAMA {halant (the preferred Hindi name)}
634U+0927 : DEVANAGARI LETTER DHA
635U+094D : DEVANAGARI SIGN VIRAMA {halant (the preferred Hindi name)}
636U+0930 : DEVANAGARI LETTER RA
637U+094D : DEVANAGARI SIGN VIRAMA {halant (the preferred Hindi name)}
638U+092F : DEVANAGARI LETTER YA
639U+FE18 : PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRAKCET (alias PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRACKET)
640U+A840 : PHAGS-PA LETTER KA
641U+13254 : EGYPTIAN HIEROGLYPH O004 {A plan of a courtyard or reed shelter}
642U+0041 : LATIN CAPITAL LETTER A
643U+5B57 : CJK UNIFIED IDEOGRAPH-5B57 {def: letter, character, word; Mandarin: zì; Cantonese: zi6; Japanese: ジ シ あざ あざな やしなう; Korean: 자:0E; Vietnamese: tự}
644U+1F602 : FACE WITH TEARS OF JOY
645U+0004 : <control> END OF TRANSMISSION [EOT]
646U+17FFC : TANGUT IDEOGRAPH-17FFC (L2008-2262) {bird}
647U+C120 : HANGUL SYLLABLE SEON
648U+18B9D : KHITAN SMALL SCRIPT CHARACTER-18B9D {GOLD}
649U+F9FA : CJK COMPATIBILITY IDEOGRAPH-F9FA = U+72C0 + VS1 {def: form; appearance; shape; official; Korean: 장:0}
650";
651        assert_eq!(describe(input), expected);
652    }
653
654    #[crate::ctb_test]
655    fn can_describe_string_wuc_compat() {
656        let options = DescriptionOptions::wuc_compat();
657        let out = describe_with_options("!\u{0007}\u{0009}\u{000A}", options);
658        assert!(out.contains("U+0021 : EXCLAMATION MARK {factorial; bang}"));
659        assert!(out.contains("U+0007 : <control> BELL [BEL]"));
660        assert!(out.contains("U+0009 : <control> CHARACTER TABULATION [TAB] {horizontal tabulation (HT); tab}"));
661        assert!(out.contains("U+000A : <control> LINE FEED [LF] {new line (NL); end of line (EOL)}"));
662    }
663
664    #[crate::ctb_test]
665    fn test_surrogates_and_noncharacters_and_reserved() {
666        assert_eq!(
667            describe_codepoint(0xD800),
668            "U+D800 : <surrogate> (high surrogate)"
669        );
670        assert_eq!(
671            describe_codepoint(0xDBFF),
672            "U+DBFF : <surrogate> (high surrogate)"
673        );
674        assert_eq!(
675            describe_codepoint(0xDC00),
676            "U+DC00 : <surrogate> (low surrogate)"
677        );
678        assert_eq!(
679            describe_codepoint(0xDFFF),
680            "U+DFFF : <surrogate> (low surrogate)"
681        );
682        assert_eq!(describe_codepoint(0xFDD0), "U+FDD0 : <noncharacter>");
683        assert_eq!(describe_codepoint(0xFFFF), "U+FFFF : <noncharacter>");
684        assert_eq!(describe_codepoint(0x1FFFE), "U+1FFFE : <noncharacter>");
685        assert_eq!(
686            describe_codepoint(0x1BC9A),
687            "U+1BC9A : <reserved> (Duployan block)"
688        );
689        assert_eq!(
690            describe_codepoint(0x35000),
691            "U+35000 : <reserved> (unassigned region)"
692        );
693        assert_eq!(
694            describe_codepoint(0xE000),
695            "U+E000 : <private-use> (Private Use Area block)"
696        );
697    }
698
699    #[crate::ctb_test]
700    fn test_wuc_mode_descriptions() {
701        let wuc_opts = DescriptionOptions::wuc_compat();
702
703        // 1. Control characters in legacy NamesList format
704        assert_eq!(
705            describe_codepoint_with_options(0x0000, wuc_opts),
706            "U+0000 : <control> NULL [NUL]"
707        );
708        assert_eq!(
709            describe_codepoint_with_options(0x0007, wuc_opts),
710            "U+0007 : <control> BELL [BEL]"
711        );
712        assert_eq!(
713            describe_codepoint_with_options(0x0009, wuc_opts),
714            "U+0009 : <control> CHARACTER TABULATION [TAB] {horizontal tabulation (HT); tab}"
715        );
716        assert_eq!(
717            describe_codepoint_with_options(0x000A, wuc_opts),
718            "U+000A : <control> LINE FEED [LF] {new line (NL); end of line (EOL)}"
719        );
720        assert_eq!(
721            describe_codepoint_with_options(0x0019, wuc_opts),
722            "U+0019 : <control> END OF MEDIUM [EOM]"
723        );
724        assert_eq!(
725            describe_codepoint_with_options(0x0080, wuc_opts),
726            "U+0080 : <control>"
727        );
728        assert_eq!(
729            describe_codepoint_with_options(0x0082, wuc_opts),
730            "U+0082 : <control> BREAK PERMITTED HERE [BPH]"
731        );
732
733        // 2. Graphic abbreviations
734        assert_eq!(
735            describe_codepoint_with_options(0x0020, wuc_opts),
736            "U+0020 : SPACE [SP]"
737        );
738        assert_eq!(
739            describe_codepoint_with_options(0x00A0, wuc_opts),
740            "U+00A0 : NO-BREAK SPACE [NBSP]"
741        );
742        assert_eq!(
743            describe_codepoint_with_options(0x00AD, wuc_opts),
744            "U+00AD : SOFT HYPHEN [SHY] {discretionary hyphen}"
745        );
746
747        // 3. Informative alias joining
748        assert_eq!(
749            describe_codepoint_with_options(0x0021, wuc_opts),
750            "U+0021 : EXCLAMATION MARK {factorial; bang}"
751        );
752        assert_eq!(
753            describe_codepoint_with_options(0x0023, wuc_opts),
754            "U+0023 : NUMBER SIGN {pound sign (weight); hashtag, hash; crosshatch, octothorpe}"
755        );
756        assert_eq!(
757            describe_codepoint_with_options(0x0027, wuc_opts),
758            "U+0027 : APOSTROPHE {single quote; APL quote}"
759        );
760
761        // 4. Surrogates, Noncharacters, Reserved, PUA in WUC compat mode
762        assert_eq!(
763            describe_codepoint_with_options(0xD800, wuc_opts),
764            "U+D800 : <surrogate>"
765        );
766        assert_eq!(
767            describe_codepoint_with_options(0xDC00, wuc_opts),
768            "U+DC00 : <surrogate>"
769        );
770        assert_eq!(
771            describe_codepoint_with_options(0xFDD0, wuc_opts),
772            "U+FDD0 : <noncharacter>"
773        );
774        assert_eq!(
775            describe_codepoint_with_options(0x0378, wuc_opts),
776            "U+0378 : <reserved>"
777        );
778        assert_eq!(
779            describe_codepoint_with_options(0xE000, wuc_opts),
780            "U+E000 : <private-use>"
781        );
782        assert_eq!(
783            describe_codepoint_with_options(0xF0000, wuc_opts),
784            "U+F0000 : <private-use>"
785        );
786
787        // 5. CJK Compatibility Ideographs in WUC compat mode
788        assert_eq!(
789            describe_codepoint_with_options(0xFA0E, wuc_opts),
790            "U+FA0E : CJK COMPATIBILITY IDEOGRAPH-FA0E"
791        );
792    }
793
794    #[crate::ctb_test]
795    fn test_standard_mode_descriptions() {
796        let std_opts = DescriptionOptions::standard();
797
798        // 1. Surrogates with high/low designation
799        assert_eq!(
800            describe_codepoint_with_options(0xD800, std_opts),
801            "U+D800 : <surrogate> (high surrogate)"
802        );
803        assert_eq!(
804            describe_codepoint_with_options(0xDC00, std_opts),
805            "U+DC00 : <surrogate> (low surrogate)"
806        );
807
808        // 2. Noncharacters
809        assert_eq!(
810            describe_codepoint_with_options(0xFDD0, std_opts),
811            "U+FDD0 : <noncharacter>"
812        );
813
814        // 3. Reserved with block name or unassigned region
815        assert_eq!(
816            describe_codepoint_with_options(0x0378, std_opts),
817            "U+0378 : <reserved> (Greek and Coptic block)"
818        );
819        assert_eq!(
820            describe_codepoint_with_options(0x35000, std_opts),
821            "U+35000 : <reserved> (unassigned region)"
822        );
823
824        // 4. Private Use Area with block name
825        assert_eq!(
826            describe_codepoint_with_options(0xE000, std_opts),
827            "U+E000 : <private-use> (Private Use Area block)"
828        );
829
830        // 5. Official UCD control names
831        assert_eq!(
832            describe_codepoint_with_options(0x0007, std_opts),
833            "U+0007 : <control> ALERT [BEL]"
834        );
835        assert_eq!(
836            describe_codepoint_with_options(0x000A, std_opts),
837            "U+000A : <control> END OF LINE [EOL] {new line (NL); end of line (EOL)}"
838        );
839
840        // 6. CJK Unified Ideograph with Unihan readings
841        let desc_3400 = describe_codepoint_with_options(0x3400, std_opts);
842        assert!(desc_3400.starts_with("U+3400 : CJK UNIFIED IDEOGRAPH-3400"));
843        assert!(desc_3400.contains("def: (same as 丘) hillock or mound"));
844        assert!(desc_3400.contains("Mandarin: qiū"));
845        assert!(desc_3400.contains("Cantonese: jau1"));
846
847        // 7. CJK Unified Ideograph in compatibility range (U+FA0E)
848        let desc_fa0e = describe_codepoint_with_options(0xFA0E, std_opts);
849        assert!(desc_fa0e.starts_with("U+FA0E : CJK UNIFIED IDEOGRAPH-FA0E"));
850    }
851
852    #[crate::ctb_test]
853    fn test_options_configurations() {
854        let mut custom_opts = DescriptionOptions::standard();
855        custom_opts.control_name_format = ControlNameFormat::NamesList;
856        custom_opts.include_unihan_readings = false;
857
858        assert_eq!(
859            describe_codepoint_with_options(0x0007, custom_opts),
860            "U+0007 : <control> BELL [BEL]"
861        );
862        assert_eq!(
863            describe_codepoint_with_options(0x3400, custom_opts),
864            "U+3400 : CJK UNIFIED IDEOGRAPH-3400"
865        );
866
867        let multiline = describe_with_options("\u{0007}A", custom_opts);
868        assert_eq!(
869            multiline,
870            "U+0007 : <control> BELL [BEL]\nU+0041 : LATIN CAPITAL LETTER A\n"
871        );
872
873        let default_multiline = describe("A");
874        assert_eq!(default_multiline, "U+0041 : LATIN CAPITAL LETTER A\n");
875
876        // Test UnicodeDataTables derived_age & block lookup & dynamic ideograph lookup
877        let tables_v17 = get_tables(UnicodeVersion::V17_0);
878        assert!(tables_v17.is_age("1.1", 0x0041));
879        assert!(tables_v17.is_age("16.0", 0x1FA89)); // HARP
880        assert!(tables_v17.is_v17_or_later(0x088F));
881        assert!(!tables_v17.is_v17_or_later(0x0041));
882        assert!(tables_v17.is_cjk_unified_ideograph(0x3400));
883        assert!(tables_v17.is_tangut_ideograph(0x17000));
884        assert!(tables_v17.is_khitan_character(0x18B00));
885
886        assert_eq!(crate::find_block(0x0041), Some("Basic Latin"));
887
888        // Test V15.0 and V15.1 tables loading and data-derived ideographs
889        let tables_v15 = get_tables(UnicodeVersion::V15_0);
890        assert!(!tables_v15.blocks.is_empty());
891        assert!(tables_v15.is_cjk_unified_ideograph(0x4E00));
892        assert!(tables_v15.is_tangut_ideograph(0x17000));
893        assert!(tables_v15.is_khitan_character(0x18B00));
894
895        let tables_v15_1 = get_tables(UnicodeVersion::V15_1);
896        assert!(!tables_v15_1.blocks.is_empty());
897        assert!(tables_v15_1.is_cjk_unified_ideograph(0x4E00));
898    }
899
900    // #[crate::ctb_test]
901    // fn test_full_file_regeneration_matches_fixture() {
902    //     let manifest_dir = std::path::PathBuf::from(
903    //         std::env::var("CARGO_MANIFEST_DIR")
904    //             .unwrap_or_else(|_| "/workspaces/ctoolbox/src/formats/unicode".to_string()),
905    //     );
906    //     // This test should pass, but I'm not including the fixture now that it's working.
907    //     let fixture_path = manifest_dir
908    //         .join("tests")
909    //         .join("fixtures")
910    //         .join("unicode_untrimmed_descriptions.txt");
911
912    //     let expected = std::fs::read_to_string(&fixture_path)
913    //         .expect("read unicode_untrimmed_descriptions.txt fixture");
914    //     let wuc_opts = DescriptionOptions::wuc_compat();
915
916    //     let mut generated = String::with_capacity(expected.len());
917    //     for cp in 0..=0x10FFFF {
918    //         let line = describe_codepoint_with_options(cp, wuc_opts);
919    //         generated.push_str(&line);
920    //         generated.push('\n');
921    //     }
922
923    //     assert_eq!(generated, expected);
924    // }
925
926    #[crate::ctb_test]
927    fn test_full_file_regeneration_matches_expected() {
928        let expected =
929            "2b1fc9126e2c9b2f7ee7398b96581db58d4f46bdc768264b198734d25d068be8";
930        let wuc_opts = DescriptionOptions::wuc_compat();
931
932        let mut generated = String::with_capacity(expected.len());
933        for cp in 0..=0x10FFFF {
934            let line = describe_codepoint_with_options(cp, wuc_opts);
935            generated.push_str(&line);
936            generated.push('\n');
937        }
938
939        use sha2::Digest;
940        let hash = sha2::Sha256::digest(generated.as_bytes());
941        assert_eq!(ctb_utilities::string::to_hex(&hash), expected);
942    }
943}
944
945/*
946
947Unikemet descriptions are used under the following Unicode license terms:
948
949```
950UNICODE LICENSE V3
951
952COPYRIGHT AND PERMISSION NOTICE
953
954Copyright © 1991-2026 Unicode, Inc.
955
956NOTICE TO USER: Carefully read the following legal agreement. BY
957DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
958SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
959TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
960DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
961
962Permission is hereby granted, free of charge, to any person obtaining a
963copy of data files and any associated documentation (the "Data Files") or
964software and any associated documentation (the "Software") to deal in the
965Data Files or Software without restriction, including without limitation
966the rights to use, copy, modify, merge, publish, distribute, and/or sell
967copies of the Data Files or Software, and to permit persons to whom the
968Data Files or Software are furnished to do so, provided that either (a)
969this copyright and permission notice appear with all copies of the Data
970Files or Software, or (b) this copyright and permission notice appear in
971associated Documentation.
972
973THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
974KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
975MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
976THIRD PARTY RIGHTS.
977
978IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
979BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
980OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
981WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
982ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
983FILES OR SOFTWARE.
984
985Except as contained in this notice, the name of a copyright holder shall
986not be used in advertising or otherwise to promote the sale, use or other
987dealings in these Data Files or Software without prior written
988authorization of the copyright holder.
989```
990*/