dayzmake-core 0.3.1

Readers and writers for DayZ file formats: PBO, rapified config, P3D, PAA, BI keys and signatures, and navmesh generation
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
//! Functions for rapifying and derapifying Arma configs

use std::cmp::min;
use std::collections::HashSet;
use std::io::{BufReader, BufWriter, Cursor, Error, Read, Seek, SeekFrom, Write};
use std::iter::Sum;
use std::path::PathBuf;

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};

use crate::error;
use crate::error::{ConfigParseErrorExt, ErrorExt, located_error, printable};
use crate::eval::{EvalValue, eval, exec};
use crate::io::{ReadExt, WriteExt, compressed_int_len};
use crate::preprocess::{IncludeFolders, MAX_NESTING_DEPTH, nesting_error, preprocess_in};
use crate::warning::{Warning, WarningSink};

/// Refuses a name with a control character: the config grammar has no way to write one, and it
/// would reach the terminal raw.
fn text_name(name: &str, what: &str) -> Result<(), Error> {
    if name.chars().any(char::is_control) {
        return Err(error!(
            "{what} name \"{}\" cannot be written as config text.",
            printable(name)
        ));
    }
    Ok(())
}

/// State shared with the grammar for `__EVAL` / `__EXEC`.
#[derive(Default)]
pub(crate) struct EvalCtx {
    vars: std::collections::HashMap<String, EvalValue>,
    /// The first error raised from a grammar action, with the byte offset of the token it belongs to.
    error: Option<(usize, Error)>,
}

impl From<EvalValue> for ConfigEntry {
    fn from(v: EvalValue) -> ConfigEntry {
        match v {
            EvalValue::Str(s) => ConfigEntry::StringEntry(s),
            EvalValue::Number(n)
                if matches!(n.fract().classify(), std::num::FpCategory::Zero)
                    && n.abs() < 2_147_483_648.0 =>
            {
                // the guard above ensures the value fits an i32 without truncation
                #[expect(
                    clippy::cast_possible_truncation,
                    reason = "guarded by fract() == 0 and abs() < 2^31"
                )]
                {
                    ConfigEntry::IntEntry(n as i32)
                }
            }
            EvalValue::Number(n) => ConfigEntry::FloatEntry(n),
        }
    }
}

impl From<EvalValue> for ConfigArrayElement {
    fn from(v: EvalValue) -> ConfigArrayElement {
        match v {
            EvalValue::Str(s) => ConfigArrayElement::StringElement(s),
            EvalValue::Number(n)
                if matches!(n.fract().classify(), std::num::FpCategory::Zero)
                    && n.abs() < 2_147_483_648.0 =>
            {
                // the guard above ensures the value fits an i32 without truncation
                #[expect(
                    clippy::cast_possible_truncation,
                    reason = "guarded by fract() == 0 and abs() < 2^31"
                )]
                {
                    ConfigArrayElement::IntElement(n as i32)
                }
            }
            EvalValue::Number(n) => ConfigArrayElement::FloatElement(n),
        }
    }
}

