whiteoutlib 0.1.5

Read and write Blizzard game assets from Rust: models (MDX, M2, M3), textures (BLP, DDS, PNG, JPEG, BMP, TGA, TIFF, GIF) and archives (CASC, MPQ).
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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2026 Fernando Sahmkow
// AUTOGENERATED by tools/codegen/emit_rust.py — do not edit.
// Regenerate via:  python -m tools.codegen.codegen mpq --backend rust

#![allow(clippy::too_many_arguments)]

// Which of these a module needs depends on its shapes; the modules that
// have no span accessors would otherwise trip the unused-import lint.
#[allow(unused_imports)]
use crate::support::{BorrowedSlice, Bytes};

/// MPQ format version.
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FormatVersion {
    /// Original format (up to 4 GB archives).
    V1 = 0,
    /// Extended format (>4 GB archives, hi-block table).
    V2 = 1,
}

impl TryFrom<i32> for FormatVersion {
    type Error = crate::Error;
    fn try_from(v: i32) -> Result<Self, crate::Error> {
        match v {
            0 => Ok(FormatVersion::V1),
            1 => Ok(FormatVersion::V2),
            other => Err(crate::Error::UnknownEnum {
                name: "FormatVersion",
                value: other,
            }),
        }
    }
}

/// Compression algorithm for writing files.
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Compression {
    /// No compression; data stored verbatim.
    None = 0,
    /// Huffman coding (used for audio in older Blizzard games).
    Huffman = 1,
    /// zlib / DEFLATE compression (most common MPQ codec).
    Zlib = 2,
    /// PKware DCL (implode) compression.
    PKware = 8,
    /// bzip2 compression.
    BZip2 = 16,
    /// Sparse / RLE compression.
    Sparse = 32,
    /// IMA ADPCM mono (used for mono audio).
    AdpcmMono = 64,
    /// IMA ADPCM stereo (used for stereo audio).
    AdpcmStereo = -128,
}

impl TryFrom<i32> for Compression {
    type Error = crate::Error;
    fn try_from(v: i32) -> Result<Self, crate::Error> {
        match v {
            0 => Ok(Compression::None),
            1 => Ok(Compression::Huffman),
            2 => Ok(Compression::Zlib),
            8 => Ok(Compression::PKware),
            16 => Ok(Compression::BZip2),
            32 => Ok(Compression::Sparse),
            64 => Ok(Compression::AdpcmMono),
            -128 => Ok(Compression::AdpcmStereo),
            other => Err(crate::Error::UnknownEnum {
                name: "Compression",
                value: other,
            }),
        }
    }
}

/// Bit flags. Combine with `|`, test with [`FileFlags::contains`].
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct FileFlags(pub i32);

impl FileFlags {
    pub const NONE: Self = Self(0);
    /// File uses sector compression.
    pub const COMPRESSED: Self = Self(512);
    /// File data is encrypted.
    pub const ENCRYPTED: Self = Self(65536);
    /// File stored as a single unit (no sector splitting).
    pub const SINGLE_UNIT: Self = Self(16777216);
    /// Slot is occupied by a real file.
    pub const EXISTS: Self = Self(-2147483648);

    #[inline]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    #[inline]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl core::ops::BitOr for FileFlags {
    type Output = Self;
    #[inline]
    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl core::ops::BitAnd for FileFlags {
    type Output = Self;
    #[inline]
    fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
    }
}

impl core::ops::Not for FileFlags {
    type Output = Self;
    #[inline]
    fn not(self) -> Self {
        Self(!self.0)
    }
}

impl core::fmt::Debug for FileFlags {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "FileFlags({:#x})", self.0)
    }
}

/// Information about a single file in the archive.
pub struct FileInfo {
    pub(crate) raw: core::ptr::NonNull<ffi::whiteout_MpqFileInfo>,
}

impl Drop for FileInfo {
    fn drop(&mut self) {
        // SAFETY: `raw` came from a native constructor and Drop runs once.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_delete(self.raw.as_ptr()) }
    }
}

impl FileInfo {
    /// # Safety
    /// `raw` must be a live handle this value takes ownership of.
    #[allow(dead_code)] // used by whichever methods return this type
    pub(crate) unsafe fn from_raw(raw: *mut ffi::whiteout_MpqFileInfo) -> Option<Self> {
        core::ptr::NonNull::new(raw).map(|raw| FileInfo { raw })
    }
}

// SAFETY: handles are plain heap pointers with no thread affinity. `Sync`
// is deliberately NOT implemented — the C++ types make no documented
// guarantee about concurrent use, and claiming one we haven't verified
// would be unsound. See `@bind thread_safe` in the plan.
unsafe impl Send for FileInfo {}

