-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.rs
More file actions
1841 lines (1655 loc) · 59.8 KB
/
build.rs
File metadata and controls
1841 lines (1655 loc) · 59.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#[cfg(any(
feature = "gb18030",
feature = "euc-jp",
feature = "iso-2022-jp",
feature = "euc-kr",
feature = "big5",
feature = "shift-jis",
feature = "codepages-iso8859",
feature = "codepages-windows",
feature = "codepages-dos",
feature = "codepages-apple",
feature = "codepages-misc",
))]
use std::collections::BTreeMap;
#[cfg(any(
feature = "gb18030",
feature = "euc-jp",
feature = "iso-2022-jp",
feature = "euc-kr",
feature = "big5",
feature = "shift-jis",
feature = "codepages-iso8859",
feature = "codepages-windows",
feature = "codepages-dos",
feature = "codepages-apple",
feature = "codepages-misc",
))]
use std::fmt::Write;
#[cfg(any(
feature = "gb18030",
feature = "euc-jp",
feature = "iso-2022-jp",
feature = "euc-kr",
feature = "big5",
feature = "shift-jis",
feature = "codepages-iso8859",
feature = "codepages-windows",
feature = "codepages-dos",
feature = "codepages-apple",
feature = "codepages-misc",
))]
use std::path::Path;
fn main() {
// GB18030 (feature-gated)
#[cfg(feature = "gb18030")]
build_gb18030();
// Japanese encodings - JIS X 0208 table (shared by EUC-JP, ISO-2022-JP, and Shift_JIS)
#[cfg(any(feature = "euc-jp", feature = "iso-2022-jp", feature = "shift-jis"))]
build_jis0208_tables();
// JIS X 0212 table (only EUC-JP)
#[cfg(feature = "euc-jp")]
build_jis0212_tables();
// Korean encoding - EUC-KR
#[cfg(feature = "euc-kr")]
build_euckr_tables();
// Traditional Chinese - Big5
#[cfg(feature = "big5")]
build_big5_tables();
// Legacy codepages (granular feature-gated)
#[cfg(any(
feature = "codepages-iso8859",
feature = "codepages-windows",
feature = "codepages-dos",
feature = "codepages-apple",
feature = "codepages-misc",
))]
build_codepages();
}
#[cfg(feature = "gb18030")]
fn build_gb18030() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let dest = std::path::Path::new(&out_dir).join("gb18030_tables.rs");
let mut output = String::new();
output.push_str("// Generated by build.rs - do not edit manually\n");
output.push_str("// GB18030 encoding tables\n\n");
// Parse WHATWG index-gb18030.txt for 2-byte mappings (preferred, includes Euro etc.)
let index_path = Path::new("data/index-gb18030.txt");
if index_path.exists() {
generate_gbk_tables_from_whatwg(index_path, &mut output);
} else {
// Fallback to CP936.TXT
let cp936_path = Path::new("data/mappings/windows/CP936.TXT");
if cp936_path.exists() {
generate_gbk_tables_from_cp936(cp936_path, &mut output);
} else {
output.push_str("// WARNING: No 2-byte mapping files found\n");
output.push_str("pub(crate) static GBK_DECODE_2BYTE: &[(u16, char)] = &[];\n");
output.push_str("pub(crate) static GBK_ENCODE: &[(char, u16)] = &[];\n\n");
}
}
// Parse index-gb18030-ranges.txt for 4-byte algorithmic ranges
let ranges_path = Path::new("data/index-gb18030-ranges.txt");
if ranges_path.exists() {
generate_gb18030_ranges(ranges_path, &mut output);
} else {
output.push_str("// WARNING: gb18030-ranges.txt not found\n");
output.push_str("pub(crate) static GB18030_RANGES: &[(u32, u32)] = &[];\n");
}
std::fs::write(&dest, output).unwrap();
println!("cargo:rerun-if-changed=data/index-gb18030.txt");
println!("cargo:rerun-if-changed=data/mappings/windows/CP936.TXT");
println!("cargo:rerun-if-changed=data/index-gb18030-ranges.txt");
}
#[cfg(feature = "gb18030")]
/// Generate GBK tables from WHATWG index format.
/// Index format: pointer -> codepoint, where bytes are calculated from pointer.
fn generate_gbk_tables_from_whatwg(path: &Path, output: &mut String) {
let content = std::fs::read_to_string(path).unwrap();
let mut decode_2byte: BTreeMap<u16, char> = BTreeMap::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
// Format: pointer\tcodepoint\tname (tab or space separated)
let parts: Vec<&str> = line
.split(|c| c == '\t' || c == ' ')
.filter(|s| !s.is_empty())
.collect();
if parts.len() < 2 {
continue;
}
let pointer: u32 = match parts[0].parse() {
Ok(v) => v,
Err(_) => continue,
};
let cp_str = parts[1].trim();
let codepoint = if cp_str.starts_with("0x") || cp_str.starts_with("0X") {
match u32::from_str_radix(&cp_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
// Convert WHATWG pointer to actual bytes
// lead = pointer / 190 + 0x81
// offset = pointer % 190
// trail = offset + 0x40 if offset < 0x3F else offset + 0x41
let lead = (pointer / 190 + 0x81) as u8;
let offset = pointer % 190;
let trail = if offset < 0x3F {
(offset + 0x40) as u8
} else {
(offset + 0x41) as u8
};
let bytes = ((lead as u16) << 8) | (trail as u16);
if let Some(c) = char::from_u32(codepoint) {
decode_2byte.insert(bytes, c);
}
}
// Generate decode table (sorted by byte value for binary search)
writeln!(output, "/// GBK 2-byte decode table: (bytes, char)").unwrap();
writeln!(
output,
"pub(crate) static GBK_DECODE_2BYTE: &[(u16, char)] = &["
)
.unwrap();
for (&bytes, &ch) in &decode_2byte {
writeln!(output, " (0x{:04X}, '\\u{{{:04X}}}'),", bytes, ch as u32).unwrap();
}
writeln!(output, "];\n").unwrap();
// Generate encode table (sorted by char for binary search)
let mut encode: BTreeMap<char, u16> = BTreeMap::new();
for (&bytes, &ch) in &decode_2byte {
encode.entry(ch).or_insert(bytes);
}
writeln!(output, "/// GBK 2-byte encode table: (char, bytes)").unwrap();
writeln!(output, "pub(crate) static GBK_ENCODE: &[(char, u16)] = &[").unwrap();
for (&ch, &bytes) in &encode {
writeln!(output, " ('\\u{{{:04X}}}', 0x{:04X}),", ch as u32, bytes).unwrap();
}
writeln!(output, "];\n").unwrap();
}
#[cfg(feature = "gb18030")]
fn generate_gbk_tables_from_cp936(path: &Path, output: &mut String) {
let content = std::fs::read_to_string(path).unwrap();
let mut decode_2byte: BTreeMap<u16, char> = BTreeMap::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line
.split(|c| c == '\t' || c == ' ')
.filter(|s| !s.is_empty())
.collect();
if parts.len() < 2 {
continue;
}
let byte_str = parts[0].trim();
let byte_val = if byte_str.starts_with("0x") || byte_str.starts_with("0X") {
match u32::from_str_radix(&byte_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
// Only interested in 2-byte sequences (0x8140-0xFEFE range)
if byte_val <= 0xFF || byte_val > 0xFFFF {
continue;
}
let cp_str = parts[1].trim();
if cp_str.is_empty() || cp_str.starts_with('#') {
continue;
}
let codepoint = if cp_str.starts_with("0x") || cp_str.starts_with("0X") {
match u32::from_str_radix(&cp_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
if let Some(c) = char::from_u32(codepoint) {
decode_2byte.insert(byte_val as u16, c);
}
}
// Generate decode table (sorted by byte value for binary search)
writeln!(output, "/// GBK 2-byte decode table: (bytes, char)").unwrap();
writeln!(
output,
"pub(crate) static GBK_DECODE_2BYTE: &[(u16, char)] = &["
)
.unwrap();
for (&bytes, &ch) in &decode_2byte {
writeln!(output, " (0x{:04X}, '\\u{{{:04X}}}'),", bytes, ch as u32).unwrap();
}
writeln!(output, "];\n").unwrap();
// Generate encode table (sorted by char for binary search)
// Build reverse mapping, keeping first occurrence
let mut encode: BTreeMap<char, u16> = BTreeMap::new();
for (&bytes, &ch) in &decode_2byte {
encode.entry(ch).or_insert(bytes);
}
writeln!(output, "/// GBK 2-byte encode table: (char, bytes)").unwrap();
writeln!(output, "pub(crate) static GBK_ENCODE: &[(char, u16)] = &[").unwrap();
for (&ch, &bytes) in &encode {
writeln!(output, " ('\\u{{{:04X}}}', 0x{:04X}),", ch as u32, bytes).unwrap();
}
writeln!(output, "];\n").unwrap();
}
#[cfg(feature = "gb18030")]
fn generate_gb18030_ranges(path: &Path, output: &mut String) {
let content = std::fs::read_to_string(path).unwrap();
let mut ranges: Vec<(u32, u32)> = Vec::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 2 {
continue;
}
let pointer: u32 = match parts[0].parse() {
Ok(v) => v,
Err(_) => continue,
};
let codepoint_str = parts[1].trim();
let codepoint = if codepoint_str.starts_with("0x") || codepoint_str.starts_with("0X") {
match u32::from_str_radix(&codepoint_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
ranges.push((pointer, codepoint));
}
writeln!(
output,
"/// GB18030 4-byte range table: (pointer, codepoint)"
)
.unwrap();
writeln!(
output,
"/// Between consecutive entries, codepoints are sequential."
)
.unwrap();
writeln!(
output,
"pub(crate) static GB18030_RANGES: &[(u32, u32)] = &["
)
.unwrap();
for (pointer, codepoint) in &ranges {
writeln!(output, " ({}, 0x{:04X}),", pointer, codepoint).unwrap();
}
writeln!(output, "];").unwrap();
}
// ============================================================================
// JIS tables for EUC-JP, ISO-2022-JP, and Shift_JIS
// ============================================================================
#[cfg(any(feature = "euc-jp", feature = "iso-2022-jp", feature = "shift-jis"))]
fn build_jis0208_tables() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let dest = std::path::Path::new(&out_dir).join("jis0208_tables.rs");
let mut output = String::new();
output.push_str("// Generated by build.rs - do not edit manually\n");
output.push_str("// JIS X 0208 encoding tables\n\n");
// JIS X 0208 - used by both EUC-JP and ISO-2022-JP
let jis0208_path = Path::new("data/index-jis0208.txt");
if jis0208_path.exists() {
generate_jis0208_tables(jis0208_path, &mut output);
} else {
output.push_str("// WARNING: index-jis0208.txt not found\n");
output.push_str("pub(crate) static JIS0208_DECODE: &[(u16, char)] = &[];\n");
output.push_str("pub(crate) static JIS0208_ENCODE: &[(char, u16)] = &[];\n\n");
}
std::fs::write(&dest, output).unwrap();
println!("cargo:rerun-if-changed=data/index-jis0208.txt");
}
#[cfg(feature = "euc-jp")]
fn build_jis0212_tables() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let dest = std::path::Path::new(&out_dir).join("jis0212_tables.rs");
let mut output = String::new();
output.push_str("// Generated by build.rs - do not edit manually\n");
output.push_str("// JIS X 0212 encoding tables\n\n");
// JIS X 0212 - only used by EUC-JP (3-byte sequences)
let jis0212_path = Path::new("data/index-jis0212.txt");
if jis0212_path.exists() {
generate_jis0212_table(jis0212_path, &mut output);
} else {
output.push_str("// WARNING: index-jis0212.txt not found\n");
output.push_str("pub(crate) static JIS0212_DECODE: &[(u16, char)] = &[];\n");
}
std::fs::write(&dest, output).unwrap();
println!("cargo:rerun-if-changed=data/index-jis0212.txt");
}
#[cfg(any(feature = "euc-jp", feature = "iso-2022-jp", feature = "shift-jis"))]
fn generate_jis0208_tables(path: &Path, output: &mut String) {
let content = std::fs::read_to_string(path).unwrap();
let mut decode: BTreeMap<u16, char> = BTreeMap::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
// Format: pointer\t0xCodepoint\tCharacter (Name)
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() < 2 {
continue;
}
let pointer: u16 = match parts[0].trim().parse() {
Ok(v) => v,
Err(_) => continue,
};
let cp_str = parts[1].trim();
let codepoint = if cp_str.starts_with("0x") || cp_str.starts_with("0X") {
match u32::from_str_radix(&cp_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
if let Some(c) = char::from_u32(codepoint) {
decode.insert(pointer, c);
}
}
// Generate decode table (sorted by pointer for binary search)
writeln!(output, "/// JIS X 0208 decode table: (pointer, char)").unwrap();
writeln!(
output,
"pub(crate) static JIS0208_DECODE: &[(u16, char)] = &["
)
.unwrap();
for (&pointer, &ch) in &decode {
writeln!(output, " ({}, '\\u{{{:04X}}}'),", pointer, ch as u32).unwrap();
}
writeln!(output, "];\n").unwrap();
// Generate encode table (sorted by char for binary search)
let mut encode: BTreeMap<char, u16> = BTreeMap::new();
for (&pointer, &ch) in &decode {
encode.entry(ch).or_insert(pointer);
}
writeln!(output, "/// JIS X 0208 encode table: (char, pointer)").unwrap();
writeln!(
output,
"pub(crate) static JIS0208_ENCODE: &[(char, u16)] = &["
)
.unwrap();
for (&ch, &pointer) in &encode {
writeln!(output, " ('\\u{{{:04X}}}', {}),", ch as u32, pointer).unwrap();
}
writeln!(output, "];\n").unwrap();
}
#[cfg(feature = "euc-jp")]
fn generate_jis0212_table(path: &Path, output: &mut String) {
let content = std::fs::read_to_string(path).unwrap();
let mut decode: BTreeMap<u16, char> = BTreeMap::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
// Format: pointer\t0xCodepoint\tCharacter (Name)
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() < 2 {
continue;
}
let pointer: u16 = match parts[0].trim().parse() {
Ok(v) => v,
Err(_) => continue,
};
let cp_str = parts[1].trim();
let codepoint = if cp_str.starts_with("0x") || cp_str.starts_with("0X") {
match u32::from_str_radix(&cp_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
if let Some(c) = char::from_u32(codepoint) {
decode.insert(pointer, c);
}
}
// Generate decode table only (JIS X 0212 is rarely used for encoding)
writeln!(output, "/// JIS X 0212 decode table: (pointer, char)").unwrap();
writeln!(
output,
"pub(crate) static JIS0212_DECODE: &[(u16, char)] = &["
)
.unwrap();
for (&pointer, &ch) in &decode {
writeln!(output, " ({}, '\\u{{{:04X}}}'),", pointer, ch as u32).unwrap();
}
writeln!(output, "];\n").unwrap();
}
// ============================================================================
// EUC-KR tables for Korean
// ============================================================================
#[cfg(feature = "euc-kr")]
fn build_euckr_tables() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let dest = std::path::Path::new(&out_dir).join("euckr_tables.rs");
let mut output = String::new();
output.push_str("// Generated by build.rs - do not edit manually\n");
output.push_str("// EUC-KR encoding tables\n\n");
let index_path = Path::new("data/index-euc-kr.txt");
if index_path.exists() {
generate_euckr_tables(index_path, &mut output);
} else {
output.push_str("// WARNING: index-euc-kr.txt not found\n");
output.push_str("pub(crate) static EUCKR_DECODE: &[(u16, char)] = &[];\n");
output.push_str("pub(crate) static EUCKR_ENCODE: &[(char, u16)] = &[];\n\n");
}
std::fs::write(&dest, output).unwrap();
println!("cargo:rerun-if-changed=data/index-euc-kr.txt");
}
#[cfg(feature = "euc-kr")]
fn generate_euckr_tables(path: &Path, output: &mut String) {
let content = std::fs::read_to_string(path).unwrap();
let mut decode: BTreeMap<u16, char> = BTreeMap::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
// Format: pointer\t0xCodepoint\tCharacter (Name)
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() < 2 {
continue;
}
let pointer: u16 = match parts[0].trim().parse() {
Ok(v) => v,
Err(_) => continue,
};
let cp_str = parts[1].trim();
let codepoint = if cp_str.starts_with("0x") || cp_str.starts_with("0X") {
match u32::from_str_radix(&cp_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
if let Some(c) = char::from_u32(codepoint) {
decode.insert(pointer, c);
}
}
// Generate decode table (sorted by pointer for binary search)
writeln!(output, "/// EUC-KR decode table: (pointer, char)").unwrap();
writeln!(
output,
"pub(crate) static EUCKR_DECODE: &[(u16, char)] = &["
)
.unwrap();
for (&pointer, &ch) in &decode {
writeln!(output, " ({}, '\\u{{{:04X}}}'),", pointer, ch as u32).unwrap();
}
writeln!(output, "];\n").unwrap();
// Generate encode table (sorted by char for binary search)
let mut encode: BTreeMap<char, u16> = BTreeMap::new();
for (&pointer, &ch) in &decode {
encode.entry(ch).or_insert(pointer);
}
writeln!(output, "/// EUC-KR encode table: (char, pointer)").unwrap();
writeln!(
output,
"pub(crate) static EUCKR_ENCODE: &[(char, u16)] = &["
)
.unwrap();
for (&ch, &pointer) in &encode {
writeln!(output, " ('\\u{{{:04X}}}', {}),", ch as u32, pointer).unwrap();
}
writeln!(output, "];\n").unwrap();
}
// ============================================================================
// Big5 tables for Traditional Chinese
// ============================================================================
#[cfg(feature = "big5")]
fn build_big5_tables() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let dest = std::path::Path::new(&out_dir).join("big5_tables.rs");
let mut output = String::new();
output.push_str("// Generated by build.rs - do not edit manually\n");
output.push_str("// Big5 encoding tables\n\n");
let index_path = Path::new("data/index-big5.txt");
if index_path.exists() {
generate_big5_tables(index_path, &mut output);
} else {
output.push_str("// WARNING: index-big5.txt not found\n");
output.push_str("pub(crate) static BIG5_DECODE: &[(u16, char)] = &[];\n");
output.push_str("pub(crate) static BIG5_ENCODE: &[(char, u16)] = &[];\n\n");
}
std::fs::write(&dest, output).unwrap();
println!("cargo:rerun-if-changed=data/index-big5.txt");
}
#[cfg(feature = "big5")]
fn generate_big5_tables(path: &Path, output: &mut String) {
let content = std::fs::read_to_string(path).unwrap();
let mut decode: BTreeMap<u16, char> = BTreeMap::new();
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
// Format: pointer\t0xCodepoint\tCharacter (Name)
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() < 2 {
continue;
}
let pointer: u16 = match parts[0].trim().parse() {
Ok(v) => v,
Err(_) => continue,
};
let cp_str = parts[1].trim();
let codepoint = if cp_str.starts_with("0x") || cp_str.starts_with("0X") {
match u32::from_str_radix(&cp_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
if let Some(c) = char::from_u32(codepoint) {
decode.insert(pointer, c);
}
}
// Generate decode table (sorted by pointer for binary search)
writeln!(output, "/// Big5 decode table: (pointer, char)").unwrap();
writeln!(output, "pub(crate) static BIG5_DECODE: &[(u16, char)] = &[").unwrap();
for (&pointer, &ch) in &decode {
writeln!(output, " ({}, '\\u{{{:04X}}}'),", pointer, ch as u32).unwrap();
}
writeln!(output, "];\n").unwrap();
// Generate encode table (sorted by char for binary search)
let mut encode: BTreeMap<char, u16> = BTreeMap::new();
for (&pointer, &ch) in &decode {
encode.entry(ch).or_insert(pointer);
}
writeln!(output, "/// Big5 encode table: (char, pointer)").unwrap();
writeln!(output, "pub(crate) static BIG5_ENCODE: &[(char, u16)] = &[").unwrap();
for (&ch, &pointer) in &encode {
writeln!(output, " ('\\u{{{:04X}}}', {}),", ch as u32, pointer).unwrap();
}
writeln!(output, "];\n").unwrap();
}
#[cfg(any(
feature = "codepages-iso8859",
feature = "codepages-windows",
feature = "codepages-dos",
feature = "codepages-apple",
feature = "codepages-misc",
))]
fn build_codepages() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let dest = Path::new(&out_dir).join("codepages.rs");
let mappings_dir = Path::new("data/mappings");
if !mappings_dir.exists() {
std::fs::write(&dest, "// No codepage mappings found\n").unwrap();
return;
}
let mut output = String::new();
output.push_str("// Generated by build.rs - do not edit manually\n\n");
output.push_str("use crate::encoding::Encoding;\n");
output.push_str("use crate::error::EncodingError;\n\n");
let mut codepage_names = Vec::new();
let mut generated_names = std::collections::HashSet::new();
// Scan only the subdirectories for enabled features
#[cfg(feature = "codepages-iso8859")]
scan_directory(
&mappings_dir.join("iso8859"),
"iso8859",
&mut output,
&mut codepage_names,
&mut generated_names,
);
#[cfg(feature = "codepages-windows")]
scan_directory(
&mappings_dir.join("windows"),
"windows",
&mut output,
&mut codepage_names,
&mut generated_names,
);
#[cfg(feature = "codepages-dos")]
scan_directory(
&mappings_dir.join("dos"),
"dos",
&mut output,
&mut codepage_names,
&mut generated_names,
);
#[cfg(feature = "codepages-apple")]
scan_directory(
&mappings_dir.join("apple"),
"apple",
&mut output,
&mut codepage_names,
&mut generated_names,
);
#[cfg(feature = "codepages-misc")]
scan_directory(
&mappings_dir.join("misc"),
"misc",
&mut output,
&mut codepage_names,
&mut generated_names,
);
// Generate re-exports comment
codepage_names.sort();
if !codepage_names.is_empty() {
output.push_str("// Available codepages:\n");
for name in &codepage_names {
writeln!(output, "// - {}", name).unwrap();
}
}
std::fs::write(&dest, output).unwrap();
println!("cargo:rerun-if-changed=data/mappings/");
}
#[cfg(any(
feature = "codepages-iso8859",
feature = "codepages-windows",
feature = "codepages-dos",
feature = "codepages-apple",
feature = "codepages-misc",
))]
fn scan_directory(
dir: &Path,
category: &str,
output: &mut String,
codepage_names: &mut Vec<String>,
generated_names: &mut std::collections::HashSet<String>,
) {
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
};
for entry in entries {
let entry = match entry {
Ok(e) => e,
Err(_) => continue,
};
let path = entry.path();
if path.is_dir() {
scan_directory(&path, category, output, codepage_names, generated_names);
} else if path
.extension()
.map(|e| e == "txt" || e == "TXT")
.unwrap_or(false)
{
if let Some(codepage) = parse_and_generate(&path, category, output, generated_names) {
codepage_names.push(codepage);
}
}
}
}
#[cfg(any(
feature = "codepages-iso8859",
feature = "codepages-windows",
feature = "codepages-dos",
feature = "codepages-apple",
feature = "codepages-misc",
))]
fn parse_and_generate(
path: &Path,
category: &str,
output: &mut String,
generated_names: &mut std::collections::HashSet<String>,
) -> Option<String> {
let content = std::fs::read_to_string(path).ok()?;
let filename = path.file_stem()?.to_str()?;
// Skip readme files
if filename.to_lowercase() == "readme" {
return None;
}
// Check for duplicates before doing anything
let struct_name = derive_struct_name(filename);
if generated_names.contains(&struct_name) {
// Skip duplicate codepage (e.g., CP874 exists in both DOS and Windows)
return None;
}
// Parse the mapping file
// Format: 0xNN\t0xNNNN or 0xNNNN\t0xNNNN (for multi-byte)
let mut single_byte_mappings: BTreeMap<u8, char> = BTreeMap::new();
let mut multi_byte_mappings: BTreeMap<u32, char> = BTreeMap::new();
let mut is_multi_byte = false;
let mut max_bytes = 1usize;
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line
.split(|c| c == '\t' || c == ' ')
.filter(|s| !s.is_empty())
.collect();
if parts.len() < 2 {
continue;
}
// Parse byte value(s)
let byte_str = parts[0].trim();
let byte_val = if byte_str.starts_with("0x") || byte_str.starts_with("0X") {
match u32::from_str_radix(&byte_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
// Parse unicode codepoint
let cp_str = parts[1].trim();
if cp_str.is_empty() || cp_str.starts_with('#') {
continue;
}
let codepoint = if cp_str.starts_with("0x") || cp_str.starts_with("0X") {
match u32::from_str_radix(&cp_str[2..], 16) {
Ok(v) => v,
Err(_) => continue,
}
} else {
continue;
};
let c = match char::from_u32(codepoint) {
Some(c) => c,
None => continue,
};
if byte_val > 0xFF {
is_multi_byte = true;
let num_bytes = if byte_val > 0xFFFFFF {
4
} else if byte_val > 0xFFFF {
3
} else if byte_val > 0xFF {
2
} else {
1
};
max_bytes = max_bytes.max(num_bytes);
multi_byte_mappings.insert(byte_val, c);
} else {
single_byte_mappings.insert(byte_val as u8, c);
}
}
// If we have multi-byte mappings, merge single-byte into multi-byte
if is_multi_byte {
for (&b, &c) in &single_byte_mappings {
multi_byte_mappings.insert(b as u32, c);
}
}
if single_byte_mappings.is_empty() && multi_byte_mappings.is_empty() {
return None;
}
// Mark this name as generated
generated_names.insert(struct_name.clone());
if is_multi_byte {
generate_multi_byte_encoding(
&struct_name,
filename,
category,
&multi_byte_mappings,
max_bytes,
output,
)
} else {
generate_single_byte_encoding(
&struct_name,
filename,
category,
&single_byte_mappings,
output,
)
}
}
#[cfg(any(
feature = "codepages-iso8859",
feature = "codepages-windows",
feature = "codepages-dos",
feature = "codepages-apple",
feature = "codepages-misc",
))]
fn generate_single_byte_encoding(
struct_name: &str,
filename: &str,
category: &str,
mappings: &BTreeMap<u8, char>,
output: &mut String,
) -> Option<String> {
let const_prefix = struct_name.to_uppercase();
// Build decode table
let mut decode_table = ['\u{FFFD}'; 256];
for (&byte, &ch) in mappings {
decode_table[byte as usize] = ch;
}
let has_undefined = decode_table.iter().any(|&c| c == '\u{FFFD}');
// Generate struct
writeln!(output, "/// {} encoding.", struct_name).unwrap();
writeln!(
output,
"#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]"
)
.unwrap();
writeln!(output, "pub struct {};", struct_name).unwrap();
writeln!(output).unwrap();
// Generate decode table
writeln!(output, "static {}_DECODE: [char; 256] = [", const_prefix).unwrap();
for (i, chunk) in decode_table.chunks(8).enumerate() {
write!(output, " ").unwrap();
for (j, &c) in chunk.iter().enumerate() {
if j > 0 {
write!(output, " ").unwrap();
}
write!(output, "'\\u{{{:04X}}}',", c as u32).unwrap();
}
writeln!(output, " // 0x{:02X}-0x{:02X}", i * 8, i * 8 + 7).unwrap();
}
writeln!(output, "];").unwrap();
writeln!(output).unwrap();
// Generate encode helper
let ascii_identity = (0u8..128).all(|b| mappings.get(&b).copied() == Some(b as char));
writeln!(output, "impl {} {{", struct_name).unwrap();
writeln!(output, " fn try_encode_byte(c: char) -> Option<u8> {{").unwrap();
// Build reverse mapping (char -> byte), keeping first occurrence only
let mut char_to_byte: BTreeMap<char, u8> = BTreeMap::new();
for (&byte, &ch) in mappings {
char_to_byte.entry(ch).or_insert(byte);
}
if ascii_identity {
writeln!(output, " let cp = c as u32;").unwrap();
writeln!(output, " if cp < 128 {{").unwrap();