/// Warnings raised while parsing a config, with the byte offset they occurred at.
pub(crate) struct ConfigWarnings(pub(crate) Vec<(usize, String, Option<&'static str>)>);

impl ConfigWarnings {
    fn push(&mut self, warning: (usize, String, Option<&'static str>)) {
        self.0.push(warning);
    }
}

peg::parser! {
    /// PEG grammar for rapified config syntax.
    pub(crate) grammar config_grammar(warnings: &mut ConfigWarnings, ctx: &mut EvalCtx) for str {
        rule whitespace() = quiet!{ [' ' | '\r' | '\n' | '\t']+ }

        rule exponent() = ['e' | 'E'] ['-' | '+']? ['0'..='9']+

        rule float_text() -> (usize, &'input str) = p:position!() t:$((['-' | '+'])? ((['0'..='9']* "." ['0'..='9']+ exponent()?) / (['0'..='9']+ exponent()))) { (p, t) }

        /// The end of an entry: `;`, the `}` of the class, or (for the last entry of a block or file,
        /// as CfgConvert reads it) the end of the line.
        rule entry_end() = whitespace()? [';' | '}'] / [' ' | '\t']* ['\r' | '\n']

        /// A float followed by the end of an entry.
        rule float_entry() -> f32 = f:float_text() &entry_end() v:float_value(f) { v }

        /// A float followed by the end of an array element.
        rule float_element() -> f32 = f:float_text() &(whitespace()? [',' | '}']) v:float_value(f) { v }

        /// An overflowing literal (`1e999`) is an infinity, as `CfgConvert` writes it; derapify writes
        /// `1e999` / `-1e999` for it, which reads back to the same value.
        rule float_value(at: (usize, &str)) -> f32 = {?
            let (pos, f) = at;
            // `float_text` only matches what `f32::from_str` accepts, and overflow is an infinity, so the
            // error cannot fire; it stays as a guard against a grammar change.
            f.parse::<f32>()
                .map_err(|e| { ctx.error.get_or_insert((pos, error!("Invalid float \"{f}\": {e}"))); "a valid float" })
        }

        /// The literal of an enum value: a sign, decimal digits or `0x` / `0X` hex of any length.
        rule integer_text() -> &'input str = $((['-' | '+'])? (("0" ['x' | 'X'] ['0'..='9' | 'a'..='f' | 'A'..='F']+) / ['0'..='9']+))

        /// A literal `CfgConvert` stores as an integer: unsigned hex (any length, `0x` or `0X`) or a decimal.
        rule int_literal() -> (usize, &'input str) = p:position!() t:$(("0" ['x' | 'X'] ['0'..='9' | 'a'..='f' | 'A'..='F']+) / ((['-' | '+'])? ['0'..='9']+)) { (p, t) }

        /// A signed hex literal (`-0x10`), which `CfgConvert` stores as a float.
        rule signed_hex_text() -> &'input str = $(['-' | '+'] "0" ['x' | 'X'] ['0'..='9' | 'a'..='f' | 'A'..='F']+)

        /// An integer followed by the end of an entry; the terminator is checked first, like for floats
        /// (`99999999999x` stays an unquoted string).
        rule integer_entry() -> i32 = i:int_literal() &entry_end() v:int_value(i) { v }

        /// An integer followed by the end of an array element.
        rule integer_element() -> i32 = i:int_literal() &(whitespace()? [',' | '}']) v:int_value(i) { v }

        /// A signed hex literal followed by the end of an entry.
        rule signed_hex_entry() -> f32 = t:signed_hex_text() &entry_end() { signed_hex_float(t) }

        /// A signed hex literal followed by the end of an array element.
        rule signed_hex_element() -> f32 = t:signed_hex_text() &(whitespace()? [',' | '}']) { signed_hex_float(t) }

        /// A decimal literal that does not fit `i64`, which `CfgConvert` stores as a float (`1e20`); one that
        /// fits is left to `int64_entry` and `integer_entry`.
        rule huge_integer_text() -> (usize, &'input str) = quiet!{ p:position!() t:$((['-' | '+'])? ['0'..='9']+) {?
            if t.parse::<i64>().is_err() { Ok((p, t)) } else { Err("an integer that fits 64 bits") }
        } }

        /// A decimal literal that fits `i64` but not `i32`, which `CfgConvert` stores as a 64-bit integer in an entry.
        rule int64_text() -> i64 = quiet!{ t:$((['-' | '+'])? ['0'..='9']+) {?
            match (t.parse::<i64>(), t.parse::<i32>()) {
                (Ok(v), Err(_)) => Ok(v),
                _ => Err("an integer between 32 and 64 bits"),
            }
        } }

        /// A decimal literal that does not fit `i32`, in an array, where `CfgConvert` stores it as a float.
        rule wide_integer_text() -> (usize, &'input str) = quiet!{ p:position!() t:$((['-' | '+'])? ['0'..='9']+) {?
            if t.parse::<i32>().is_err() { Ok((p, t)) } else { Err("an integer that fits 32 bits") }
        } }

        rule huge_integer_entry() -> f32 = i:huge_integer_text() &entry_end() v:float_value(i) { v }

        rule int64_entry() -> i64 = i:int64_text() &entry_end() { i }

        rule wide_integer_element() -> f32 = i:wide_integer_text() &(whitespace()? [',' | '}']) v:float_value(i) { v }

        /// An integer literal of an entry or array element: hex keeps its low 32 bits, as in `CfgConvert`.
        /// A decimal one is always an `i32` here: wider ones are taken first by `huge_integer_entry` and
        /// `int64_entry` (entries) or `wide_integer_element` (arrays).
        rule int_value(at: (usize, &str)) -> i32 = {?
            let (pos, i) = at;
            match hex_digits(i) {
                Some(digits) => Ok(hex_wrapped(digits)),
                // the error cannot fire (see above); it stays as a guard against a grammar change
                None => i.parse::<i32>()
                    .map_err(|e| { ctx.error.get_or_insert((pos, error!("Invalid integer \"{i}\": {e}"))); "a valid integer" }),
            }
        }

        /// The value of an enum literal, as `CfgConvert` computes it: an `f32` (see `enum_literal_value`).
        rule enum_number() -> f32 = t:integer_text() { enum_literal_value(t) }

        rule doublequoted_string() -> String = "\"" s:$(("\"\"" / !['"'] [_])*) "\"" {
            s.to_string().replace("\"\"", "\"")
        }

        rule singlequoted_string() -> String = "'" s:$(("''" / !['\''] [_])*) "'" {
            s.to_string().replace("''", "'")
        }

        rule unquoted_string() -> String = pos:position!() s:$((![';' | '}' | '\r' | '\n'] [_])*) {
            let result = s.to_string().trim().to_string();
            // an empty value comes from a macro that expanded to nothing (e.g. an argument-count
            // mismatch, which has its own warning); CfgConvert makes it "" as well.
            // `unquoted_string_entry` raises `empty-value` for it
            if !result.is_empty() {
                warnings.push((pos, format!("String value \"{}\" is not quoted properly.", printable(&result)), Some("unquoted-string")));
            }
            result
        }

        rule unquoted_string_array() -> String = pos:position!() s:$( (![',' | '}' | ' ' | '\t' | '\r' | '\n'] [_]) (![',' | '}' | '\r' | '\n'] [_])* ) {
            let result = s.to_string().trim().to_string();
            warnings.push((pos, format!("String array element \"{}\" is not quoted properly.", printable(&result)), Some("unquoted-string")));
            result
        }

        /// Fails (and records the error) when `d` levels of classes, arrays or parentheses are exceeded.
        rule nesting_ok(d: usize) = pos:position!() {?
            if d >= MAX_NESTING_DEPTH {
                ctx.error.get_or_insert((pos, nesting_error()));
                Err("nesting within the limit")
            } else {
                Ok(())
            }
        }

        rule eval_body(d: usize) = ("(" nesting_ok(d) eval_body(d + 1) ")" / "\"" (!"\"" [_])* "\"" / !['(' | ')'] [_])*

        rule eval_value(d: usize) -> EvalValue = pos:position!() "__EVAL" whitespace()? "(" b:$(eval_body(d)) ")" {?
            match eval(b, &mut ctx.vars) {
                Ok(v) => Ok(v),
                Err(e) => { ctx.error.get_or_insert((pos, e)); Err("a supported __EVAL expression") }
            }
        }

        rule exec_entry(d: usize) = pos:position!() "__EXEC" whitespace()? "(" b:$(eval_body(d)) ")" whitespace()? ";" {?
            match exec(b, &mut ctx.vars) {
                Ok(()) => Ok(()),
                Err(e) => { ctx.error.get_or_insert((pos, e)); Err("a supported __EXEC statement") }
            }
        }

        rule string() -> String = doublequoted_string() / singlequoted_string()

        /// An element that is not an array. Kept out of `array_element`, whose frame is on the recursive
        /// path of nested arrays and must stay small (see `plain_entry`).
        rule scalar_element(d: usize) -> ConfigArrayElement =
            f:float_element() { ConfigArrayElement::FloatElement(f) } /
            f:wide_integer_element() { ConfigArrayElement::FloatElement(f) } /
            f:signed_hex_element() { ConfigArrayElement::FloatElement(f) } /
            i:integer_element() { ConfigArrayElement::IntElement(i) } /
            s:string()  &(whitespace()? [',' | '}']) { ConfigArrayElement::StringElement(s) } /
            v:eval_value(d) &(whitespace()? [',' | '}']) { v.into() } /
            s:unquoted_string_array() &(whitespace()? [',' | '}']) { ConfigArrayElement::StringElement(s) }

        /// An array is tried first: the other elements cannot start with `{` except an unquoted string,
        /// which comes last.
        rule array_element(d: usize) -> ConfigArrayElement =
            a:array(d)   &(whitespace()? [',' | '}']) { ConfigArrayElement::ArrayElement(a) } /
            scalar_element(d)

        rule array_elements(d: usize) -> Vec<ConfigArrayElement> = array_element(d) ** (whitespace()? "," whitespace()?)

        rule array(d: usize) -> ConfigArray = "{" nesting_ok(d) whitespace()? elems:array_elements(d + 1) whitespace()? ","? whitespace()? "}" {
            ConfigArray {
                is_expansion: false,
                elements: elems
            }
        }

        rule var(d: usize) -> ConfigEntry =
            f:float_entry() { ConfigEntry::FloatEntry(f) } /
            f:signed_hex_entry() { ConfigEntry::FloatEntry(f) } /
            f:huge_integer_entry() { ConfigEntry::FloatEntry(f) } /
            i:int64_entry() { ConfigEntry::Int64Entry(i) } /
            i:integer_entry() { ConfigEntry::IntEntry(i) } /
            s:string()  { ConfigEntry::StringEntry(s) } /
            v:eval_value(d) { v.into() }

        rule var_entry(d: usize) -> (String, ConfigEntry) = n:name() whitespace()? "=" whitespace()? ce:var(d) {
            (n, ce)
        }

        rule unquoted_string_entry() -> (String, ConfigEntry) = pos:position!() n:name() whitespace()? "=" whitespace()? s:unquoted_string() {
            if s.is_empty() {
                // `x = ;`, or a macro that expanded to nothing; kept as "" so existing mods still build
                warnings.push((pos, format!("Entry \"{}\" has no value; it is stored as an empty string.", printable(&n)), Some("empty-value")));
            }
            (n, ConfigEntry::StringEntry(s))
        }

        rule array_entry(d: usize) -> (String, ConfigEntry) = n:name() whitespace()? "[" whitespace()? "]" whitespace()? "=" whitespace()? a:array(d) {
            (n, ConfigEntry::ArrayEntry(a))
        }

        rule array_expansion_entry(d: usize) -> (String, ConfigEntry) = n:name() whitespace()? "[" whitespace()? "]" whitespace()? "+=" whitespace()? a:array(d) {
            (n, ConfigEntry::ArrayEntry(ConfigArray {
                is_expansion: true,
                ..a
            }))
        }

        rule enum_value() -> (String, Option<f32>) = n:name() v:(whitespace()? "=" whitespace()? i:enum_number() { i })? { (n, v) }

        /// `enum { name [= int], ... }`: values count up from the last explicit one, names are stored lowercase. The
        /// values are computed in `f32` like `CfgConvert` does (`enum_literal_value`, `enum_f32_to_i32`).
        rule enum_block() -> Vec<(String, i32)> = quiet!{"enum"} whitespace()? "{" whitespace()? v:(enum_value() ** (whitespace()? "," whitespace()?)) whitespace()? ","? whitespace()? "}" {?
            let mut base = 0.0_f32;
            // the first implicit value is 0, so the distance starts one below
            let mut distance = -1.0_f32;
            let mut out = Vec::new();
            for (n, v) in v {
                match v {
                    Some(explicit) => { base = enum_i32_to_f32(enum_f32_to_i32(explicit)); distance = 0.0; }
                    None => distance += 1.0,
                }
                out.push((n.to_ascii_lowercase(), enum_f32_to_i32(base + distance)));
            }
            Ok(out)
        }

        rule array_item(d: usize) -> Item =
            e:(array_entry(d) / array_expansion_entry(d)) whitespace()? (";" / &"}") { Item::Entry(e.0, e.1, Vec::new()) }

        /// A value entry; the last one of a block or file may end at the line end instead of `;`.
        rule var_item(d: usize) -> Item =
            e:var_entry(d) (whitespace()? (";" / &"}") / [' ' | '\t']* &['\r' | '\n']) { Item::Entry(e.0, e.1, Vec::new()) }

        /// The entries that are not classes. Kept out of `entry_or_exec`, whose frame is on the recursive path
        /// (class, entries, entry_or_exec, class) and must stay small: a debug build gives every alternative of a
        /// rule its own stack slots, and a 1 MiB stack (Windows) has to hold the deepest nesting (#108).
        rule plain_entry(d: usize) -> Item =
            e:enum_block() whitespace()? (";" / &"}") { Item::Enums(e) } /
            e:(array_item(d) / var_item(d)) { e } /
            e:unquoted_string_entry() (";" / &"}" / &['\r' | '\n']) { Item::Entry(e.0, e.1, Vec::new()) }

        /// A class is tried first, directly in `entry_or_exec`: `class` and `delete` cannot start an `enum`
        /// block or `__EXEC`, so the order of the alternatives does not matter.
        rule entry_or_exec(d: usize) -> Box<Item> =
            e:class(d) whitespace()? (";" / &"}") { e } /
            exec_entry(d) { Box::new(Item::Nothing) } /
            e:plain_entry(d) { Box::new(e) }

        rule entries(d: usize) -> (Vec<(String, ConfigEntry)>, Vec<(String, i32)>) = v:(entry_or_exec(d) ** (whitespace()?)) {
            let mut entries = Vec::new();
            let mut enums = Vec::new();
            for item in v {
                match *item {
                    Item::Entry(n, e, en) => { entries.push((n, e)); enums.extend(en); }
                    Item::Enums(en) => enums.extend(en),
                    Item::Nothing => {}
                }
            }
            (entries, enums)
        }

        rule name() -> String = n:$(['a'..='z' | 'A'..='Z' | '0'..='9' | '_']+) {
            n.to_string()
        }

        rule parent() -> String = whitespace()? ":" whitespace()? n:name() {
            n
        }

        rule regular_class(d: usize) -> Box<Item> = "class" whitespace()+ n:name() p:parent()? whitespace()? "{" nesting_ok(d) whitespace()? e:entries(d + 1) whitespace()? "}" {
            let parent = p.unwrap_or_default();
            Box::new(Item::Entry(n, ConfigEntry::ClassEntry(ConfigClass {
                parent,
                is_external: false,
                is_deletion: false,
                entries: Some(e.0)
            }), e.1))
        }

        rule external_class() -> Box<Item> = "class" whitespace()+ n:name() {
            Box::new(Item::Entry(n, ConfigEntry::ClassEntry(ConfigClass {
                parent: String::new(),
                is_external: true,
                is_deletion: false,
                entries: None
            }), Vec::new()))
        }

        rule deleted_class() -> Box<Item> = "delete" whitespace()+ n:name() {
            Box::new(Item::Entry(n, ConfigEntry::ClassEntry(ConfigClass {
                parent: String::new(),
                is_external: false,
                is_deletion: true,
                entries: None
            }), Vec::new()))
        }

        rule class(d: usize) -> Box<Item> = regular_class(d) / external_class() / deleted_class()

        /// Parses a complete config: a sequence of entries until end of input.
        pub rule config() -> Config = whitespace()? e:entries(0) whitespace()? ![_] {
            Config {
                root_body: ConfigClass {
                    parent: String::new(),
                    is_external: false,
                    is_deletion: false,
                    entries: Some(e.0)
                },
                enums: e.1,
            }
        }
    }
}

/// The hex digits of an unsigned `0x` / `0X` literal.
fn hex_digits(text: &str) -> Option<&str> {
    text.strip_prefix("0x").or_else(|| text.strip_prefix("0X"))
}

/// The low 32 bits of a hex literal of any length, as `CfgConvert` stores it (`0x1FFFFFFFFF` is `-1`).
fn hex_wrapped(digits: &str) -> i32 {
    let bits = digits
        .chars()
        .filter_map(|c| c.to_digit(16))
        .fold(0_u32, |acc, d| {
            // 4 bits per digit: the high bits fall off, which is the wrap-around wanted here
            acc.wrapping_shl(4) | d
        });
    bits.cast_signed()
}

/// The `f32` an enum literal stands for in `CfgConvert`: unsigned hex keeps its low 32 bits, a signed hex
/// literal is a float, a decimal is rounded to `f32` (`16777217` is `16777216`).
#[expect(
    clippy::cast_precision_loss,
    reason = "the rounding of an i32 to f32 is what CfgConvert does"
)]
fn enum_literal_value(text: &str) -> f32 {
    let unsigned = text.strip_prefix(['-', '+']).unwrap_or(text);
    match (hex_digits(unsigned), unsigned.len() < text.len()) {
        (Some(digits), false) => hex_wrapped(digits) as f32,
        (Some(_), true) => signed_hex_float(text),
        // the grammar only passes digits, so this parses; NaN converts to i32::MIN if it ever did not
        (None, _) => text.parse::<f32>().unwrap_or(f32::NAN),
    }
}

#[expect(
    clippy::cast_precision_loss,
    reason = "an i32 that came from an f32 is exact; the cast is only the type change back"
)]
fn enum_i32_to_f32(value: i32) -> f32 {
    value as f32
}