impl core::fmt::Debug for FileInfo {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("FileInfo").finish_non_exhaustive()
    }
}

impl FileInfo {
    /// # Panics
    /// Panics if the native allocation fails.
    pub fn new() -> Self {
        // SAFETY: the native constructor returns a live handle; a null here
        // means the library is unusable.
        unsafe {
            let raw = ffi::whiteout_mpq_MpqFileInfo_new();
            Self::from_raw(raw).expect("native FileInfo allocation failed")
        }
    }

    /// Filename (from listfile or hash table lookup).
    pub fn name(&self) -> String {
        // SAFETY: the native side hands over an owned CString.
        unsafe {
            crate::support::take_string(ffi::whiteout_mpq_MpqFileInfo_get_name(self.raw.as_ptr()))
        }
    }

    pub fn set_name(&mut self, value: &str) {
        let value = std::ffi::CString::new(value).unwrap_or_default();
        // SAFETY: the pointer outlives the call.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_set_name(self.raw.as_ptr(), value.as_ptr()) }
    }

    /// Compressed storage size in bytes.
    pub fn compressed_size(&self) -> u32 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_get_compressedSize(self.raw.as_ptr()) }
    }

    pub fn set_compressed_size(&mut self, value: u32) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_set_compressedSize(self.raw.as_ptr(), value) }
    }

    /// Uncompressed (original) file size in bytes.
    pub fn uncompressed_size(&self) -> u32 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_get_uncompressedSize(self.raw.as_ptr()) }
    }

    pub fn set_uncompressed_size(&mut self, value: u32) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_set_uncompressedSize(self.raw.as_ptr(), value) }
    }

    /// Block entry flags (see FileFlags enum).
    pub fn flags(&self) -> FileFlags {
        // SAFETY: scalar read; a flag set accepts any bits.
        FileFlags(unsafe { ffi::whiteout_mpq_MpqFileInfo_get_flags(self.raw.as_ptr()) })
    }

    pub fn set_flags(&mut self, value: FileFlags) {
        // SAFETY: scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_set_flags(self.raw.as_ptr(), value.0) }
    }

    /// Locale ID (typically Locale::Neutral).
    pub fn locale(&self) -> u16 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_get_locale(self.raw.as_ptr()) }
    }

    pub fn set_locale(&mut self, value: u16) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqFileInfo_set_locale(self.raw.as_ptr(), value) }
    }
}

impl Default for FileInfo {
    fn default() -> Self {
        Self::new()
    }
}

/// Summary information about the archive.
pub struct ArchiveInfo {
    pub(crate) raw: core::ptr::NonNull<ffi::whiteout_MpqArchiveInfo>,
}

impl Drop for ArchiveInfo {
    fn drop(&mut self) {
        // SAFETY: `raw` came from a native constructor and Drop runs once.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_delete(self.raw.as_ptr()) }
    }
}

impl ArchiveInfo {
    /// # Safety
    /// `raw` must be a live handle this value takes ownership of.
    #[allow(dead_code)] // used by whichever methods return this type
    pub(crate) unsafe fn from_raw(raw: *mut ffi::whiteout_MpqArchiveInfo) -> Option<Self> {
        core::ptr::NonNull::new(raw).map(|raw| ArchiveInfo { raw })
    }
}

// SAFETY: handles are plain heap pointers with no thread affinity. `Sync`
// is deliberately NOT implemented — the C++ types make no documented
// guarantee about concurrent use, and claiming one we haven't verified
// would be unsound. See `@bind thread_safe` in the plan.
unsafe impl Send for ArchiveInfo {}

impl core::fmt::Debug for ArchiveInfo {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ArchiveInfo").finish_non_exhaustive()
    }
}

impl ArchiveInfo {
    /// # Panics
    /// Panics if the native allocation fails.
    pub fn new() -> Self {
        // SAFETY: the native constructor returns a live handle; a null here
        // means the library is unusable.
        unsafe {
            let raw = ffi::whiteout_mpq_MpqArchiveInfo_new();
            Self::from_raw(raw).expect("native ArchiveInfo allocation failed")
        }
    }

