1#[allow(
23 unused_imports,
24 clippy::wildcard_imports,
25 reason = "Standard workspace module prelude"
26)]
27use std::collections::{HashMap, HashSet};
28use std::sync::LazyLock;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
32pub enum UnicodeVersion {
33 #[default]
35 V17_0,
36 V16_0,
38 V15_1,
40 V15_0,
42}
43
44fn get_ucd_file_for_version(
46 version: UnicodeVersion,
47 name: &str,
48) -> Option<String> {
49 match version {
50 UnicodeVersion::V17_0 => ctb_storage_asset_bundle::get_asset_utf8(
51 &format!("data/Unicode/Unicode-17.0.0/UCD/{name}"),
52 )
53 .ok(),
54 UnicodeVersion::V16_0 => ctb_storage_asset_bundle::get_asset_utf8(
55 &format!("data/Unicode/Unicode-16.0.0/UCD/{name}"),
56 )
57 .ok(),
58 UnicodeVersion::V15_1 => ctb_storage_asset_bundle::get_asset_utf8(
59 &format!("data/Unicode/Unicode-15.1.0/UCD/{name}"),
60 )
61 .ok(),
62 UnicodeVersion::V15_0 => ctb_storage_asset_bundle::get_asset_utf8(
63 &format!("data/Unicode/Unicode-15.0.0/UCD/{name}"),
64 )
65 .ok(),
66 }
67}
68
69fn get_character_descriptions_file(name: &str) -> Option<String> {
71 ctb_storage_asset_bundle::get_asset_utf8(&format!(
72 "data/character_descriptions/{name}"
73 ))
74 .ok()
75}
76
77#[derive(Debug, Clone)]
79pub struct UnicodeBlock {
80 pub start: u32,
81 pub end: u32,
82 pub name: String,
83}
84
85#[derive(Debug, Default, Clone)]
87pub struct NameAliasEntry {
88 pub correction: Option<String>,
89 pub control: Option<String>,
90 pub abbreviation: Option<String>,
91 pub alternate: Option<String>,
92 pub figment: Option<String>,
93 pub corrections: Vec<String>,
94 pub controls: Vec<String>,
95 pub abbreviations: Vec<String>,
96 pub alternates: Vec<String>,
97 pub figments: Vec<String>,
98}
99
100#[derive(Debug, Default, Clone)]
102pub struct UnicodeCharInfo {
103 pub name: String,
104 pub informative_aliases: Vec<String>,
105 pub is_control: bool,
106 pub general_category: String,
107 pub nameslist_control_name: Option<String>,
108 pub nameslist_control_abbr: Option<String>,
109 pub annotations: Vec<String>,
110 pub cross_references: Vec<u32>,
111 pub formal_aliases: Vec<String>,
112}
113
114#[derive(Debug, Default, Clone)]
116pub struct UnikemetEntry {
117 pub unik_code: Option<String>,
118 pub description: Option<String>,
119}
120
121#[derive(Debug, Default, Clone)]
123pub struct TangutEntry {
124 pub source_ref: Option<String>,
125 pub meaning: Option<String>,
126}
127
128pub struct UnicodeDataTables {
130 pub blocks: Vec<UnicodeBlock>,
131 pub name_aliases: HashMap<u32, NameAliasEntry>,
132 pub char_data: HashMap<u32, UnicodeCharInfo>,
133 pub standardized_variants: HashMap<u32, String>,
134 pub unikemet_data: HashMap<u32, UnikemetEntry>,
135 pub tangut_data: HashMap<u32, TangutEntry>,
136 pub derived_age: HashMap<String, HashSet<u32>>,
137 pub unified_ideographs: HashSet<u32>,
138 pub tangut_ideographs: HashSet<u32>,
139 pub khitan_characters: HashSet<u32>,
140}
141
142impl UnicodeDataTables {
143 #[must_use]
145 pub fn is_age(&self, age: &str, cp: u32) -> bool {
146 self.derived_age
147 .get(age)
148 .is_some_and(|set| set.contains(&cp))
149 }
150
151 #[must_use]
153 pub fn is_v17_or_later(&self, cp: u32) -> bool {
154 self.derived_age
155 .iter()
156 .filter(|(ver, _)| ver.starts_with("17."))
157 .any(|(_, set)| set.contains(&cp))
158 }
159
160 #[must_use]
162 pub fn is_cjk_unified_ideograph(&self, cp: u32) -> bool {
163 self.unified_ideographs.contains(&cp)
164 }
165
166 #[must_use]
168 pub fn is_tangut_ideograph(&self, cp: u32) -> bool {
169 self.tangut_ideographs.contains(&cp)
170 }
171
172 #[must_use]
174 pub fn is_khitan_character(&self, cp: u32) -> bool {
175 self.khitan_characters.contains(&cp)
176 }
177
178 #[must_use]
180 pub fn is_assigned(&self, cp: u32) -> bool {
181 if cp > 0x10_FFFF
182 || is_noncharacter(cp)
183 || (0xD800..=0xDFFF).contains(&cp)
184 {
185 return false;
186 }
187 self.char_data.contains_key(&cp)
188 || self.is_cjk_unified_ideograph(cp)
189 || self.is_tangut_ideograph(cp)
190 || self.is_khitan_character(cp)
191 || (0xAC00..=0xD7A3).contains(&cp)
192 || (0xE000..=0xF8FF).contains(&cp)
193 || (0xF0000..=0xFFFFD).contains(&cp)
194 || (0x100000..=0x10FFFD).contains(&cp)
195 }
196
197 #[must_use]
199 pub fn get_general_category(&self, cp: u32) -> Option<&str> {
200 self.char_data
201 .get(&cp)
202 .map(|info| info.general_category.as_str())
203 }
204
205 #[must_use]
207 pub fn is_format_char(&self, cp: u32) -> bool {
208 self.get_general_category(cp) == Some("Cf")
209 }
210}
211
212fn parse_nameslist_xref(text: &str) -> Option<u32> {
214 let trimmed = text.trim();
215 if let Some(inside) =
216 trimmed.strip_prefix('(').and_then(|s| s.strip_suffix(')'))
217 {
218 let inside = inside.trim();
219 if let Some((_name, hex_part)) = inside.rsplit_once('-') {
220 u32::from_str_radix(hex_part.trim(), 16).ok()
221 } else if let Some(last_tok) = inside.split_whitespace().next_back() {
222 u32::from_str_radix(last_tok.trim(), 16).ok()
223 } else {
224 None
225 }
226 } else {
227 u32::from_str_radix(trimmed, 16).ok()
228 }
229}
230
231fn load_tables(version: UnicodeVersion) -> UnicodeDataTables {
232 let mut blocks = Vec::new();
234 if let Some(content) = get_ucd_file_for_version(version, "Blocks.txt") {
235 for line in content.lines() {
236 let trimmed = line.trim();
237 if trimmed.is_empty() || trimmed.starts_with('#') {
238 continue;
239 }
240 let Some((range_part, name_part)) = trimmed.split_once(';') else {
241 continue;
242 };
243 let Some((start_hex, end_hex)) = range_part.trim().split_once("..")
244 else {
245 continue;
246 };
247 let Ok(start) = u32::from_str_radix(start_hex.trim(), 16) else {
248 continue;
249 };
250 let Ok(end) = u32::from_str_radix(end_hex.trim(), 16) else {
251 continue;
252 };
253 blocks.push(UnicodeBlock {
254 start,
255 end,
256 name: name_part.trim().to_string(),
257 });
258 }
259 }
260
261 let mut name_aliases: HashMap<u32, NameAliasEntry> = HashMap::new();
263 if let Some(content) = get_ucd_file_for_version(version, "NameAliases.txt")
264 {
265 for line in content.lines() {
266 let trimmed = line.trim();
267 if trimmed.is_empty() || trimmed.starts_with('#') {
268 continue;
269 }
270 let parts: Vec<&str> = trimmed.split(';').collect();
271 if parts.len() < 3 {
272 continue;
273 }
274 let (Some(&cp_hex), Some(&alias), Some(&kind)) =
275 (parts.first(), parts.get(1), parts.get(2))
276 else {
277 continue;
278 };
279 let Ok(cp) = u32::from_str_radix(cp_hex.trim(), 16) else {
280 continue;
281 };
282 let entry = name_aliases.entry(cp).or_default();
283 let alias_trimmed = alias.trim().to_string();
284 match kind.trim() {
285 "correction" => {
286 entry.correction = Some(alias_trimmed.clone());
287 entry.corrections.push(alias_trimmed);
288 }
289 "control" => {
290 entry.control = Some(alias_trimmed.clone());
291 entry.controls.push(alias_trimmed);
292 }
293 "abbreviation" => {
294 entry.abbreviation = Some(alias_trimmed.clone());
295 entry.abbreviations.push(alias_trimmed);
296 }
297 "alternate" => {
298 entry.alternate = Some(alias_trimmed.clone());
299 entry.alternates.push(alias_trimmed);
300 }
301 "figment" => {
302 entry.figment = Some(alias_trimmed.clone());
303 entry.figments.push(alias_trimmed);
304 }
305 _ => {}
306 }
307 }
308 }
309
310 let mut char_data: HashMap<u32, UnicodeCharInfo> = HashMap::new();
312 if let Some(content) = get_ucd_file_for_version(version, "UnicodeData.txt")
313 {
314 for line in content.lines() {
315 let trimmed = line.trim();
316 if trimmed.is_empty() || trimmed.starts_with('#') {
317 continue;
318 }
319 let parts: Vec<&str> = trimmed.split(';').collect();
320 if parts.len() < 3 {
321 continue;
322 }
323 let (Some(&cp_hex), Some(&name), Some(&cat)) =
324 (parts.first(), parts.get(1), parts.get(2))
325 else {
326 continue;
327 };
328 let Ok(cp) = u32::from_str_radix(cp_hex.trim(), 16) else {
329 continue;
330 };
331 let is_control = cat.trim() == "Cc" || name.trim() == "<control>";
332 char_data.insert(
333 cp,
334 UnicodeCharInfo {
335 name: name.trim().to_string(),
336 informative_aliases: Vec::new(),
337 is_control,
338 general_category: cat.trim().to_string(),
339 nameslist_control_name: None,
340 nameslist_control_abbr: None,
341 annotations: Vec::new(),
342 cross_references: Vec::new(),
343 formal_aliases: Vec::new(),
344 },
345 );
346 }
347 }
348
349 if let Some(content) = get_ucd_file_for_version(version, "NamesList.txt") {
350 let mut current_cp: Option<u32> = None;
351 for line in content.lines() {
352 if line.starts_with('@') {
353 current_cp = None;
354 } else if line.starts_with('\t') {
355 if let Some(cp) = current_cp {
356 let rest = line.trim_start_matches('\t');
357 if let Some(alias) = rest.strip_prefix("= ") {
358 let trimmed_alias = alias.trim();
359 let entry = char_data.entry(cp).or_default();
360 if entry.is_control {
361 if entry.nameslist_control_name.is_none() {
362 if let Some((name_part, abbr_part)) =
363 trimmed_alias
364 .strip_suffix(')')
365 .and_then(|s| s.rsplit_once('('))
366 {
367 entry.nameslist_control_name =
368 Some(name_part.trim().to_string());
369 entry.nameslist_control_abbr =
370 Some(abbr_part.trim().to_string());
371 } else {
372 entry.nameslist_control_name =
373 Some(trimmed_alias.to_string());
374 }
375 } else if !trimmed_alias.ends_with("(1.0)") {
376 entry
377 .informative_aliases
378 .push(trimmed_alias.to_string());
379 }
380 } else if !trimmed_alias.ends_with("(1.0)") {
381 entry
382 .informative_aliases
383 .push(trimmed_alias.to_string());
384 }
385 } else if let Some(annot) = rest.strip_prefix("* ") {
386 let entry = char_data.entry(cp).or_default();
387 let trimmed_annot = annot.trim();
388 if !trimmed_annot.is_empty() {
389 entry.annotations.push(trimmed_annot.to_string());
390 }
391 } else if let Some(xref_raw) = rest.strip_prefix("x ") {
392 if let Some(target) = parse_nameslist_xref(xref_raw) {
393 let entry = char_data.entry(cp).or_default();
394 entry.cross_references.push(target);
395 }
396 } else if let Some(formal) = rest.strip_prefix("% ") {
397 let entry = char_data.entry(cp).or_default();
398 let trimmed_formal = formal.trim();
399 if !trimmed_formal.is_empty() {
400 entry
401 .formal_aliases
402 .push(trimmed_formal.to_string());
403 }
404 }
405 }
406 } else if !line.is_empty() {
407 let trimmed = line.trim();
408 if let Some((hex_str, name)) = trimmed.split_once('\t') {
409 if let Ok(cp) = u32::from_str_radix(hex_str.trim(), 16) {
410 current_cp = Some(cp);
411 let entry = char_data.entry(cp).or_default();
412 if entry.name.is_empty() || entry.name.starts_with('<')
413 {
414 entry.name = name.trim().to_string();
415 }
416 } else {
417 current_cp = None;
418 }
419 } else {
420 current_cp = None;
421 }
422 }
423 }
424 }
425
426 let mut standardized_variants = HashMap::new();
428 if let Some(content) =
429 get_ucd_file_for_version(version, "StandardizedVariants.txt")
430 {
431 for line in content.lines() {
432 let trimmed = line.trim();
433 if trimmed.is_empty() || trimmed.starts_with('#') {
434 continue;
435 }
436 let parts: Vec<&str> = trimmed.split(';').collect();
437 if parts.len() < 2 {
438 continue;
439 }
440 let (Some(&seq_part), Some(&desc_part)) =
441 (parts.first(), parts.get(1))
442 else {
443 continue;
444 };
445 let seq: Vec<&str> = seq_part.split_whitespace().collect();
446 if seq.len() != 2 {
447 continue;
448 }
449 let (Some(&base_hex), Some(&vs_hex)) = (seq.first(), seq.get(1))
450 else {
451 continue;
452 };
453 let (Ok(base_cp), Ok(vs_cp)) = (
454 u32::from_str_radix(base_hex.trim(), 16),
455 u32::from_str_radix(vs_hex.trim(), 16),
456 ) else {
457 continue;
458 };
459
460 let desc = desc_part.trim();
461 if let Some(comp_name) =
462 desc.strip_prefix("CJK COMPATIBILITY IDEOGRAPH-")
463 {
464 let comp_hex = comp_name.trim().trim_end_matches(';');
465 if let Ok(comp_cp) = u32::from_str_radix(comp_hex, 16) {
466 let vs_num = if (0xFE00..=0xFE0F).contains(&vs_cp) {
467 vs_cp.saturating_sub(0xFE00).saturating_add(1)
468 } else if (0xE0100..=0xE01EF).contains(&vs_cp) {
469 vs_cp.saturating_sub(0xE0100).saturating_add(17)
470 } else {
471 1
472 };
473 let formatted = format!("= U+{base_cp:04X} + VS{vs_num}");
474 standardized_variants.insert(comp_cp, formatted);
475 }
476 }
477 }
478 }
479
480 let mut unikemet_data: HashMap<u32, UnikemetEntry> = HashMap::new();
482 if let Some(content) = get_ucd_file_for_version(version, "Unikemet.txt") {
483 for line in content.lines() {
484 let trimmed = line.trim();
485 if trimmed.is_empty() || trimmed.starts_with('#') {
486 continue;
487 }
488 let parts: Vec<&str> = trimmed.split('\t').collect();
489 if parts.len() < 3 {
490 continue;
491 }
492 let (Some(&cp_str), Some(&key), Some(&val)) =
493 (parts.first(), parts.get(1), parts.get(2))
494 else {
495 continue;
496 };
497 let Some(hex_str) = cp_str.strip_prefix("U+") else {
498 continue;
499 };
500 let Ok(cp) = u32::from_str_radix(hex_str.trim(), 16) else {
501 continue;
502 };
503 let entry = unikemet_data.entry(cp).or_default();
504 match key.trim() {
505 "kEH_UniK" => entry.unik_code = Some(val.trim().to_string()),
506 "kEH_Desc" => {
507 let desc = if version == UnicodeVersion::V16_0 {
508 val.trim_end_matches('.').to_string()
509 } else {
510 val.trim().trim_end_matches('.').to_string()
511 };
512 entry.description = Some(desc);
513 }
514 _ => {}
515 }
516 }
517 }
518
519 let mut tangut_data: HashMap<u32, TangutEntry> = HashMap::new();
521 if let Some(content) =
522 get_ucd_file_for_version(version, "TangutSources.txt")
523 {
524 for line in content.lines() {
525 let trimmed = line.trim();
526 if trimmed.is_empty() || trimmed.starts_with('#') {
527 continue;
528 }
529 let parts: Vec<&str> = trimmed.split('\t').collect();
530 if parts.len() < 3 {
531 continue;
532 }
533 let (Some(&cp_str), Some(&key), Some(&val)) =
534 (parts.first(), parts.get(1), parts.get(2))
535 else {
536 continue;
537 };
538 let Some(hex_str) = cp_str.strip_prefix("U+") else {
539 continue;
540 };
541 let Ok(cp) = u32::from_str_radix(hex_str.trim(), 16) else {
542 continue;
543 };
544 if key.trim() == "kTGT_MergedSrc" {
545 let entry = tangut_data.entry(cp).or_default();
546 entry.source_ref = Some(val.trim().to_string());
547 }
548 }
549 }
550
551 if let Some(content) = get_character_descriptions_file("TangutMeanings.csv")
552 {
553 let mut rdr = csv::ReaderBuilder::new()
554 .has_headers(true)
555 .flexible(true)
556 .from_reader(content.as_bytes());
557 for result in rdr.records() {
558 let Ok(record) = result else {
559 continue;
560 };
561 let (Some(hex_str), Some(def)) = (record.get(0), record.get(1))
562 else {
563 continue;
564 };
565 let Ok(cp) = u32::from_str_radix(hex_str.trim(), 16) else {
566 continue;
567 };
568 if !def.trim().is_empty() {
569 let entry = tangut_data.entry(cp).or_default();
570 entry.meaning = Some(def.trim().to_string());
571 }
572 }
573 }
574
575 if let Some(content) =
576 get_character_descriptions_file("TangutSupplementMeanings.csv")
577 {
578 let mut rdr = csv::ReaderBuilder::new()
579 .has_headers(true)
580 .flexible(true)
581 .from_reader(content.as_bytes());
582 for result in rdr.records() {
583 let Ok(record) = result else {
584 continue;
585 };
586 let (Some(hex_str), Some(def)) = (record.get(0), record.get(1))
587 else {
588 continue;
589 };
590 let Ok(cp) = u32::from_str_radix(hex_str.trim(), 16) else {
591 continue;
592 };
593 let entry = tangut_data.entry(cp).or_default();
594 if !def.trim().is_empty() && entry.meaning.is_none() {
595 entry.meaning = Some(def.trim().to_string());
596 }
597 if let Some(src) = record.get(5) {
598 if !src.trim().is_empty() && entry.source_ref.is_none() {
599 entry.source_ref = Some(src.trim().to_string());
600 }
601 }
602 }
603 }
604
605 let mut derived_age: HashMap<String, HashSet<u32>> = HashMap::new();
607 if let Some(content) =
608 get_ucd_file_for_version(UnicodeVersion::V17_0, "DerivedAge.txt")
609 {
610 for line in content.lines() {
611 let trimmed = line.trim();
612 if trimmed.is_empty() || trimmed.starts_with('#') {
613 continue;
614 }
615 let Some((range_part, rest)) = trimmed.split_once(';') else {
616 continue;
617 };
618 let age_val = rest.split('#').next().unwrap_or("").trim();
620 if !age_val.is_empty() {
621 let set = derived_age.entry(age_val.to_string()).or_default();
622 if let Some((start_hex, end_hex)) =
623 range_part.trim().split_once("..")
624 {
625 if let (Ok(start), Ok(end)) = (
626 u32::from_str_radix(start_hex.trim(), 16),
627 u32::from_str_radix(end_hex.trim(), 16),
628 ) {
629 for cp in start..=end {
630 set.insert(cp);
631 }
632 }
633 } else if let Ok(cp) =
634 u32::from_str_radix(range_part.trim(), 16)
635 {
636 set.insert(cp);
637 }
638 }
639 }
640 }
641
642 let mut unified_ideographs: HashSet<u32> = HashSet::new();
644 if let Some(content) = get_ucd_file_for_version(version, "PropList.txt") {
645 for line in content.lines() {
646 let trimmed = line.trim();
647 if trimmed.is_empty() || trimmed.starts_with('#') {
648 continue;
649 }
650 let Some((range_part, rest)) = trimmed.split_once(';') else {
651 continue;
652 };
653 let prop = rest.split('#').next().unwrap_or("").trim();
655 if prop == "Unified_Ideograph" {
656 if let Some((start_hex, end_hex)) =
657 range_part.trim().split_once("..")
658 {
659 if let (Ok(start), Ok(end)) = (
660 u32::from_str_radix(start_hex.trim(), 16),
661 u32::from_str_radix(end_hex.trim(), 16),
662 ) {
663 for cp in start..=end {
664 unified_ideographs.insert(cp);
665 }
666 }
667 } else if let Ok(cp) =
668 u32::from_str_radix(range_part.trim(), 16)
669 {
670 unified_ideographs.insert(cp);
671 }
672 }
673 }
674 }
675
676 let mut tangut_ideographs: HashSet<u32> = HashSet::new();
678 let mut khitan_characters: HashSet<u32> = HashSet::new();
679 if let Some(content) = get_ucd_file_for_version(version, "Scripts.txt") {
680 for line in content.lines() {
681 let trimmed = line.trim();
682 if trimmed.is_empty() || trimmed.starts_with('#') {
683 continue;
684 }
685 let Some((range_part, rest)) = trimmed.split_once(';') else {
686 continue;
687 };
688 let (script_part, comment) =
690 rest.split_once('#').unwrap_or((rest, ""));
691 let script = script_part.trim();
692 let comment_trimmed = comment.trim();
693
694 if script == "Tangut" {
695 if comment_trimmed.contains("TANGUT IDEOGRAPH-") {
696 if let Some((start_hex, end_hex)) =
697 range_part.trim().split_once("..")
698 {
699 if let (Ok(start), Ok(end)) = (
700 u32::from_str_radix(start_hex.trim(), 16),
701 u32::from_str_radix(end_hex.trim(), 16),
702 ) {
703 for cp in start..=end {
704 tangut_ideographs.insert(cp);
705 }
706 }
707 } else if let Ok(cp) =
708 u32::from_str_radix(range_part.trim(), 16)
709 {
710 tangut_ideographs.insert(cp);
711 }
712 }
713 } else if script == "Khitan_Small_Script"
714 && comment_trimmed.contains("KHITAN SMALL SCRIPT CHARACTER-")
715 {
716 if let Some((start_hex, end_hex)) =
717 range_part.trim().split_once("..")
718 {
719 if let (Ok(start), Ok(end)) = (
720 u32::from_str_radix(start_hex.trim(), 16),
721 u32::from_str_radix(end_hex.trim(), 16),
722 ) {
723 for cp in start..=end {
724 khitan_characters.insert(cp);
725 }
726 }
727 } else if let Ok(cp) =
728 u32::from_str_radix(range_part.trim(), 16)
729 {
730 khitan_characters.insert(cp);
731 }
732 }
733 }
734 }
735
736 UnicodeDataTables {
737 blocks,
738 name_aliases,
739 char_data,
740 standardized_variants,
741 unikemet_data,
742 tangut_data,
743 derived_age,
744 unified_ideographs,
745 tangut_ideographs,
746 khitan_characters,
747 }
748}
749
750pub static TABLES_V17: LazyLock<UnicodeDataTables> =
751 LazyLock::new(|| load_tables(UnicodeVersion::V17_0));
752pub static TABLES_V16: LazyLock<UnicodeDataTables> =
753 LazyLock::new(|| load_tables(UnicodeVersion::V16_0));
754pub static TABLES_V15_1: LazyLock<UnicodeDataTables> =
755 LazyLock::new(|| load_tables(UnicodeVersion::V15_1));
756pub static TABLES_V15_0: LazyLock<UnicodeDataTables> =
757 LazyLock::new(|| load_tables(UnicodeVersion::V15_0));
758
759pub fn get_tables(version: UnicodeVersion) -> &'static UnicodeDataTables {
760 match version {
761 UnicodeVersion::V17_0 => &TABLES_V17,
762 UnicodeVersion::V16_0 => &TABLES_V16,
763 UnicodeVersion::V15_1 => &TABLES_V15_1,
764 UnicodeVersion::V15_0 => &TABLES_V15_0,
765 }
766}
767
768pub static KHITAN_DATA: LazyLock<HashMap<u32, String>> = LazyLock::new(|| {
770 let Some(content) = get_character_descriptions_file("KhitanMeanings.csv")
771 else {
772 return HashMap::new();
773 };
774 let mut map = HashMap::new();
775 let mut rdr = csv::ReaderBuilder::new()
776 .has_headers(true)
777 .flexible(true)
778 .from_reader(content.as_bytes());
779 for result in rdr.records() {
780 let Ok(record) = result else {
781 continue;
782 };
783 let (Some(hex_str), Some(def)) = (record.get(0), record.get(1)) else {
784 continue;
785 };
786 let Ok(cp) = u32::from_str_radix(hex_str.trim(), 16) else {
787 continue;
788 };
789 if !def.trim().is_empty() {
790 map.insert(cp, def.trim().to_string());
791 }
792 }
793 map
794});
795
796#[derive(Debug, Default, Clone)]
798pub struct UnihanReadingEntry {
799 pub definition: Option<String>,
800 pub mandarin: Option<String>,
801 pub cantonese: Option<String>,
802 pub japanese: Option<String>,
803 pub korean: Option<String>,
804 pub vietnamese: Option<String>,
805}
806
807pub static UNIHAN_DATA: LazyLock<HashMap<u32, UnihanReadingEntry>> =
809 LazyLock::new(|| {
810 let Some(content) = ctb_storage_asset_bundle::get_asset_utf8(
811 "data/Unicode/Unicode-17.0.0/Unihan/Unihan/Unihan_Readings.txt",
812 )
813 .ok() else {
814 return HashMap::new();
815 };
816 let mut map: HashMap<u32, UnihanReadingEntry> = HashMap::new();
817 for line in content.lines() {
818 let trimmed = line.trim();
819 if trimmed.is_empty() || trimmed.starts_with('#') {
820 continue;
821 }
822 let parts: Vec<&str> = trimmed.split('\t').collect();
823 if parts.len() < 3 {
824 continue;
825 }
826 let (Some(&cp_str), Some(&key), Some(&val)) =
827 (parts.first(), parts.get(1), parts.get(2))
828 else {
829 continue;
830 };
831 let Some(hex_str) = cp_str.strip_prefix("U+") else {
832 continue;
833 };
834 let Ok(cp) = u32::from_str_radix(hex_str.trim(), 16) else {
835 continue;
836 };
837 let entry = map.entry(cp).or_default();
838 match key.trim() {
839 "kDefinition" => {
840 entry.definition = Some(val.trim().to_string());
841 }
842 "kMandarin" => entry.mandarin = Some(val.trim().to_string()),
843 "kCantonese" => entry.cantonese = Some(val.trim().to_string()),
844 "kJapanese" | "kJapaneseKun" | "kJapaneseOn" => {
845 if entry.japanese.is_none() {
846 entry.japanese = Some(val.trim().to_string());
847 }
848 }
849 "kKorean" | "kHangul" => {
850 if entry.korean.is_none() {
851 entry.korean = Some(val.trim().to_string());
852 }
853 }
854 "kVietnamese" => {
855 entry.vietnamese = Some(val.trim().to_string());
856 }
857 _ => {}
858 }
859 }
860 map
861 });
862
863pub fn is_noncharacter(cp: u32) -> bool {
865 if (0xFDD0..=0xFDEF).contains(&cp) {
866 return true;
867 }
868 let low16 = cp & 0xFFFF;
869 (low16 == 0xFFFE || low16 == 0xFFFF) && cp <= 0x10FFFF
870}
871
872pub fn find_block_with_version(
874 version: UnicodeVersion,
875 cp: u32,
876) -> Option<&'static str> {
877 let tables = get_tables(version);
878 for b in &tables.blocks {
879 if cp >= b.start && cp <= b.end {
880 return Some(&b.name);
881 }
882 }
883 None
884}
885
886pub fn find_block(cp: u32) -> Option<&'static str> {
888 find_block_with_version(UnicodeVersion::V17_0, cp)
889}
890
891pub fn is_assigned_unicode(cp: u32) -> bool {
893 get_tables(UnicodeVersion::V17_0).is_assigned(cp)
894}