/// An enum value from its `f32`, as `CfgConvert` converts it: a value outside `i32` (and NaN) is `i32::MIN`.
#[expect(
    clippy::cast_possible_truncation,
    reason = "the value is in the i32 range, checked right here"
)]
fn enum_f32_to_i32(value: f32) -> i32 {
    if (-2_147_483_648.0..2_147_483_648.0).contains(&value) {
        value as i32
    } else {
        i32::MIN
    }
}

/// The value of a signed hex literal (`-0x10`), which `CfgConvert` stores as a float. The magnitude is rounded
/// to an f64 digit by digit and then to an f32, the double rounding `CfgConvert` shows: `-0x8000008000000001`,
/// `-0x1000001000000001` and `-0x10000010000000001` give `0xDF000000`, `0xDD800000` and `0xDF800000` there
/// (golden `hex_round*`, 2026-11-17), not the singly rounded `0xDF000001` and so on.
#[expect(
    clippy::cast_possible_truncation,
    reason = "the f64 magnitude is rounded to the nearest f32, overflow is an infinity"
)]
fn signed_hex_float(text: &str) -> f32 {
    let (negative, rest) = match text.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, text.strip_prefix('+').unwrap_or(text)),
    };
    let magnitude = hex_digits(rest)
        .unwrap_or_default()
        .chars()
        .filter_map(|c| c.to_digit(16))
        .fold(0.0_f64, |acc, d| acc * 16.0 + f64::from(d));
    let value = magnitude as f32;
    if negative { -value } else { value }
}