    /// 0 = V1, 1 = V2.
    pub fn format_version(&self) -> u16 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_get_formatVersion(self.raw.as_ptr()) }
    }

    pub fn set_format_version(&mut self, value: u16) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_set_formatVersion(self.raw.as_ptr(), value) }
    }

    /// Hash table capacity (always a power of 2).
    pub fn hash_table_entries(&self) -> u32 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_get_hashTableEntries(self.raw.as_ptr()) }
    }

    pub fn set_hash_table_entries(&mut self, value: u32) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_set_hashTableEntries(self.raw.as_ptr(), value) }
    }

    /// Number of occupied block table entries.
    pub fn block_table_entries(&self) -> u32 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_get_blockTableEntries(self.raw.as_ptr()) }
    }

    pub fn set_block_table_entries(&mut self, value: u32) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_set_blockTableEntries(self.raw.as_ptr(), value) }
    }

    /// Sector size in bytes (512 << sectorSizeShift).
    pub fn sector_size(&self) -> u32 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_get_sectorSize(self.raw.as_ptr()) }
    }

    pub fn set_sector_size(&mut self, value: u32) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_set_sectorSize(self.raw.as_ptr(), value) }
    }

    /// Total archive size in bytes.
    pub fn archive_size(&self) -> u64 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_get_archiveSize(self.raw.as_ptr()) }
    }

    pub fn set_archive_size(&mut self, value: u64) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqArchiveInfo_set_archiveSize(self.raw.as_ptr(), value) }
    }
}

impl Default for ArchiveInfo {
    fn default() -> Self {
        Self::new()
    }
}

/// Options for writing a file into the archive.
pub struct WriteOptions {
    pub(crate) raw: core::ptr::NonNull<ffi::whiteout_MpqWriteOptions>,
}

impl Drop for WriteOptions {
    fn drop(&mut self) {
        // SAFETY: `raw` came from a native constructor and Drop runs once.
        unsafe { ffi::whiteout_mpq_MpqWriteOptions_delete(self.raw.as_ptr()) }
    }
}

impl WriteOptions {
    /// # Safety
    /// `raw` must be a live handle this value takes ownership of.
    #[allow(dead_code)] // used by whichever methods return this type
    pub(crate) unsafe fn from_raw(raw: *mut ffi::whiteout_MpqWriteOptions) -> Option<Self> {
        core::ptr::NonNull::new(raw).map(|raw| WriteOptions { raw })
    }
}

// SAFETY: handles are plain heap pointers with no thread affinity. `Sync`
// is deliberately NOT implemented — the C++ types make no documented
// guarantee about concurrent use, and claiming one we haven't verified
// would be unsound. See `@bind thread_safe` in the plan.
unsafe impl Send for WriteOptions {}

impl core::fmt::Debug for WriteOptions {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("WriteOptions").finish_non_exhaustive()
    }
}

impl WriteOptions {
    /// # Panics
    /// Panics if the native allocation fails.
    pub fn new() -> Self {
        // SAFETY: the native constructor returns a live handle; a null here
        // means the library is unusable.
        unsafe {
            let raw = ffi::whiteout_mpq_MpqWriteOptions_new();
            Self::from_raw(raw).expect("native WriteOptions allocation failed")
        }
    }

    /// Compression algorithm to apply.
    pub fn compression(&self) -> Compression {
        // SAFETY: scalar read; the discriminant is validated below.
        unsafe { ffi::whiteout_mpq_MpqWriteOptions_get_compression(self.raw.as_ptr()) }
            .try_into()
            .expect("unknown enum discriminant from the native library")
    }

    pub fn set_compression(&mut self, value: Compression) {
        // SAFETY: scalar write through a live handle.
        unsafe {
            ffi::whiteout_mpq_MpqWriteOptions_set_compression(self.raw.as_ptr(), value as i32)
        }
    }

    /// Locale ID for the hash table slot.
    pub fn locale(&self) -> u16 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqWriteOptions_get_locale(self.raw.as_ptr()) }
    }

    pub fn set_locale(&mut self, value: u16) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqWriteOptions_set_locale(self.raw.as_ptr(), value) }
    }

    /// Encrypt file data with a derived key.
    pub fn encrypt(&self) -> bool {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqWriteOptions_get_encrypt(self.raw.as_ptr()) != 0 }
    }

    pub fn set_encrypt(&mut self, value: bool) {
        // SAFETY: plain scalar write through a live handle.
        unsafe {
            ffi::whiteout_mpq_MpqWriteOptions_set_encrypt(
                self.raw.as_ptr(),
                if value { 1 } else { 0 },
            )
        }
    }

    /// Store the file as a single unpartitioned unit.
    pub fn single_unit(&self) -> bool {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqWriteOptions_get_singleUnit(self.raw.as_ptr()) != 0 }
    }

    pub fn set_single_unit(&mut self, value: bool) {
        // SAFETY: plain scalar write through a live handle.
        unsafe {
            ffi::whiteout_mpq_MpqWriteOptions_set_singleUnit(
                self.raw.as_ptr(),
                if value { 1 } else { 0 },
            )
        }
    }
}

impl Default for WriteOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// Options for creating a new archive.
pub struct CreateOptions {
    pub(crate) raw: core::ptr::NonNull<ffi::whiteout_MpqCreateOptions>,
}

