dayzmake-core 0.2.2

Readers and writers for DayZ file formats: PBO, rapified config, P3D, PAA, BI keys and signatures
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
//! 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, 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>,
    error: Option<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 float() -> f32 = f:$((['-' | '+'])? ['0'..='9']* "." ['0'..='9']+) {?
            f.parse::<f32>()
                .map_err(|e| { ctx.error.get_or_insert(error!("Invalid float \"{f}\": {e}")); "a valid float" })
        }

        rule integer() -> i32 = i:$((['-' | '+'])? (("0x" ['0'..='9' | 'a'..='f' | 'A'..='F']+) / ['0'..='9']+)) {?
            if i.contains("0x") {
                i32::from_str_radix(&i.replace("0x", ""), 16)
                    .map_err(|e| { ctx.error.get_or_insert(error!("Invalid integer \"{i}\": {e}")); "a valid integer" })
            } else {
                i.parse::<i32>()
                    .map_err(|e| { ctx.error.get_or_insert(error!("Invalid integer \"{i}\": {e}")); "a valid integer" })
            }
        }

        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) = {?
            if d >= MAX_NESTING_DEPTH {
                ctx.error.get_or_insert(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 = "__EVAL" whitespace()? "(" b:$(eval_body(d)) ")" {?
            match eval(b, &mut ctx.vars) {
                Ok(v) => Ok(v),
                Err(e) => { ctx.error.get_or_insert(e); Err("a supported __EVAL expression") }
            }
        }

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

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

        rule array_element(d: usize) -> ConfigArrayElement =
            f:float()   &(whitespace()? [',' | '}']) { ConfigArrayElement::FloatElement(f) } /
            i:integer() &(whitespace()? [',' | '}']) { ConfigArrayElement::IntElement(i) } /
            a:array(d)   &(whitespace()? [',' | '}']) { ConfigArrayElement::ArrayElement(a) } /
            s:string()  &(whitespace()? [',' | '}']) { ConfigArrayElement::StringElement(s) } /
            v:eval_value(d) &(whitespace()? [',' | '}']) { v.into() } /
            s:unquoted_string_array() &(whitespace()? [',' | '}']) { ConfigArrayElement::StringElement(s) }

        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()   { ConfigEntry::FloatEntry(f) } /
            i:integer() { 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 entry(d: usize) -> (String, ConfigEntry) =
            e:(class(d) / array_entry(d) / array_expansion_entry(d) / var_entry(d)) whitespace()? (";" / &"}") { e } /
            e:unquoted_string_entry() (";" / &"}" / &['\r' | '\n']) { e }

        rule entry_or_exec(d: usize) -> Option<(String, ConfigEntry)> = exec_entry(d) { None } / e:entry(d) { Some(e) }

        rule entries(d: usize) -> Vec<(String, ConfigEntry)> = v:(entry_or_exec(d) ** (whitespace()?)) { v.into_iter().flatten().collect() }

        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) -> (String, ConfigEntry) = "class" whitespace()+ n:name() p:parent()? whitespace()? "{" nesting_ok(d) whitespace()? e:entries(d + 1) whitespace()? "}" {
            let parent = p.unwrap_or_default();
            (n, ConfigEntry::ClassEntry(ConfigClass {
                parent,
                is_external: false,
                is_deletion: false,
                entries: Some(e)
            }))
        }

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

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

        rule class(d: usize) -> (String, ConfigEntry) = 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)
                }
            }
        }
    }
}

/// 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,
}

/// 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),
    /// 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(format!("{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::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} = {f:?};\n").as_bytes())?;
                    }
                    ConfigEntry::IntEntry(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::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 {
                    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
    }

    /// 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> {
        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())?;

        writer.write_all(b"\0\0\0\0")?;

        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() + 20;

        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:")?;

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

        let mut ctx = EvalCtx::default();
        let parsed = config_grammar::config(&preprocessed, &mut found, &mut ctx);
        let result = match ctx.error.take() {
            // the warnings were raised by the fallback rules tried after the failed __EVAL/__EXEC
            Some(e) => return Err(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."));
        }

        Ok(Config {
            root_body: ConfigClass::read_rapified(&mut reader, 0, &mut ReadBudget::new())?,
        })
    }
}