/// The text of a float as derapify writes it. An infinity becomes `1e999` / `-1e999`, a literal that
/// overflows to the same f32 when read back. NaN has no such form and stays `NaN` (a string when read).
fn float_literal(f: f32) -> String {
    if f.is_infinite() {
        if f.is_sign_positive() {
            "1e999"
        } else {
            "-1e999"
        }
        .to_string()
    } else {
        format!("{f:?}")
    }
}

/// Reads the enum table at the header's `enum_offset`. The class tree is usable without it, so a bad
/// offset, a cut-short table or a name that is not a config identifier gives the values read before
/// it, never an error.
fn read_enum_table<I: Read + Seek>(input: &mut I) -> Vec<(String, i32)> {
    let mut out = Vec::new();
    // an unreadable table is not an error: the values read so far are returned
    let _ = (|| -> std::io::Result<()> {
        input.seek(SeekFrom::Start(12))?;
        let offset = input.read_u32::<LittleEndian>()?;
        input.seek(SeekFrom::Start(offset.into()))?;
        let count = input.read_u32::<LittleEndian>()?;
        // no preallocation from the count: the loop ends at the first read error
        for _ in 0..count {
            let name = input.read_cstring()?;
            let value = input.read_i32::<LittleEndian>()?;
            // the table ends at the first name the config grammar cannot write
            if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
                break;
            }
            out.push((name, value));
        }
        Ok(())
    })();
    out
}

/// Returns true if `data` starts with the rapified config signature.
#[must_use]
pub fn is_rapified(data: &[u8]) -> bool {
    data.starts_with(b"\0raP")
}

/// `compressed_int_len` for an in-memory length. Config element counts beyond
/// `u32::MAX` are impossible in practice (each element costs far more than a
/// byte of memory), so they clamp to the maximum; the write path reports them
/// as errors instead.
fn compressed_int_len_of(len: usize) -> usize {
    compressed_int_len(u32::try_from(len).unwrap_or(u32::MAX))
}

/// Config
///
/// # Examples
///
/// ```
/// # use dayzmake_core::config::Config;
/// # use dayzmake_core::warning::Warnings;
/// let input = String::from("
/// #define bar 42
///
/// foo = bar;
/// ");
///
/// let config = Config::from_string(input, None, &Vec::new(), &mut Warnings::new()).expect("Failed to parse config");
///
/// assert_eq!("foo = 42;\n", config.to_string().unwrap());
/// assert_eq!(b"\0raP", &config.to_cursor().unwrap().into_inner()[..4]);
/// ```
#[derive(Debug)]
pub struct Config {
    root_body: ConfigClass,
    enums: Vec<(String, i32)>,
}

/// One parsed config item: the grammar returns the enum values of nested blocks upwards.
enum Item {
    Entry(String, ConfigEntry, Vec<(String, i32)>),
    Enums(Vec<(String, i32)>),
    Nothing,
}

/// Config class
#[derive(Debug)]
pub struct ConfigClass {
    parent: String,
    is_external: bool,
    is_deletion: bool,
    entries: Option<Vec<(String, ConfigEntry)>>,
}

/// Config entry
#[derive(Debug)]
#[non_exhaustive]
pub enum ConfigEntry {
    /// String entry
    StringEntry(String),
    /// Float entry
    FloatEntry(f32),
    /// Int entry
    IntEntry(i32),
    /// 64-bit int entry (entry subtype 6): `CfgConvert` writes a decimal literal that fits `i64` but not `i32` this way
    Int64Entry(i64),
    /// Array entry
    ArrayEntry(ConfigArray),
    /// Class entry
    ClassEntry(ConfigClass),
}

/// Config array
#[derive(Debug)]
pub struct ConfigArray {
    is_expansion: bool,
    elements: Vec<ConfigArrayElement>,
}

/// Config array element
#[derive(Debug)]
#[non_exhaustive]
pub enum ConfigArrayElement {
    /// String element
    StringElement(String),
    /// Float element
    FloatElement(f32),
    /// Int element
    IntElement(i32),
    /// Array element
    ArrayElement(ConfigArray),
}

impl ConfigArrayElement {
    fn rapified_length(&self) -> usize {
        match self {
            ConfigArrayElement::StringElement(s) => s.len() + 2,
            ConfigArrayElement::FloatElement(_f) => 5,
            ConfigArrayElement::IntElement(_i) => 5,
            ConfigArrayElement::ArrayElement(a) => {
                1 + compressed_int_len_of(a.elements.len())
                    + usize::sum(a.elements.iter().map(ConfigArrayElement::rapified_length))
            }
        }
    }
}

/// Deepest class or array nesting accepted when reading a rapified config: the root class plus the
/// `MAX_NESTING_DEPTH` levels the text parser accepts, so every config this crate writes reads back.
const MAX_RAPIFIED_DEPTH: u32 = 129;

/// Most entries and array elements accepted in one rapified config.
const MAX_RAPIFIED_ENTRIES: u64 = 4_000_000;

/// Limits that keep reading a crafted rapified config from running away.
struct ReadBudget {
    depth: u32,
    remaining: u64,
    /// Offsets of the class bodies being read, to catch bodies that contain themselves.
    open_bodies: Vec<u32>,
    /// Offsets of every class body read so far. Real configs never share a body between classes; a file
    /// that does can make the output exponentially larger than the input.
    seen_bodies: HashSet<u32>,
}

impl ReadBudget {
    fn new() -> Self {
        ReadBudget {
            depth: 0,
            remaining: MAX_RAPIFIED_ENTRIES,
            open_bodies: Vec::new(),
            seen_bodies: HashSet::new(),
        }
    }