impl Drop for CreateOptions {
    fn drop(&mut self) {
        // SAFETY: `raw` came from a native constructor and Drop runs once.
        unsafe { ffi::whiteout_mpq_MpqCreateOptions_delete(self.raw.as_ptr()) }
    }
}

impl CreateOptions {
    /// # Safety
    /// `raw` must be a live handle this value takes ownership of.
    #[allow(dead_code)] // used by whichever methods return this type
    pub(crate) unsafe fn from_raw(raw: *mut ffi::whiteout_MpqCreateOptions) -> Option<Self> {
        core::ptr::NonNull::new(raw).map(|raw| CreateOptions { raw })
    }
}

// SAFETY: handles are plain heap pointers with no thread affinity. `Sync`
// is deliberately NOT implemented — the C++ types make no documented
// guarantee about concurrent use, and claiming one we haven't verified
// would be unsound. See `@bind thread_safe` in the plan.
unsafe impl Send for CreateOptions {}

impl core::fmt::Debug for CreateOptions {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CreateOptions").finish_non_exhaustive()
    }
}

impl CreateOptions {
    /// # Panics
    /// Panics if the native allocation fails.
    pub fn new() -> Self {
        // SAFETY: the native constructor returns a live handle; a null here
        // means the library is unusable.
        unsafe {
            let raw = ffi::whiteout_mpq_MpqCreateOptions_new();
            Self::from_raw(raw).expect("native CreateOptions allocation failed")
        }
    }

    /// Archive format version (V1 or V2).
    pub fn version(&self) -> FormatVersion {
        // SAFETY: scalar read; the discriminant is validated below.
        unsafe { ffi::whiteout_mpq_MpqCreateOptions_get_version(self.raw.as_ptr()) }
            .try_into()
            .expect("unknown enum discriminant from the native library")
    }

    pub fn set_version(&mut self, value: FormatVersion) {
        // SAFETY: scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqCreateOptions_set_version(self.raw.as_ptr(), value as i32) }
    }

    /// Initial hash table capacity; rounded up to the next power of 2.
    pub fn hash_table_size(&self) -> u32 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqCreateOptions_get_hashTableSize(self.raw.as_ptr()) }
    }

    pub fn set_hash_table_size(&mut self, value: u32) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqCreateOptions_set_hashTableSize(self.raw.as_ptr(), value) }
    }

    /// Sector size = 512 << shift (default 3 → 4096 bytes).
    pub fn sector_size_shift(&self) -> u16 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_mpq_MpqCreateOptions_get_sectorSizeShift(self.raw.as_ptr()) }
    }

    pub fn set_sector_size_shift(&mut self, value: u16) {
        // SAFETY: plain scalar write through a live handle.
        unsafe { ffi::whiteout_mpq_MpqCreateOptions_set_sectorSizeShift(self.raw.as_ptr(), value) }
    }
}

impl Default for CreateOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// RAII wrapper for MPQ archive access
///
/// Provides full CRUD operations on MPQ archives.  Modifications are held in a virtual overlay until save() is called, which writes a complete new archive atomically (write to temp file, then rename).
///
/// All public methods are thread-safe: read operations acquire a shared lock; write and persist operations acquire an exclusive lock.
pub struct Storage {
    pub(crate) raw: core::ptr::NonNull<ffi::whiteout_MpqStorage>,
}

impl Drop for Storage {
    fn drop(&mut self) {
        // SAFETY: `raw` came from a native constructor and Drop runs once.
        unsafe { ffi::whiteout_mpq_MpqStorage_delete(self.raw.as_ptr()) }
    }
}

impl Storage {
    /// # Safety
    /// `raw` must be a live handle this value takes ownership of.
    #[allow(dead_code)] // used by whichever methods return this type
    pub(crate) unsafe fn from_raw(raw: *mut ffi::whiteout_MpqStorage) -> Option<Self> {
        core::ptr::NonNull::new(raw).map(|raw| Storage { raw })
    }
}

// SAFETY: handles are plain heap pointers with no thread affinity. `Sync`
// is deliberately NOT implemented — the C++ types make no documented
// guarantee about concurrent use, and claiming one we haven't verified
// would be unsound. See `@bind thread_safe` in the plan.
unsafe impl Send for Storage {}

impl core::fmt::Debug for Storage {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Storage").finish_non_exhaustive()
    }
}