    fn enter(&mut self) -> Result<(), Error> {
        if self.depth >= MAX_RAPIFIED_DEPTH {
            return Err(error!(
                "Rapified config nesting is deeper than {MAX_RAPIFIED_DEPTH} levels."
            ));
        }
        self.depth += 1;
        Ok(())
    }

    fn leave(&mut self) {
        self.depth = self.depth.saturating_sub(1);
    }

    fn take_entry(&mut self) -> Result<(), Error> {
        self.remaining = self
            .remaining
            .checked_sub(1)
            .ok_or_else(|| error!("Rapified config has too many entries."))?;
        Ok(())
    }
}

impl ConfigArray {
    /// The array's elements.
    #[must_use]
    pub fn elements(&self) -> &[ConfigArrayElement] {
        &self.elements
    }

    /// Whether this is an array expansion (`x[] += {...}`).
    #[must_use]
    pub fn is_expansion(&self) -> bool {
        self.is_expansion
    }

    fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        output.write_all(b"{")?;
        for (key, value) in self.elements.iter().enumerate() {
            match value {
                ConfigArrayElement::ArrayElement(a) => {
                    a.write(output)?;
                }
                ConfigArrayElement::StringElement(s) => {
                    output.write_all(
                        format!(
                            "\"{}\"",
                            s.replace('\r', "\\r")
                                .replace('\n', "\\n")
                                .replace('"', "\"\"")
                        )
                        .as_bytes(),
                    )?;
                }
                ConfigArrayElement::FloatElement(f) => {
                    output.write_all(float_literal(*f).as_bytes())?;
                }
                ConfigArrayElement::IntElement(i) => {
                    output.write_all(format!("{i}").as_bytes())?;
                }
            }
            if key < self.elements.len() - 1 {
                output.write_all(b", ")?;
            }
        }
        output.write_all(b"}")?;
        Ok(())
    }

    fn write_rapified<O: Write>(&self, output: &mut O) -> Result<usize, Error> {
        let num_elements = u32::try_from(self.elements.len())
            .map_err(|_| error!("too many array elements: {}", self.elements.len()))?;
        let mut written = output.write_compressed_int(num_elements)?;

        for (index, element) in self.elements.iter().enumerate() {
            match element {
                ConfigArrayElement::StringElement(s) => {
                    output.write_all(&[0])?;
                    output
                        .write_cstring(s)
                        .prepend_error(format!("Array element {index}:"))?;
                    written += s.len() + 2;
                }
                ConfigArrayElement::FloatElement(f) => {
                    output.write_all(&[1])?;
                    output.write_f32::<LittleEndian>(*f)?;
                    written += 5;
                }
                ConfigArrayElement::IntElement(i) => {
                    output.write_all(&[2])?;
                    output.write_i32::<LittleEndian>(*i)?;
                    written += 5;
                }
                ConfigArrayElement::ArrayElement(a) => {
                    output.write_all(&[3])?;
                    written += 1 + a
                        .write_rapified(output)
                        .prepend_error(format!("Array element {index}:"))?;
                }
            }
        }

        Ok(written)
    }

    fn read_rapified<I: Read + Seek>(
        input: &mut I,
        budget: &mut ReadBudget,
    ) -> Result<ConfigArray, Error> {
        budget.enter()?;
        let result = ConfigArray::read_rapified_elements(input, budget);
        budget.leave();
        result
    }

    fn read_rapified_elements<I: Read + Seek>(
        input: &mut I,
        budget: &mut ReadBudget,
    ) -> Result<ConfigArray, Error> {
        let num_elements: u32 = input.read_compressed_int()?;
        // never preallocate the full length from untrusted input
        let mut elements: Vec<ConfigArrayElement> =
            Vec::with_capacity(num_elements.min(65536) as usize);

        for _i in 0..num_elements {
            budget.take_entry()?;
            let mut buf = [0u8; 1];
            input.read_exact(&mut buf)?;
            let element_type = buf[0];

            if element_type == 0 {
                elements.push(ConfigArrayElement::StringElement(input.read_cstring()?));
            } else if element_type == 1 {
                elements.push(ConfigArrayElement::FloatElement(
                    input.read_f32::<LittleEndian>()?,
                ));
            } else if element_type == 2 {
                elements.push(ConfigArrayElement::IntElement(
                    input.read_i32::<LittleEndian>()?,
                ));
            } else if element_type == 3 {
                elements.push(ConfigArrayElement::ArrayElement(
                    ConfigArray::read_rapified(input, budget)?,
                ));
            } else {
                return Err(error!("Unrecognized array element type: {}", element_type));
            }
        }

        Ok(ConfigArray {
            is_expansion: false,
            elements,
        })
    }
}

impl ConfigEntry {
    // without the name
    fn rapified_length(&self) -> usize {
        match self {
            ConfigEntry::StringEntry(s) => s.len() + 3,
            ConfigEntry::FloatEntry(_f) => 6,
            ConfigEntry::IntEntry(_i) => 6,
            ConfigEntry::Int64Entry(_i) => 10,
            ConfigEntry::ArrayEntry(a) => {
                let len = 1
                    + compressed_int_len_of(a.elements.len())
                    + usize::sum(a.elements.iter().map(ConfigArrayElement::rapified_length));
                if a.is_expansion { len + 4 } else { len }
            }
            ConfigEntry::ClassEntry(c) => {
                if c.is_external || c.is_deletion {
                    1
                } else {
                    5
                }
            }
        }
    }
}

impl ConfigClass {
    /// The parent class name, or `None` when the class has no parent.
    #[must_use]
    pub fn parent(&self) -> Option<&str> {
        if self.parent.is_empty() {
            None
        } else {
            Some(&self.parent)
        }
    }

    /// Whether this is an external declaration (`class X;`).
    #[must_use]
    pub fn is_external(&self) -> bool {
        self.is_external
    }

    /// Whether this is a deletion (`delete X;`).
    #[must_use]
    pub fn is_deletion(&self) -> bool {
        self.is_deletion
    }

    /// The entries in file order; empty for external classes and deletions.
    pub fn entries(&self) -> impl Iterator<Item = (&str, &ConfigEntry)> {
        self.entries
            .iter()
            .flatten()
            .map(|(name, entry)| (name.as_str(), entry))
    }

    /// Looks up an entry by name, ASCII case-insensitively like the game.
    ///
    /// Returns the first entry with that name; use [`ConfigClass::entries`] to see every entry
    /// when a config defines a name twice. A `delete X;` entry comes back
    /// as [`ConfigEntry::ClassEntry`] with [`ConfigClass::is_deletion`] `true`.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&ConfigEntry> {
        self.entries()
            .find(|(n, _)| n.eq_ignore_ascii_case(name))
            .map(|(_, entry)| entry)
    }

    fn write<O: Write>(&self, output: &mut O, level: usize, indent: &str) -> Result<(), Error> {
        if let Some(entries) = &self.entries {
            if level > 0 && !entries.is_empty() {
                output.write_all(b"\n")?;
            }
            for (key, value) in entries {
                text_name(key, "Entry")?;
                output.write_all(indent.repeat(level).as_bytes())?;

                match value {
                    ConfigEntry::ClassEntry(c) => {
                        if c.is_deletion {
                            output.write_all(format!("delete {key};\n").as_bytes())?;
                        } else if c.is_external {
                            output.write_all(format!("class {key};\n").as_bytes())?;
                        } else {
                            let parent = if c.parent.is_empty() {
                                String::new()
                            } else {
                                text_name(&c.parent, "Parent class")?;
                                format!(": {}", c.parent)
                            };
                            match &c.entries {
                                Some(entries) => {
                                    if entries.is_empty() {
                                        output.write_all(
                                            format!("class {key}{parent} {{}};\n").as_bytes(),
                                        )?;
                                    } else {
                                        output.write_all(
                                            format!("class {key}{parent} {{").as_bytes(),
                                        )?;
                                        c.write(output, level + 1, indent)?;
                                        output.write_all(indent.repeat(level).as_bytes())?;
                                        output.write_all(b"};\n")?;
                                    }
                                }
                                None => {
                                    output.write_all(
                                        format!("class {key}{parent} {{}};\n").as_bytes(),
                                    )?;
                                }
                            }
                        }
                    }
                    ConfigEntry::StringEntry(s) => {
                        output.write_all(
                            format!(
                                "{} = \"{}\";\n",
                                key,
                                s.replace('\r', "\\r")
                                    .replace('\n', "\\n")
                                    .replace('"', "\"\"")
                            )
                            .as_bytes(),
                        )?;
                    }
                    ConfigEntry::FloatEntry(f) => {
                        output.write_all(format!("{key} = {};\n", float_literal(*f)).as_bytes())?;
                    }
                    ConfigEntry::IntEntry(i) => {
                        output.write_all(format!("{key} = {i};\n").as_bytes())?;
                    }
                    ConfigEntry::Int64Entry(i) => {
                        output.write_all(format!("{key} = {i};\n").as_bytes())?;
                    }
                    ConfigEntry::ArrayEntry(a) => {
                        if a.is_expansion {
                            output.write_all(format!("{key}[] += ").as_bytes())?;
                        } else {
                            output.write_all(format!("{key}[] = ").as_bytes())?;
                        }
                        a.write(output)?;
                        output.write_all(b";\n")?;
                    }
                }
            }
        }

        Ok(())
    }

    fn rapified_length(&self) -> usize {
        match &self.entries {
            Some(entries) => {
                self.parent.len()
                    + 1
                    + compressed_int_len_of(entries.len())
                    + usize::sum(entries.iter().map(|(k, v)| {
                        k.len()
                            + 1
                            + v.rapified_length()
                            + match v {
                                ConfigEntry::ClassEntry(c) => c.rapified_length(),
                                _ => 0,
                            }
                    }))
            }
            None => 0,
        }
    }

    fn write_rapified<O: Write>(&self, output: &mut O, offset: usize) -> Result<usize, Error> {
        let mut written = 0;

        match &self.entries {
            Some(entries) => {
                output.write_cstring(&self.parent)?;
                written += self.parent.len() + 1;

                let num_entries = u32::try_from(entries.len())
                    .map_err(|_| error!("too many class entries: {}", entries.len()))?;
                written += output.write_compressed_int(num_entries)?;

                let entries_len = usize::sum(
                    entries
                        .iter()
                        .map(|(k, v)| k.len() + 1 + v.rapified_length()),
                );
                let mut class_offset = offset + written + entries_len;
                let mut class_bodies: Vec<Cursor<Box<[u8]>>> = Vec::new();
                let pre_entries = written;

                for (name, entry) in entries {
                    let pre_write = written;
                    match entry {
                        ConfigEntry::StringEntry(s) => {
                            output.write_all(&[1, 0])?;
                            output
                                .write_cstring(name)
                                .and_then(|()| output.write_cstring(s))
                                .prepend_error(format!("Entry \"{}\":", printable(name)))?;
                            written += name.len() + s.len() + 4;
                        }
                        ConfigEntry::FloatEntry(f) => {
                            output.write_all(&[1, 1])?;
                            output.write_cstring(name)?;
                            output.write_f32::<LittleEndian>(*f)?;
                            written += name.len() + 7;
                        }
                        ConfigEntry::IntEntry(i) => {
                            output.write_all(&[1, 2])?;
                            output.write_cstring(name)?;
                            output.write_i32::<LittleEndian>(*i)?;
                            written += name.len() + 7;
                        }
                        ConfigEntry::Int64Entry(i) => {
                            output.write_all(&[1, 6])?;
                            output.write_cstring(name)?;
                            output.write_i64::<LittleEndian>(*i)?;
                            written += name.len() + 11;
                        }
                        ConfigEntry::ArrayEntry(a) => {
                            output.write_all(if a.is_expansion { &[5] } else { &[2] })?;
                            if a.is_expansion {
                                output.write_all(&[1, 0, 0, 0])?;
                                written += 4;
                            }
                            output.write_cstring(name)?;
                            written += name.len()
                                + 2
                                + a.write_rapified(output)
                                    .prepend_error(format!("Entry \"{}\":", printable(name)))?;
                        }
                        ConfigEntry::ClassEntry(c) => {
                            if c.is_external || c.is_deletion {
                                output.write_all(if c.is_deletion { &[4] } else { &[3] })?;
                                output.write_cstring(name)?;
                                written += name.len() + 2;
                            } else {
                                output.write_all(&[0])?;
                                output.write_cstring(name)?;
                                let class_offset_u32 =
                                    u32::try_from(class_offset).map_err(|_| {
                                        error!("class body offset out of range: {class_offset}")
                                    })?;
                                output.write_u32::<LittleEndian>(class_offset_u32)?;
                                written += name.len() + 6;

                                let buffer: Box<[u8]> =
                                    vec![0; c.rapified_length()].into_boxed_slice();
                                let mut cursor: Cursor<Box<[u8]>> = Cursor::new(buffer);
                                class_offset +=
                                    c.write_rapified(&mut cursor, class_offset).prepend_error(
                                        format!("Failed to rapify {}:", printable(name)),
                                    )?;

                                class_bodies.push(cursor);
                            }
                        }
                    }
                    assert_eq!(
                        written - pre_write,
                        entry.rapified_length() + name.len() + 1
                    );
                }

                assert_eq!(written - pre_entries, entries_len);

                for cursor in class_bodies {
                    output.write_all(cursor.get_ref())?;
                    written += cursor.get_ref().len();
                }
            }
            None => {
                return Err(error!("Cannot rapify a class without entries."));
            }
        }

        Ok(written)
    }

    fn read_rapified<I: Read + Seek>(
        input: &mut I,
        level: u32,
        budget: &mut ReadBudget,
    ) -> Result<ConfigClass, Error> {
        let mut fp = 0;
        let body_offset: u32 = if level == 0 {
            input.seek(SeekFrom::Start(16))?;
            16
        } else {
            let classbody_fp: u32 = input.read_u32::<LittleEndian>()?;

            fp = input.stream_position()?;
            input.seek(SeekFrom::Start(classbody_fp.into()))?;
            classbody_fp
        };

        if budget.open_bodies.contains(&body_offset) {
            return Err(error!("Rapified class body cycle at offset {body_offset}."));
        }
        if !budget.seen_bodies.insert(body_offset) {
            return Err(error!(
                "Rapified class body shared at offset {body_offset}."
            ));
        }
        budget.enter()?;
        budget.open_bodies.push(body_offset);
        let result = ConfigClass::read_rapified_body(input, level, budget);
        budget.open_bodies.pop();
        budget.leave();
        let class = result?;

        if level > 0 {
            input.seek(SeekFrom::Start(fp))?;
        }

        Ok(class)
    }

    fn read_rapified_body<I: Read + Seek>(
        input: &mut I,
        level: u32,
        budget: &mut ReadBudget,
    ) -> Result<ConfigClass, Error> {
        let parent = input.read_cstring()?;
        let num_entries: u32 = input.read_compressed_int()?;
        // never preallocate the full length from untrusted input
        let mut entries: Vec<(String, ConfigEntry)> =
            Vec::with_capacity(num_entries.min(65536) as usize);

        for _i in 0..num_entries {
            budget.take_entry()?;
            let mut buf = [0u8; 1];
            input.read_exact(&mut buf)?;
            let entry_type = buf[0];

            if entry_type == 0 {
                let name = input.read_cstring()?;

                let class_entry = ConfigClass::read_rapified(input, level + 1, budget)
                    .prepend_error(format!(
                        "Failed to read rapified class \"{}\":",
                        printable(&name)
                    ))?;
                entries.push((name, ConfigEntry::ClassEntry(class_entry)));
            } else if entry_type == 1 {
                let mut buf = [0u8; 1];
                input.read_exact(&mut buf)?;
                let subtype = buf[0];
                let name = input.read_cstring()?;

                if subtype == 0 {
                    entries.push((name, ConfigEntry::StringEntry(input.read_cstring()?)));
                } else if subtype == 1 {
                    entries.push((
                        name,
                        ConfigEntry::FloatEntry(input.read_f32::<LittleEndian>()?),
                    ));
                } else if subtype == 2 {
                    entries.push((
                        name,
                        ConfigEntry::IntEntry(input.read_i32::<LittleEndian>()?),
                    ));
                } else if subtype == 6 {
                    entries.push((
                        name,
                        ConfigEntry::Int64Entry(input.read_i64::<LittleEndian>()?),
                    ));
                } else {
                    return Err(error!("Unrecognized variable entry subtype: {}.", subtype));
                }
            } else if entry_type == 2 || entry_type == 5 {
                if entry_type == 5 {
                    input.seek(SeekFrom::Current(4))?;
                }

                let name = input.read_cstring()?;
                let mut array = ConfigArray::read_rapified(input, budget)
                    .prepend_error("Failed to read rapified array:")?;
                array.is_expansion = entry_type == 5;

                entries.push((name.clone(), ConfigEntry::ArrayEntry(array)));
            } else if entry_type == 3 || entry_type == 4 {
                let name = input.read_cstring()?;
                let class_entry = ConfigClass {
                    parent: String::new(),
                    is_external: entry_type == 3,
                    is_deletion: entry_type == 4,
                    entries: None,
                };

                entries.push((name.clone(), ConfigEntry::ClassEntry(class_entry)));
            } else {
                return Err(error!("Unrecognized class entry type: {}.", entry_type));
            }
        }

        Ok(ConfigClass {
            parent,
            is_external: false,
            is_deletion: false,
            entries: Some(entries),
        })
    }
}