impl Storage {
    /// Open an existing MPQ archive. Memory-maps the file and parses tables. @param path  Path to the .mpq file. @param pool  Optional WorkerPool for parallel compress/decompress (non-owning). @return A valid Storage, or std::nullopt on failure.
    pub fn open(path: &str, pool: Option<&crate::interfaces::HostWorkerPool>) -> Option<Storage> {
        let path_cstr = std::ffi::CString::new(path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Storage::from_raw(ffi::whiteout_mpq_MpqStorage_open(
                path_cstr.as_ptr(),
                pool.map_or(core::ptr::null_mut(), |v| v.as_ptr()),
            ))
        }
    }

    /// Create a new empty archive in memory. No file on disk until save(path).
    pub fn create(
        opts: &CreateOptions,
        pool: Option<&crate::interfaces::HostWorkerPool>,
    ) -> Option<Storage> {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Storage::from_raw(ffi::whiteout_mpq_MpqStorage_create(
                opts.raw.as_ptr(),
                pool.map_or(core::ptr::null_mut(), |v| v.as_ptr()),
            ))
        }
    }

    /// Release all resources. Same effect as letting the Storage go out of scope.
    pub fn close(&mut self) {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_mpq_MpqStorage_close(self.raw.as_ptr());
        }
    }

    /// Read a file from the archive. Checks the overlay first, then the source archive. @return File contents, or std::nullopt if not found or deleted.
    pub fn read_file(&self, name: &str) -> Option<Bytes> {
        let name_cstr = std::ffi::CString::new(name).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Bytes::from_raw(ffi::whiteout_mpq_MpqStorage_readFile(
                self.raw.as_ptr(),
                name_cstr.as_ptr(),
            ))
        }
    }

    /// Read a file with a specific locale.
    pub fn read_file_name_locale(&self, name: &str, locale: u16) -> Option<Bytes> {
        let name_cstr = std::ffi::CString::new(name).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Bytes::from_raw(ffi::whiteout_mpq_MpqStorage_readFile_name_locale(
                self.raw.as_ptr(),
                name_cstr.as_ptr(),
                locale,
            ))
        }
    }

    /// Check if a file exists in the archive (including overlay).
    pub fn file_exists(&self, name: &str) -> bool {
        let name_cstr = std::ffi::CString::new(name).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_mpq_MpqStorage_fileExists(self.raw.as_ptr(), name_cstr.as_ptr()) != 0
        }
    }

    /// Get information about a file.
    pub fn file_info(&self, name: &str) -> Option<FileInfo> {
        let name_cstr = std::ffi::CString::new(name).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            FileInfo::from_raw(ffi::whiteout_mpq_MpqStorage_fileInfo(
                self.raw.as_ptr(),
                name_cstr.as_ptr(),
            ))
        }
    }

    /// Get summary information about the archive.
    pub fn archive_info(&self) -> Option<ArchiveInfo> {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ArchiveInfo::from_raw(ffi::whiteout_mpq_MpqStorage_archiveInfo(self.raw.as_ptr()))
        }
    }

    /// List all known filenames (from listfile + overlay additions − deletions).
    pub fn list_files(&self) -> Vec<String> {
        // SAFETY: one call materialises the list; the
        // elements are borrowed out of it and it is freed
        // before returning. Reading is O(1) per element.
        unsafe {
            let list = ffi::whiteout_mpq_MpqStorage_listFiles(self.raw.as_ptr());
            if list.is_null() {
                return Vec::new();
            }
            let n = ffi::whiteout_mpq_StringList_size(list);
            let out = (0..n)
                .map(|i| crate::support::take_string(ffi::whiteout_mpq_StringList_at(list, i)))
                .collect();
            ffi::whiteout_mpq_StringList_delete(list);
            out
        }
    }

    /// Write or overwrite a file. Data is held in overlay until save(). @return true on success, false if the hash table is full.
    pub fn write_file(&mut self, name: &[u8], data: &[u8], opts: &WriteOptions) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_mpq_MpqStorage_writeFile(
                self.raw.as_ptr(),
                name.as_ptr(),
                name.len(),
                data.as_ptr(),
                data.len(),
                opts.raw.as_ptr(),
            ) != 0
        }
    }

    /// Delete a file from the archive. @return true if the file was found (in source or overlay), false otherwise.
    pub fn delete_file(&mut self, name: &str) -> bool {
        let name_cstr = std::ffi::CString::new(name).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_mpq_MpqStorage_deleteFile(self.raw.as_ptr(), name_cstr.as_ptr()) != 0
        }
    }

    /// Save the archive to its original path (temp file + atomic rename). @return false if this Storage was created via create() with no prior save(path).
    pub fn save(&mut self) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe { ffi::whiteout_mpq_MpqStorage_save(self.raw.as_ptr()) != 0 }
    }

    /// Save the archive to a specific path. After saving, the new file becomes the source archive and the overlay is cleared.
    pub fn save_path(&mut self, path: &str) -> bool {
        let path_cstr = std::ffi::CString::new(path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_mpq_MpqStorage_save_path(self.raw.as_ptr(), path_cstr.as_ptr()) != 0
        }
    }
}