/// Options for [`Config::write_with`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WriteOptions {
    indent: String,
}

impl Default for WriteOptions {
    fn default() -> Self {
        Self {
            indent: "    ".to_string(),
        }
    }
}

impl WriteOptions {
    /// The default options: four spaces of indentation.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the string written once per nesting level.
    ///
    /// The string may be empty and may only contain spaces and tabs, at most 64 characters, so the
    /// output stays parsable.
    ///
    /// # Errors
    ///
    /// Returns an error naming the value if it contains other characters or is too long.
    pub fn indent(mut self, indent: impl Into<String>) -> Result<Self, Error> {
        let indent = indent.into();
        let length = indent.chars().count();
        if length > 64 {
            return Err(error!(
                "Invalid indentation: it is {length} characters, at most 64 are allowed."
            ));
        }
        if !indent.chars().all(|c| c == ' ' || c == '\t') {
            return Err(error!(
                "Invalid indentation \"{}\": use spaces and tabs only.",
                printable(&indent)
            ));
        }
        self.indent = indent;
        Ok(self)
    }
}

impl Config {
    /// The unnamed top-level class holding all entries of the file.
    #[must_use]
    pub fn root(&self) -> &ConfigClass {
        &self.root_body
    }

    /// The values of the `enum { ... }` blocks, in source order (or table order for a rapified config).
    ///
    /// Names are lowercase, as the game stores them. The values of all blocks, at any class level,
    /// land in this one table.
    #[must_use]
    pub fn enum_values(&self) -> &[(String, i32)] {
        &self.enums
    }

    fn rapified_enum_table_length(&self) -> usize {
        4 + self
            .enums
            .iter()
            .map(|(n, _)| n.len() + 1 + 4)
            .sum::<usize>()
    }