/// VirtualPathFileSystem implementation backed by an MPQ archive.
///
/// The Storage must outlive this object — MpqFileSystem holds a non-owning reference to it.
///
/// Path separators: both '/' and '\\' are accepted and treated identically. Filename comparison is case-insensitive, matching MPQ archive semantics.
///
/// Requires the `whiteout_mpq` CMake target.
///
/// Example: auto storage = mpq::Storage::open("War3.mpq"); utils::MpqFileSystem fs(*storage); auto data = fs.readFile("units\\orc\\grunt\\grunt.mdx");
pub struct FileSystem {
    pub(crate) raw: core::ptr::NonNull<ffi::whiteout_MpqFileSystem>,
}

impl Drop for FileSystem {
    fn drop(&mut self) {
        // SAFETY: `raw` came from a native constructor and Drop runs once.
        unsafe { ffi::whiteout_mpq_MpqFileSystem_delete(self.raw.as_ptr()) }
    }
}

impl FileSystem {
    /// # Safety
    /// `raw` must be a live handle this value takes ownership of.
    #[allow(dead_code)] // used by whichever methods return this type
    pub(crate) unsafe fn from_raw(raw: *mut ffi::whiteout_MpqFileSystem) -> Option<Self> {
        core::ptr::NonNull::new(raw).map(|raw| FileSystem { raw })
    }
}

// SAFETY: handles are plain heap pointers with no thread affinity. `Sync`
// is deliberately NOT implemented — the C++ types make no documented
// guarantee about concurrent use, and claiming one we haven't verified
// would be unsound. See `@bind thread_safe` in the plan.
unsafe impl Send for FileSystem {}

impl core::fmt::Debug for FileSystem {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("FileSystem").finish_non_exhaustive()
    }
}

impl FileSystem {
    /// Read a file from the archive. Returns an empty vector if not found.
    pub fn read_file(&self, path: &str) -> Bytes {
        let path_cstr = std::ffi::CString::new(path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Bytes::from_raw(ffi::whiteout_mpq_MpqFileSystem_readFile(
                self.raw.as_ptr(),
                path_cstr.as_ptr(),
            ))
            .unwrap_or_else(Bytes::empty)
        }
    }

    /// Write a file into the archive overlay. Changes are not persisted to disk until storage.save() is called on the underlying Storage.
    pub fn write_file(&mut self, path: &str, data: &[u8]) -> bool {
        let path_cstr = std::ffi::CString::new(path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_mpq_MpqFileSystem_writeFile(
                self.raw.as_ptr(),
                path_cstr.as_ptr(),
                data.as_ptr(),
                data.len(),
            ) != 0
        }
    }

    /// Check if a file exists in the archive (including the write overlay).
    pub fn file_exists(&self, path: &str) -> bool {
        let path_cstr = std::ffi::CString::new(path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_mpq_MpqFileSystem_fileExists(self.raw.as_ptr(), path_cstr.as_ptr()) != 0
        }
    }
}

#[doc(hidden)]
pub mod ffi {
    #![allow(missing_debug_implementations)]

    #[allow(unused_imports)]
    use crate::support::{RawBytes, RawCString};

    #[repr(C)]
    pub struct whiteout_MpqFileInfo {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_MpqArchiveInfo {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_MpqWriteOptions {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_MpqCreateOptions {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_MpqStorage {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_MpqFileSystem {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_StringList {
        _private: [u8; 0],
    }