    /// Writes the config (unrapified) to the output.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failure.
    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        self.write_with(output, &WriteOptions::new())
    }

    /// Writes the config (unrapified) to the output with the given options.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failure or if a name cannot be written as text.
    pub fn write_with<O: Write>(
        &self,
        output: &mut O,
        options: &WriteOptions,
    ) -> Result<(), Error> {
        // check everything before the first byte: a block is never half-written
        for (name, _) in &self.enums {
            text_name(name, "Enum")?;
        }
        if !self.enums.is_empty() {
            output.write_all(b"enum {\n")?;
            for (i, (name, value)) in self.enums.iter().enumerate() {
                let comma = if i + 1 < self.enums.len() { "," } else { "" };
                output
                    .write_all(format!("{}{name} = {value}{comma}\n", options.indent).as_bytes())?;
            }
            output.write_all(b"};\n")?;
        }
        self.root_body.write(output, 0, &options.indent)
    }

    /// Returns the unrapified config as a string.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failure or invalid UTF-8 in the output.
    pub fn to_string(&self) -> Result<String, Error> {
        let buffer = Vec::new();
        let mut cursor: Cursor<Vec<u8>> = Cursor::new(buffer);
        self.write(&mut cursor)?;

        String::from_utf8(cursor.into_inner())
            .map_err(|e| error!("Invalid UTF-8 in config output: {e}"))
    }

    /// Writes the rapified config to the output.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failure or if the config cannot be rapified.
    pub fn write_rapified<O: Write>(&self, output: &mut O) -> Result<(), Error> {
        let mut writer = BufWriter::new(output);

        writer.write_all(b"\0raP")?;
        writer.write_all(b"\0\0\0\0\x08\0\0\0")?; // always_0, always_8

        let buffer: Box<[u8]> = vec![0; self.root_body.rapified_length()].into_boxed_slice();
        let mut cursor: Cursor<Box<[u8]>> = Cursor::new(buffer);
        self.root_body
            .write_rapified(&mut cursor, 16)
            .prepend_error("Failed to rapify root class:")?;

        let enum_offset = u32::try_from(16 + cursor.get_ref().len())
            .map_err(|_| error!("config too large: {} bytes", cursor.get_ref().len()))?;
        writer.write_u32::<LittleEndian>(enum_offset)?;

        writer.write_all(cursor.get_ref())?;

        let count = u32::try_from(self.enums.len())
            .map_err(|_| error!("too many enum values: {}", self.enums.len()))?;
        writer.write_u32::<LittleEndian>(count)?;
        for (name, value) in &self.enums {
            writer.write_all(name.as_bytes())?;
            writer.write_all(b"\0")?;
            writer.write_i32::<LittleEndian>(*value)?;
        }
        writer.flush()?;

        Ok(())
    }

    /// Returns the rapified config as a `Cursor`.
    ///
    /// # Errors
    ///
    /// Returns an error if the config cannot be rapified.
    pub fn to_cursor(&self) -> Result<Cursor<Box<[u8]>>, Error> {
        let len = self.root_body.rapified_length() + 16 + self.rapified_enum_table_length();

        let buffer: Box<[u8]> = vec![0; len].into_boxed_slice();
        let mut cursor: Cursor<Box<[u8]>> = Cursor::new(buffer);
        self.write_rapified(&mut cursor)?;

        Ok(cursor)
    }

    /// Reads the unrapified config from input, preprocessing it.
    ///
    /// `path` is the path to the input if it is known and is used for relative includes and error
    /// messages. `includefolders` are the folders searched recursively for absolute includes.
    ///
    /// # Errors
    ///
    /// Returns an error on preprocessing or parse failures.
    pub fn read<I: Read>(
        input: &mut I,
        path: Option<PathBuf>,
        includefolders: &[PathBuf],
        warnings: &mut dyn WarningSink,
    ) -> Result<Config, Error> {
        Self::read_in(
            input,
            path,
            &IncludeFolders::new(includefolders.to_vec()),
            warnings,
        )
    }

    /// Like [`Config::read`], with the include folders given as an [`IncludeFolders`] (some of them can be checked
    /// directly instead of searched recursively).
    ///
    /// # Errors
    ///
    /// Returns an error on preprocessing or parse failures.
    pub fn read_in<I: Read>(
        input: &mut I,
        path: Option<PathBuf>,
        includefolders: &IncludeFolders,
        warnings: &mut dyn WarningSink,
    ) -> Result<Config, Error> {
        let mut bytes = Vec::new();
        input
            .read_to_end(&mut bytes)
            .prepend_error("Failed to read input file:")?;
        if is_rapified(&bytes) {
            return Config::read_rapified(&mut Cursor::new(bytes));
        }
        let buffer =
            String::from_utf8(bytes).map_err(|e| error!("Failed to read input file: {}", e))?;
        let (preprocessed, info) = preprocess_in(buffer, path, includefolders, warnings)
            .prepend_error("Failed to preprocess config:")?;

        // The preprocessor ends its output with a line end. A file whose last source line is an entry
        // (not empty, a directive, a comment or inside an unterminated comment) has no line end of its own there, so that entry ends at the end of the file, which CfgConvert
        // rejects unless it is closed by `;` or `}`.
        let preprocessed = match preprocessed.strip_suffix('\n') {
            Some(text) if info.ends_in_entry => text.to_string(),
            _ => preprocessed,
        };

        let mut found = ConfigWarnings(Vec::new());

        let mut ctx = EvalCtx::default();
        let parsed = config_grammar::config(&preprocessed, &mut found, &mut ctx);
        // The line the parse failed on starts at `failed_line_start`. Warnings raised from there on are by
        // the attempts that failed (`x = 1 // c` is tried as an unquoted string first), not about the
        // input, so they are dropped; the ones from earlier lines are real and stay. One search for the
        // line start, so the filter is linear in the number of warnings.
        let failed_at = match (&ctx.error, &parsed) {
            (Some((pos, _)), _) => Some(*pos),
            (None, Err(pe)) => Some(pe.location.offset),
            (None, Ok(_)) => None,
        };
        if let Some(at) = failed_at {
            let before = preprocessed.get(..at).unwrap_or(&preprocessed);
            let failed_line_start = before.rfind('\n').map_or(0, |i| i + 1);
            found.0.retain(|w| w.0 < failed_line_start);
        }
        let result = match ctx.error.take() {
            Some((pos, e)) => Err(located_error(&info, &preprocessed, pos, &e)),
            _ => ConfigParseErrorExt::format_error(parsed, &info, &preprocessed),
        };

        // PEG backtracking runs rule actions more than once; report each warning once.
        let mut seen = std::collections::HashSet::new();
        found.0.retain(|w| seen.insert((w.0, w.1.clone())));

        for w in found.0 {
            let location = if warnings.is_suppressed(w.2) {
                (None, None)
            } else {
                let lines_before = preprocessed[..w.0].chars().filter(|c| c == &'\n').count();
                let idx = min(lines_before, info.line_origins.len().saturating_sub(1)); // origins are 1-based line numbers
                let file = info
                    .line_origins
                    .get(idx)
                    .and_then(|o| o.1.as_ref())
                    .map(|p| p.display().to_string());
                let line = match info.line_origins.get(idx) {
                    Some(o) => o.0,
                    None => u32::try_from(lines_before + 1)
                        .map_err(|_| error!("line number out of range"))?,
                };

                (file, Some(line))
            };

            let mut warning = Warning::new(w.2, w.1);
            if let Some(file) = location.0 {
                warning = warning.in_file(file);
            }
            if let Some(line) = location.1 {
                warning = warning.at_line(line);
            }
            warnings.warn(warning);
        }

        result
    }

    /// Preprocesses and parses input string.
    ///
    /// `path` is the path to the input if it is known and is used for relative includes and error
    /// messages. `includefolders` are the folders searched recursively for absolute includes.
    ///
    /// # Errors
    ///
    /// Returns an error on preprocessing or parse failures.
    pub fn from_string(
        input: String,
        path: Option<PathBuf>,
        includefolders: &[PathBuf],
        warnings: &mut dyn WarningSink,
    ) -> Result<Config, Error> {
        let mut cursor = Cursor::new(input.into_bytes());
        Self::read(&mut cursor, path, includefolders, warnings)
    }

    /// Like [`Config::from_string`], with the include folders given as an [`IncludeFolders`].
    ///
    /// # Errors
    ///
    /// Returns an error on preprocessing or parse failures.
    pub fn from_string_in(
        input: String,
        path: Option<PathBuf>,
        includefolders: &IncludeFolders,
        warnings: &mut dyn WarningSink,
    ) -> Result<Config, Error> {
        let mut cursor = Cursor::new(input.into_bytes());
        Self::read_in(&mut cursor, path, includefolders, warnings)
    }

    /// Reads the rapified config from input.
    ///
    /// # Errors
    ///
    /// Returns an error if the input is not a rapified config or cannot be parsed.
    pub fn read_rapified<I: Read + Seek>(input: &mut I) -> Result<Config, Error> {
        let mut reader = BufReader::new(input);

        let mut buffer = [0; 4];
        reader.read_exact(&mut buffer)?;

        if &buffer != b"\0raP" {
            return Err(error!("File doesn't seem to be a rapified config."));
        }

        let root_body = ConfigClass::read_rapified(&mut reader, 0, &mut ReadBudget::new())?;
        let enums = read_enum_table(&mut reader);

        Ok(Config { root_body, enums })
    }
}