    extern "C" {
        pub fn whiteout_mpq_StringList_size(self_: *mut whiteout_StringList) -> usize;
        pub fn whiteout_mpq_StringList_at(
            self_: *mut whiteout_StringList,
            index: usize,
        ) -> RawCString;
        pub fn whiteout_mpq_StringList_delete(self_: *mut whiteout_StringList);
        // FileInfo
        pub fn whiteout_mpq_MpqFileInfo_new() -> *mut whiteout_MpqFileInfo;
        pub fn whiteout_mpq_MpqFileInfo_delete(self_: *mut whiteout_MpqFileInfo);
        pub fn whiteout_mpq_MpqFileInfo_get_name(self_: *mut whiteout_MpqFileInfo) -> RawCString;
        pub fn whiteout_mpq_MpqFileInfo_set_name(
            self_: *mut whiteout_MpqFileInfo,
            value: *const core::ffi::c_char,
        );
        pub fn whiteout_mpq_MpqFileInfo_get_compressedSize(self_: *mut whiteout_MpqFileInfo)
            -> u32;
        pub fn whiteout_mpq_MpqFileInfo_set_compressedSize(
            self_: *mut whiteout_MpqFileInfo,
            value: u32,
        );
        pub fn whiteout_mpq_MpqFileInfo_get_uncompressedSize(
            self_: *mut whiteout_MpqFileInfo,
        ) -> u32;
        pub fn whiteout_mpq_MpqFileInfo_set_uncompressedSize(
            self_: *mut whiteout_MpqFileInfo,
            value: u32,
        );
        pub fn whiteout_mpq_MpqFileInfo_get_flags(self_: *mut whiteout_MpqFileInfo) -> i32;
        pub fn whiteout_mpq_MpqFileInfo_set_flags(self_: *mut whiteout_MpqFileInfo, value: i32);
        pub fn whiteout_mpq_MpqFileInfo_get_locale(self_: *mut whiteout_MpqFileInfo) -> u16;
        pub fn whiteout_mpq_MpqFileInfo_set_locale(self_: *mut whiteout_MpqFileInfo, value: u16);
        // ArchiveInfo
        pub fn whiteout_mpq_MpqArchiveInfo_new() -> *mut whiteout_MpqArchiveInfo;
        pub fn whiteout_mpq_MpqArchiveInfo_delete(self_: *mut whiteout_MpqArchiveInfo);
        pub fn whiteout_mpq_MpqArchiveInfo_get_formatVersion(
            self_: *mut whiteout_MpqArchiveInfo,
        ) -> u16;
        pub fn whiteout_mpq_MpqArchiveInfo_set_formatVersion(
            self_: *mut whiteout_MpqArchiveInfo,
            value: u16,
        );
        pub fn whiteout_mpq_MpqArchiveInfo_get_hashTableEntries(
            self_: *mut whiteout_MpqArchiveInfo,
        ) -> u32;
        pub fn whiteout_mpq_MpqArchiveInfo_set_hashTableEntries(
            self_: *mut whiteout_MpqArchiveInfo,
            value: u32,
        );
        pub fn whiteout_mpq_MpqArchiveInfo_get_blockTableEntries(
            self_: *mut whiteout_MpqArchiveInfo,
        ) -> u32;
        pub fn whiteout_mpq_MpqArchiveInfo_set_blockTableEntries(
            self_: *mut whiteout_MpqArchiveInfo,
            value: u32,
        );
        pub fn whiteout_mpq_MpqArchiveInfo_get_sectorSize(
            self_: *mut whiteout_MpqArchiveInfo,
        ) -> u32;
        pub fn whiteout_mpq_MpqArchiveInfo_set_sectorSize(
            self_: *mut whiteout_MpqArchiveInfo,
            value: u32,
        );
        pub fn whiteout_mpq_MpqArchiveInfo_get_archiveSize(
            self_: *mut whiteout_MpqArchiveInfo,
        ) -> u64;
        pub fn whiteout_mpq_MpqArchiveInfo_set_archiveSize(
            self_: *mut whiteout_MpqArchiveInfo,
            value: u64,
        );
        // WriteOptions
        pub fn whiteout_mpq_MpqWriteOptions_new() -> *mut whiteout_MpqWriteOptions;
        pub fn whiteout_mpq_MpqWriteOptions_delete(self_: *mut whiteout_MpqWriteOptions);
        pub fn whiteout_mpq_MpqWriteOptions_get_compression(
            self_: *mut whiteout_MpqWriteOptions,
        ) -> i32;
        pub fn whiteout_mpq_MpqWriteOptions_set_compression(
            self_: *mut whiteout_MpqWriteOptions,
            value: i32,
        );
        pub fn whiteout_mpq_MpqWriteOptions_get_locale(self_: *mut whiteout_MpqWriteOptions)
            -> u16;
        pub fn whiteout_mpq_MpqWriteOptions_set_locale(
            self_: *mut whiteout_MpqWriteOptions,
            value: u16,
        );
        pub fn whiteout_mpq_MpqWriteOptions_get_encrypt(
            self_: *mut whiteout_MpqWriteOptions,
        ) -> i32;
        pub fn whiteout_mpq_MpqWriteOptions_set_encrypt(
            self_: *mut whiteout_MpqWriteOptions,
            value: i32,
        );
        pub fn whiteout_mpq_MpqWriteOptions_get_singleUnit(
            self_: *mut whiteout_MpqWriteOptions,
        ) -> i32;
        pub fn whiteout_mpq_MpqWriteOptions_set_singleUnit(
            self_: *mut whiteout_MpqWriteOptions,
            value: i32,
        );
        // CreateOptions
        pub fn whiteout_mpq_MpqCreateOptions_new() -> *mut whiteout_MpqCreateOptions;
        pub fn whiteout_mpq_MpqCreateOptions_delete(self_: *mut whiteout_MpqCreateOptions);
        pub fn whiteout_mpq_MpqCreateOptions_get_version(
            self_: *mut whiteout_MpqCreateOptions,
        ) -> i32;
        pub fn whiteout_mpq_MpqCreateOptions_set_version(
            self_: *mut whiteout_MpqCreateOptions,
            value: i32,
        );
        pub fn whiteout_mpq_MpqCreateOptions_get_hashTableSize(
            self_: *mut whiteout_MpqCreateOptions,
        ) -> u32;
        pub fn whiteout_mpq_MpqCreateOptions_set_hashTableSize(
            self_: *mut whiteout_MpqCreateOptions,
            value: u32,
        );
        pub fn whiteout_mpq_MpqCreateOptions_get_sectorSizeShift(
            self_: *mut whiteout_MpqCreateOptions,
        ) -> u16;
        pub fn whiteout_mpq_MpqCreateOptions_set_sectorSizeShift(
            self_: *mut whiteout_MpqCreateOptions,
            value: u16,
        );
        // Storage
        pub fn whiteout_mpq_MpqStorage_delete(self_: *mut whiteout_MpqStorage);
        pub fn whiteout_mpq_MpqStorage_open(
            path: *const core::ffi::c_char,
            pool: *mut core::ffi::c_void,
        ) -> *mut whiteout_MpqStorage;
        pub fn whiteout_mpq_MpqStorage_create(
            opts: *mut whiteout_MpqCreateOptions,
            pool: *mut core::ffi::c_void,
        ) -> *mut whiteout_MpqStorage;
        pub fn whiteout_mpq_MpqStorage_close(self_: *mut whiteout_MpqStorage);
        pub fn whiteout_mpq_MpqStorage_readFile(
            self_: *mut whiteout_MpqStorage,
            name: *const core::ffi::c_char,
        ) -> RawBytes;
        pub fn whiteout_mpq_MpqStorage_readFile_name_locale(
            self_: *mut whiteout_MpqStorage,
            name: *const core::ffi::c_char,
            locale: u16,
        ) -> RawBytes;
        pub fn whiteout_mpq_MpqStorage_fileExists(
            self_: *mut whiteout_MpqStorage,
            name: *const core::ffi::c_char,
        ) -> i32;
        pub fn whiteout_mpq_MpqStorage_fileInfo(
            self_: *mut whiteout_MpqStorage,
            name: *const core::ffi::c_char,
        ) -> *mut whiteout_MpqFileInfo;
        pub fn whiteout_mpq_MpqStorage_archiveInfo(
            self_: *mut whiteout_MpqStorage,
        ) -> *mut whiteout_MpqArchiveInfo;
        pub fn whiteout_mpq_MpqStorage_listFiles(
            self_: *mut whiteout_MpqStorage,
        ) -> *mut whiteout_StringList;
        pub fn whiteout_mpq_MpqStorage_writeFile(
            self_: *mut whiteout_MpqStorage,
            name: *const u8,
            name_size: usize,
            data: *const u8,
            data_size: usize,
            opts: *mut whiteout_MpqWriteOptions,
        ) -> i32;
        pub fn whiteout_mpq_MpqStorage_deleteFile(
            self_: *mut whiteout_MpqStorage,
            name: *const core::ffi::c_char,
        ) -> i32;
        pub fn whiteout_mpq_MpqStorage_save(self_: *mut whiteout_MpqStorage) -> i32;
        pub fn whiteout_mpq_MpqStorage_save_path(
            self_: *mut whiteout_MpqStorage,
            path: *const core::ffi::c_char,
        ) -> i32;
        // FileSystem
        pub fn whiteout_mpq_MpqFileSystem_new_storage(
            _0: *mut core::ffi::c_void,
        ) -> *mut whiteout_MpqFileSystem;
        pub fn whiteout_mpq_MpqFileSystem_delete(self_: *mut whiteout_MpqFileSystem);
        pub fn whiteout_mpq_MpqFileSystem_readFile(
            self_: *mut whiteout_MpqFileSystem,
            path: *const core::ffi::c_char,
        ) -> RawBytes;
        pub fn whiteout_mpq_MpqFileSystem_writeFile(
            self_: *mut whiteout_MpqFileSystem,
            path: *const core::ffi::c_char,
            data: *const u8,
            data_size: usize,
        ) -> i32;
        pub fn whiteout_mpq_MpqFileSystem_fileExists(
            self_: *mut whiteout_MpqFileSystem,
            path: *const core::ffi::c_char,
        ) -> i32;
    }
}