whiteoutlib 0.1.6

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
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
// 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 casc --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};

/// Root manifest format.
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RootFormat {
    /// Could not determine format.
    Unknown = 0,
    /// World of Warcraft root (FileDataId-based, legacy MFST).
    Wow = 1,
    /// World of Warcraft root (FileDataId-based, TVFS-backed, 11.x+).
    WowTvfs = 2,
    /// Diablo III root (hierarchical directory).
    Diablo3 = 3,
    /// Diablo IV root (TVFS enriched with CoreTOC paths).
    Diablo4 = 4,
    /// TVFS prefix-tree root (WC3 Reforged and general purpose).
    Tvfs = 5,
    /// MNDX trie-based root (StarCraft II, Heroes of the Storm).
    Mndx = 6,
    /// Overwatch root (text manifest + CMF content manifests).
    Overwatch = 7,
    /// Agent/S1 text root (SC:R, Hearthstone, etc.).
    Agent = 8,
}

impl TryFrom<i32> for RootFormat {
    type Error = crate::Error;
    fn try_from(v: i32) -> Result<Self, crate::Error> {
        match v {
            0 => Ok(RootFormat::Unknown),
            1 => Ok(RootFormat::Wow),
            2 => Ok(RootFormat::WowTvfs),
            3 => Ok(RootFormat::Diablo3),
            4 => Ok(RootFormat::Diablo4),
            5 => Ok(RootFormat::Tvfs),
            6 => Ok(RootFormat::Mndx),
            7 => Ok(RootFormat::Overwatch),
            8 => Ok(RootFormat::Agent),
            other => Err(crate::Error::UnknownEnum {
                name: "RootFormat",
                value: other,
            }),
        }
    }
}

/// Hint for disambiguating FileDataId-based lookups. In Diablo IV, a single SNO ID can map to multiple entries (child, meta, payload, etc.).  The hint tells the root which variant to return. Roots that don't use sub-types (e.g. WoW) ignore the hint.
#[repr(i32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FileIdHint {
    /// Default — return the primary entry (child/main content).
    None = 0,
    /// Metadata entry.
    Meta = 1,
    /// Full-resolution payload.
    Payload = 2,
    /// Low-resolution payload.
    Paylow = 3,
    /// Medium-resolution payload.
    Paymed = 4,
}

impl TryFrom<i32> for FileIdHint {
    type Error = crate::Error;
    fn try_from(v: i32) -> Result<Self, crate::Error> {
        match v {
            0 => Ok(FileIdHint::None),
            1 => Ok(FileIdHint::Meta),
            2 => Ok(FileIdHint::Payload),
            3 => Ok(FileIdHint::Paylow),
            4 => Ok(FileIdHint::Paymed),
            other => Err(crate::Error::UnknownEnum {
                name: "FileIdHint",
                value: other,
            }),
        }
    }
}

/// Entry returned by enumerate/list operations.
#[derive(Clone, Debug, PartialEq)]
pub struct FindEntry {
    pub c_key: Vec<u8>,
    pub file_size: u64,
    pub locale_flags: u32,
    pub content_flags: u32,
    pub file_data_id: i32,
    pub path: String,
}

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

impl Drop for CreateOptions {
    fn drop(&mut self) {
        // SAFETY: `raw` came from a native constructor and Drop runs once.
        unsafe { ffi::whiteout_casc_CascCreateOptions_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_CascCreateOptions) -> 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_casc_CascCreateOptions_new();
            Self::from_raw(raw).expect("native CreateOptions allocation failed")
        }
    }

    pub fn product(&self) -> String {
        // SAFETY: the native side hands over an owned CString.
        unsafe {
            crate::support::take_string(ffi::whiteout_casc_CascCreateOptions_get_product(
                self.raw.as_ptr(),
            ))
        }
    }

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

    pub fn version(&self) -> String {
        // SAFETY: the native side hands over an owned CString.
        unsafe {
            crate::support::take_string(ffi::whiteout_casc_CascCreateOptions_get_version(
                self.raw.as_ptr(),
            ))
        }
    }

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

    /// 1 GB.
    pub fn archive_max_size(&self) -> u32 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_casc_CascCreateOptions_get_archiveMaxSize(self.raw.as_ptr()) }
    }

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

    /// 64 KB.
    pub fn blte_frame_size(&self) -> u32 {
        // SAFETY: plain scalar read through a live handle.
        unsafe { ffi::whiteout_casc_CascCreateOptions_get_blteFrameSize(self.raw.as_ptr()) }
    }

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

    pub fn root_format(&self) -> RootFormat {
        // SAFETY: scalar read; the discriminant is validated below.
        unsafe { ffi::whiteout_casc_CascCreateOptions_get_rootFormat(self.raw.as_ptr()) }
            .try_into()
            .expect("unknown enum discriminant from the native library")
    }

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

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

/// Options for writing a file into a CASC storage.
#[derive(Clone, Debug, PartialEq)]
pub struct WriteOptions {
    pub locale_flags: u32,
    pub content_flags: u32,
    pub compress: bool,
}

impl Default for WriteOptions {
    fn default() -> Self {
        // SAFETY: `_new` always returns a live handle; freed before return.
        unsafe {
            let h = ffi::whiteout_casc_CascWriteOptions_new();
            let out = WriteOptions {
                locale_flags: ffi::whiteout_casc_CascWriteOptions_get_localeFlags(h),
                content_flags: ffi::whiteout_casc_CascWriteOptions_get_contentFlags(h),
                compress: ffi::whiteout_casc_CascWriteOptions_get_compress(h) != 0,
            };
            ffi::whiteout_casc_CascWriteOptions_delete(h);
            out
        }
    }
}

impl WriteOptions {
    /// Build a native handle carrying these values. Caller frees it.
    #[allow(dead_code)] // consumed once the methods taking these options bind
    pub(crate) unsafe fn to_native(&self) -> *mut ffi::whiteout_CascWriteOptions {
        unsafe {
            let h = ffi::whiteout_casc_CascWriteOptions_new();
            ffi::whiteout_casc_CascWriteOptions_set_localeFlags(h, self.locale_flags);
            ffi::whiteout_casc_CascWriteOptions_set_contentFlags(h, self.content_flags);
            ffi::whiteout_casc_CascWriteOptions_set_compress(h, if self.compress { 1 } else { 0 });
            h
        }
    }

    /// Free a handle produced by [`Self::to_native`].
    ///
    /// # Safety
    /// `h` must have come from `to_native` and not been freed already.
    #[allow(dead_code)]
    pub(crate) unsafe fn free_native(h: *mut ffi::whiteout_CascWriteOptions) {
        unsafe { ffi::whiteout_casc_CascWriteOptions_delete(h) }
    }
}

/// Unified read-only CASC storage (local disk or CDN)
///
/// Storage is the primary entry point for reading CASC archives. Use `open()` for local disk, `openOnline()` for CDN-backed access. The same public read API works identically regardless of backing store.
///
/// All public methods are thread-safe: read operations acquire a shared lock.
///
/// Uses the PImpl (Pointer to Implementation) idiom to hide internals.
///
/// @see StorageWritable for write + persist operations.
pub struct Storage {
    pub(crate) raw: core::ptr::NonNull<ffi::whiteout_CascStorage>,
}

impl Drop for Storage {
    fn drop(&mut self) {
        // SAFETY: `raw` came from a native constructor and Drop runs once.
        unsafe { ffi::whiteout_casc_CascStorage_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_CascStorage) -> 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 local CASC storage. @param path Path to the game's top-level directory (containing .build.info) or its Data subdirectory. @param pool Optional WorkerPool for parallel I/O (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_casc_CascStorage_open(
                path_cstr.as_ptr(),
                pool.map_or(core::ptr::null_mut(), |v| v.as_ptr()),
            ))
        }
    }

    /// @overload Open with locale mask.
    pub fn open_path_locale_mask_pool(
        path: &str,
        locale_mask: u32,
        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_casc_CascStorage_open_path_localeMask_pool(
                path_cstr.as_ptr(),
                locale_mask,
                pool.map_or(core::ptr::null_mut(), |v| v.as_ptr()),
            ))
        }
    }

    /// @overload Open a specific product from a multi-product `.build.info`. @param product Product code selecting the build, e.g. "w3" (Warcraft III retail) vs "w3t" (its PTR). Matched case-insensitively against the active builds; empty selects the first active build. See OpenOptions::product. Open fails if the product has no active build.
    pub fn open_path_product_pool(
        path: &str,
        product: &str,
        pool: Option<&crate::interfaces::HostWorkerPool>,
    ) -> Option<Storage> {
        let path_cstr = std::ffi::CString::new(path).unwrap_or_default();
        let product_cstr = std::ffi::CString::new(product).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Storage::from_raw(ffi::whiteout_casc_CascStorage_open_path_product_pool(
                path_cstr.as_ptr(),
                product_cstr.as_ptr(),
                pool.map_or(core::ptr::null_mut(), |v| v.as_ptr()),
            ))
        }
    }

    /// Release all resources and invalidate the storage.
    pub fn close(&mut self) {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_casc_CascStorage_close(self.raw.as_ptr());
        }
    }

    /// @return True if this storage reads from local disk.
    pub fn is_local(&self) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe { ffi::whiteout_casc_CascStorage_isLocal(self.raw.as_ptr()) != 0 }
    }

    /// @return True if this storage reads from CDN.
    pub fn is_online(&self) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe { ffi::whiteout_casc_CascStorage_isOnline(self.raw.as_ptr()) != 0 }
    }

    /// @return True if this storage has a write overlay (StorageWritable).
    pub fn is_writable(&self) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe { ffi::whiteout_casc_CascStorage_isWritable(self.raw.as_ptr()) != 0 }
    }

    /// @return The root manifest format, or RootFormat::Unknown.
    pub fn root_format(&self) -> RootFormat {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            RootFormat::try_from(ffi::whiteout_casc_CascStorage_rootFormat(self.raw.as_ptr()))
                .expect("unknown enum discriminant from the native library (ABI version skew)")
        }
    }

    /// @return File contents, or std::nullopt if the path is not found.
    pub fn read_file(&self, casc_path: &str) -> Option<Bytes> {
        let casc_path_cstr = std::ffi::CString::new(casc_path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Bytes::from_raw(ffi::whiteout_casc_CascStorage_readFile(
                self.raw.as_ptr(),
                casc_path_cstr.as_ptr(),
            ))
        }
    }

    /// @overload Read a file by path with locale and open flags.
    pub fn read_file_casc_path_locale_flags_open_flags(
        &self,
        casc_path: &str,
        locale_flags: u32,
        open_flags: u32,
    ) -> Option<Bytes> {
        let casc_path_cstr = std::ffi::CString::new(casc_path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Bytes::from_raw(
                ffi::whiteout_casc_CascStorage_readFile_cascPath_localeFlags_openFlags(
                    self.raw.as_ptr(),
                    casc_path_cstr.as_ptr(),
                    locale_flags,
                    open_flags,
                ),
            )
        }
    }

    /// @overload Read a file by WoW-style FileDataId.
    pub fn read_file_file_id_hint(&self, file_id: i32, hint: FileIdHint) -> Option<Bytes> {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Bytes::from_raw(ffi::whiteout_casc_CascStorage_readFile_fileId_hint(
                self.raw.as_ptr(),
                file_id,
                hint as i32,
            ))
        }
    }

    /// @overload Read a file by FileDataId with locale and open flags.
    pub fn read_file_file_id_locale_flags_open_flags_hint(
        &self,
        file_id: i32,
        locale_flags: u32,
        open_flags: u32,
        hint: FileIdHint,
    ) -> Option<Bytes> {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            Bytes::from_raw(
                ffi::whiteout_casc_CascStorage_readFile_fileId_localeFlags_openFlags_hint(
                    self.raw.as_ptr(),
                    file_id,
                    locale_flags,
                    open_flags,
                    hint as i32,
                ),
            )
        }
    }

    /// @return True if the path resolves to a known file.
    pub fn file_exists(&self, casc_path: &str) -> bool {
        let casc_path_cstr = std::ffi::CString::new(casc_path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_casc_CascStorage_fileExists(self.raw.as_ptr(), casc_path_cstr.as_ptr())
                != 0
        }
    }

    /// @overload Check existence by FileDataId.
    pub fn file_exists_file_id_hint(&self, file_id: i32, hint: FileIdHint) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_casc_CascStorage_fileExists_fileId_hint(
                self.raw.as_ptr(),
                file_id,
                hint as i32,
            ) != 0
        }
    }

    /// @return Uncompressed file size, or std::nullopt if not found.
    pub fn file_size(&self, casc_path: &str) -> Option<u64> {
        let casc_path_cstr = std::ffi::CString::new(casc_path).unwrap_or_default();
        let mut __v: u64 = 0;
        // SAFETY: `__v` is a live local, written by the
        // native side only when it returns 1.
        let __has = unsafe {
            ffi::whiteout_casc_CascStorage_fileSize(
                self.raw.as_ptr(),
                casc_path_cstr.as_ptr(),
                &mut __v,
            )
        };
        (__has != 0).then_some(__v)
    }

    /// @overload
    pub fn file_size_file_id_hint(&self, file_id: i32, hint: FileIdHint) -> Option<u64> {
        let mut __v: u64 = 0;
        // SAFETY: `__v` is a live local, written by the
        // native side only when it returns 1.
        let __has = unsafe {
            ffi::whiteout_casc_CascStorage_fileSize_fileId_hint(
                self.raw.as_ptr(),
                file_id,
                hint as i32,
                &mut __v,
            )
        };
        (__has != 0).then_some(__v)
    }

    /// @return All known file paths.
    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_casc_CascStorage_listFiles(self.raw.as_ptr());
            if list.is_null() {
                return Vec::new();
            }
            let n = ffi::whiteout_casc_StringList_size(list);
            let out = (0..n)
                .map(|i| crate::support::take_string(ffi::whiteout_casc_StringList_at(list, i)))
                .collect();
            ffi::whiteout_casc_StringList_delete(list);
            out
        }
    }

    /// @return All entries with metadata.
    pub fn list_entries(&self) -> Vec<FindEntry> {
        // SAFETY: one call materialises the snapshot; each
        // field is read by index and the snapshot is freed
        // before returning. Reading is O(1) per element.
        unsafe {
            let snap = ffi::whiteout_casc_CascStorage_listEntries_snapshot(self.raw.as_ptr());
            if snap.is_null() {
                return Vec::new();
            }
            let n = ffi::whiteout_casc_CascStorage_listEntries_count(snap);
            let mut out = Vec::with_capacity(n);
            for i in 0..n {
                out.push(FindEntry {
                    c_key: crate::support::Bytes::from_raw(
                        ffi::whiteout_casc_CascStorage_listEntries_cKey_at(snap, i),
                    )
                    .map(|b| b.to_vec())
                    .unwrap_or_default(),
                    file_size: ffi::whiteout_casc_CascStorage_listEntries_fileSize_at(snap, i),
                    locale_flags: ffi::whiteout_casc_CascStorage_listEntries_localeFlags_at(
                        snap, i,
                    ),
                    content_flags: ffi::whiteout_casc_CascStorage_listEntries_contentFlags_at(
                        snap, i,
                    ),
                    file_data_id: ffi::whiteout_casc_CascStorage_listEntries_fileDataId_at(snap, i),
                    path: crate::support::take_string(
                        ffi::whiteout_casc_CascStorage_listEntries_path_at(snap, i),
                    ),
                });
            }
            ffi::whiteout_casc_CascStorage_listEntries_free(snap);
            out
        }
    }

    /// @return Total number of files in the root manifest.
    pub fn total_file_count(&self) -> Option<u32> {
        let mut __v: u32 = 0;
        // SAFETY: `__v` is a live local, written by the
        // native side only when it returns 1.
        let __has =
            unsafe { ffi::whiteout_casc_CascStorage_totalFileCount(self.raw.as_ptr(), &mut __v) };
        (__has != 0).then_some(__v)
    }

    /// Import encryption keys from a formatted string (one per line).
    pub fn import_keys_from_string(&mut self, key_list: &str) -> bool {
        let key_list_cstr = std::ffi::CString::new(key_list).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_casc_CascStorage_importKeysFromString(
                self.raw.as_ptr(),
                key_list_cstr.as_ptr(),
            ) != 0
        }
    }

    /// Import encryption keys from a file.
    pub fn import_keys_from_file(&mut self, key_file_path: &str) -> bool {
        let key_file_path_cstr = std::ffi::CString::new(key_file_path).unwrap_or_default();
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_casc_CascStorage_importKeysFromFile(
                self.raw.as_ptr(),
                key_file_path_cstr.as_ptr(),
            ) != 0
        }
    }

    /// @return The encryption key for @p keyName, or std::nullopt if not found.
    pub fn find_encryption_key(&self, key_name: u64) -> Option<[u8; 16]> {
        let mut __v: [u8; 16] = Default::default();
        // SAFETY: `__v` is a live local of exactly the
        // length the native side writes.
        let __has = unsafe {
            ffi::whiteout_casc_CascStorage_findEncryptionKey(
                self.raw.as_ptr(),
                key_name,
                __v.as_mut_ptr(),
            )
        };
        (__has != 0).then_some(__v)
    }

    /// Clear the in-memory decoded-data cache (container cache).
    pub fn flush_cache(&mut self) {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_casc_CascStorage_flushCache(self.raw.as_ptr());
        }
    }

    /// Force every deferred load (encoding, root, VFS, index files, orphan bitvector) to resolve. Idempotent.
    pub fn prefetch(&mut self) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe { ffi::whiteout_casc_CascStorage_prefetch(self.raw.as_ptr()) != 0 }
    }

    /// @return Last error code (thread-local).
    pub fn last_error() -> u32 {
        // SAFETY: handle is live for the duration of the call.
        unsafe { ffi::whiteout_casc_CascStorage_lastError() }
    }
}

/// Writable CASC storage (read + write + save)
///
/// Inherits all read operations from Storage. Adds write overlay and persist-to-disk support.
///
/// Only local-backed storages can be writable (CDN is read-only).
///
/// extends=whiteout::storages::casc::Storage
pub struct StorageWritable {
    pub(crate) raw: core::ptr::NonNull<ffi::whiteout_CascStorageWritable>,
}

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

impl StorageWritable {
    /// # 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_CascStorageWritable) -> Option<Self> {
        core::ptr::NonNull::new(raw).map(|raw| StorageWritable { 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 StorageWritable {}

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

impl StorageWritable {
    /// Create a new empty storage in memory.
    ///
    /// No file is written to disk until save() is called.
    ///
    /// @param opts Creation options (product name, version, root format). @param pool Optional WorkerPool for parallel I/O. @return A valid empty StorageWritable ready for writeFile() calls.
    pub fn create(
        opts: &CreateOptions,
        pool: Option<&crate::interfaces::HostWorkerPool>,
    ) -> Option<StorageWritable> {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            StorageWritable::from_raw(ffi::whiteout_casc_CascStorageWritable_create(
                opts.raw.as_ptr(),
                pool.map_or(core::ptr::null_mut(), |v| v.as_ptr()),
            ))
        }
    }

    /// Reserve a file-data-ID for a named asset.
    ///
    /// Allocates the next available file-data-ID and associates it with @p name.  The interpretation of @p name depends on the root format:
    ///
    /// - **WoW / WoWTvfs**: @p name is a full CASC path (e.g. `"Base\\creatures\\beast\\beast.m2"`). - **Diablo 3 / Diablo 4 / TVFS**: @p name is `"asset_name.ext"`, where the extension determines the SNO group.  A CoreTOC entry is created automatically.
    ///
    /// Returns @c std::nullopt if the name already exists in the root or in a previous reservation.
    ///
    /// @code auto id = storage.reserveFileId("my_beast.app"); if (id) storage.writeFile(*id, data); @endcode
    pub fn reserve_file_id(&mut self, name: &str) -> Option<u32> {
        let name_cstr = std::ffi::CString::new(name).unwrap_or_default();
        let mut __v: u32 = 0;
        // SAFETY: `__v` is a live local, written by the
        // native side only when it returns 1.
        let __has = unsafe {
            ffi::whiteout_casc_CascStorageWritable_reserveFileId(
                self.raw.as_ptr(),
                name_cstr.as_ptr(),
                &mut __v,
            )
        };
        (__has != 0).then_some(__v)
    }

    /// Write a file by path.
    ///
    /// Data is stored in an in-memory overlay until save() is called.
    ///
    /// @param path CASC path for the new or updated file. @param data File contents. @param opts Write options (locale, content flags, compression). @return True on success.
    pub fn write_file(&mut self, path: &str, data: &[u8], opts: &WriteOptions) -> bool {
        let path_cstr = std::ffi::CString::new(path).unwrap_or_default();
        let opts_native = unsafe { opts.to_native() };
        // SAFETY: handle is live for the call; the staged
        // option handles are freed immediately after.
        unsafe {
            let __r = ffi::whiteout_casc_CascStorageWritable_writeFile(
                self.raw.as_ptr(),
                path_cstr.as_ptr(),
                data.as_ptr(),
                data.len(),
                opts_native,
            ) != 0;
            WriteOptions::free_native(opts_native);
            __r
        }
    }

    /// @overload Write a file by FileDataId.
    pub fn write_file_file_id_data_opts_hint(
        &mut self,
        file_id: i32,
        data: &[u8],
        opts: &WriteOptions,
        hint: FileIdHint,
    ) -> bool {
        let opts_native = unsafe { opts.to_native() };
        // SAFETY: handle is live for the call; the staged
        // option handles are freed immediately after.
        unsafe {
            let __r = ffi::whiteout_casc_CascStorageWritable_writeFile_fileId_data_opts_hint(
                self.raw.as_ptr(),
                file_id,
                data.as_ptr(),
                data.len(),
                opts_native,
                hint as i32,
            ) != 0;
            WriteOptions::free_native(opts_native);
            __r
        }
    }

    /// Mark a file for deletion (effective on next save).
    pub fn delete_file(&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_casc_CascStorageWritable_deleteFile(self.raw.as_ptr(), path_cstr.as_ptr())
                != 0
        }
    }

    /// @overload
    pub fn delete_file_file_id_hint(&mut self, file_id: i32, hint: FileIdHint) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe {
            ffi::whiteout_casc_CascStorageWritable_deleteFile_fileId_hint(
                self.raw.as_ptr(),
                file_id,
                hint as i32,
            ) != 0
        }
    }

    /// Persist all pending changes to disk (writes to the original location).
    pub fn save(&mut self) -> bool {
        // SAFETY: handle is live for the duration of the call.
        unsafe { ffi::whiteout_casc_CascStorageWritable_save(self.raw.as_ptr()) != 0 }
    }

    /// @overload Persist to a specific output path.
    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_casc_CascStorageWritable_save_path(self.raw.as_ptr(), path_cstr.as_ptr())
                != 0
        }
    }
}

// Not yet bound (shape unsupported by the emitter):
//   - Storage::open_opts (parameter shape)

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

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

    #[repr(C)]
    pub struct whiteout_CascCreateOptions {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_CascWriteOptions {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_CascStorage {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_CascStorageWritable {
        _private: [u8; 0],
    }
    #[repr(C)]
    pub struct whiteout_StringList {
        _private: [u8; 0],
    }

    extern "C" {
        pub fn whiteout_casc_StringList_size(self_: *mut whiteout_StringList) -> usize;
        pub fn whiteout_casc_StringList_at(
            self_: *mut whiteout_StringList,
            index: usize,
        ) -> RawCString;
        pub fn whiteout_casc_StringList_delete(self_: *mut whiteout_StringList);
        // CreateOptions
        pub fn whiteout_casc_CascCreateOptions_new() -> *mut whiteout_CascCreateOptions;
        pub fn whiteout_casc_CascCreateOptions_delete(self_: *mut whiteout_CascCreateOptions);
        pub fn whiteout_casc_CascCreateOptions_get_product(
            self_: *mut whiteout_CascCreateOptions,
        ) -> RawCString;
        pub fn whiteout_casc_CascCreateOptions_set_product(
            self_: *mut whiteout_CascCreateOptions,
            value: *const core::ffi::c_char,
        );
        pub fn whiteout_casc_CascCreateOptions_get_version(
            self_: *mut whiteout_CascCreateOptions,
        ) -> RawCString;
        pub fn whiteout_casc_CascCreateOptions_set_version(
            self_: *mut whiteout_CascCreateOptions,
            value: *const core::ffi::c_char,
        );
        pub fn whiteout_casc_CascCreateOptions_get_archiveMaxSize(
            self_: *mut whiteout_CascCreateOptions,
        ) -> u32;
        pub fn whiteout_casc_CascCreateOptions_set_archiveMaxSize(
            self_: *mut whiteout_CascCreateOptions,
            value: u32,
        );
        pub fn whiteout_casc_CascCreateOptions_get_blteFrameSize(
            self_: *mut whiteout_CascCreateOptions,
        ) -> u32;
        pub fn whiteout_casc_CascCreateOptions_set_blteFrameSize(
            self_: *mut whiteout_CascCreateOptions,
            value: u32,
        );
        pub fn whiteout_casc_CascCreateOptions_get_rootFormat(
            self_: *mut whiteout_CascCreateOptions,
        ) -> i32;
        pub fn whiteout_casc_CascCreateOptions_set_rootFormat(
            self_: *mut whiteout_CascCreateOptions,
            value: i32,
        );
        // WriteOptions
        pub fn whiteout_casc_CascWriteOptions_new() -> *mut whiteout_CascWriteOptions;
        pub fn whiteout_casc_CascWriteOptions_delete(self_: *mut whiteout_CascWriteOptions);
        pub fn whiteout_casc_CascWriteOptions_get_localeFlags(
            self_: *mut whiteout_CascWriteOptions,
        ) -> u32;
        pub fn whiteout_casc_CascWriteOptions_set_localeFlags(
            self_: *mut whiteout_CascWriteOptions,
            value: u32,
        );
        pub fn whiteout_casc_CascWriteOptions_get_contentFlags(
            self_: *mut whiteout_CascWriteOptions,
        ) -> u32;
        pub fn whiteout_casc_CascWriteOptions_set_contentFlags(
            self_: *mut whiteout_CascWriteOptions,
            value: u32,
        );
        pub fn whiteout_casc_CascWriteOptions_get_compress(
            self_: *mut whiteout_CascWriteOptions,
        ) -> i32;
        pub fn whiteout_casc_CascWriteOptions_set_compress(
            self_: *mut whiteout_CascWriteOptions,
            value: i32,
        );
        // Storage
        pub fn whiteout_casc_CascStorage_delete(self_: *mut whiteout_CascStorage);
        pub fn whiteout_casc_CascStorage_open(
            path: *const core::ffi::c_char,
            pool: *mut core::ffi::c_void,
        ) -> *mut whiteout_CascStorage;
        pub fn whiteout_casc_CascStorage_open_path_localeMask_pool(
            path: *const core::ffi::c_char,
            locale_mask: u32,
            pool: *mut core::ffi::c_void,
        ) -> *mut whiteout_CascStorage;
        pub fn whiteout_casc_CascStorage_open_path_product_pool(
            path: *const core::ffi::c_char,
            product: *const core::ffi::c_char,
            pool: *mut core::ffi::c_void,
        ) -> *mut whiteout_CascStorage;
        pub fn whiteout_casc_CascStorage_close(self_: *mut whiteout_CascStorage);
        pub fn whiteout_casc_CascStorage_isLocal(self_: *mut whiteout_CascStorage) -> i32;
        pub fn whiteout_casc_CascStorage_isOnline(self_: *mut whiteout_CascStorage) -> i32;
        pub fn whiteout_casc_CascStorage_isWritable(self_: *mut whiteout_CascStorage) -> i32;
        pub fn whiteout_casc_CascStorage_rootFormat(self_: *mut whiteout_CascStorage) -> i32;
        pub fn whiteout_casc_CascStorage_readFile(
            self_: *mut whiteout_CascStorage,
            casc_path: *const core::ffi::c_char,
        ) -> RawBytes;
        pub fn whiteout_casc_CascStorage_readFile_cascPath_localeFlags_openFlags(
            self_: *mut whiteout_CascStorage,
            casc_path: *const core::ffi::c_char,
            locale_flags: u32,
            open_flags: u32,
        ) -> RawBytes;
        pub fn whiteout_casc_CascStorage_readFile_fileId_hint(
            self_: *mut whiteout_CascStorage,
            file_id: i32,
            hint: i32,
        ) -> RawBytes;
        pub fn whiteout_casc_CascStorage_readFile_fileId_localeFlags_openFlags_hint(
            self_: *mut whiteout_CascStorage,
            file_id: i32,
            locale_flags: u32,
            open_flags: u32,
            hint: i32,
        ) -> RawBytes;
        pub fn whiteout_casc_CascStorage_fileExists(
            self_: *mut whiteout_CascStorage,
            casc_path: *const core::ffi::c_char,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_fileExists_fileId_hint(
            self_: *mut whiteout_CascStorage,
            file_id: i32,
            hint: i32,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_fileSize(
            self_: *mut whiteout_CascStorage,
            casc_path: *const core::ffi::c_char,
            out_value: *mut u64,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_fileSize_fileId_hint(
            self_: *mut whiteout_CascStorage,
            file_id: i32,
            hint: i32,
            out_value: *mut u64,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_listFiles(
            self_: *mut whiteout_CascStorage,
        ) -> *mut whiteout_StringList;
        pub fn whiteout_casc_CascStorage_listEntries_snapshot(
            self_: *mut whiteout_CascStorage,
        ) -> *mut core::ffi::c_void;
        pub fn whiteout_casc_CascStorage_listEntries_count(
            snapshot: *mut core::ffi::c_void,
        ) -> usize;
        pub fn whiteout_casc_CascStorage_listEntries_cKey_at(
            snapshot: *mut core::ffi::c_void,
            index: usize,
        ) -> RawBytes;
        pub fn whiteout_casc_CascStorage_listEntries_fileSize_at(
            snapshot: *mut core::ffi::c_void,
            index: usize,
        ) -> u64;
        pub fn whiteout_casc_CascStorage_listEntries_localeFlags_at(
            snapshot: *mut core::ffi::c_void,
            index: usize,
        ) -> u32;
        pub fn whiteout_casc_CascStorage_listEntries_contentFlags_at(
            snapshot: *mut core::ffi::c_void,
            index: usize,
        ) -> u32;
        pub fn whiteout_casc_CascStorage_listEntries_fileDataId_at(
            snapshot: *mut core::ffi::c_void,
            index: usize,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_listEntries_path_at(
            snapshot: *mut core::ffi::c_void,
            index: usize,
        ) -> RawCString;
        pub fn whiteout_casc_CascStorage_listEntries_free(snapshot: *mut core::ffi::c_void);
        pub fn whiteout_casc_CascStorage_totalFileCount(
            self_: *mut whiteout_CascStorage,
            out_value: *mut u32,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_importKeysFromString(
            self_: *mut whiteout_CascStorage,
            key_list: *const core::ffi::c_char,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_importKeysFromFile(
            self_: *mut whiteout_CascStorage,
            key_file_path: *const core::ffi::c_char,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_findEncryptionKey(
            self_: *mut whiteout_CascStorage,
            key_name: u64,
            out_value: *mut u8,
        ) -> i32;
        pub fn whiteout_casc_CascStorage_flushCache(self_: *mut whiteout_CascStorage);
        pub fn whiteout_casc_CascStorage_prefetch(self_: *mut whiteout_CascStorage) -> i32;
        pub fn whiteout_casc_CascStorage_lastError() -> u32;
        // StorageWritable
        pub fn whiteout_casc_CascStorageWritable_delete(self_: *mut whiteout_CascStorageWritable);
        pub fn whiteout_casc_CascStorageWritable_create(
            opts: *mut whiteout_CascCreateOptions,
            pool: *mut core::ffi::c_void,
        ) -> *mut whiteout_CascStorageWritable;
        pub fn whiteout_casc_CascStorageWritable_reserveFileId(
            self_: *mut whiteout_CascStorageWritable,
            name: *const core::ffi::c_char,
            out_value: *mut u32,
        ) -> i32;
        pub fn whiteout_casc_CascStorageWritable_writeFile(
            self_: *mut whiteout_CascStorageWritable,
            path: *const core::ffi::c_char,
            data: *const u8,
            data_size: usize,
            opts: *mut whiteout_CascWriteOptions,
        ) -> i32;
        pub fn whiteout_casc_CascStorageWritable_writeFile_fileId_data_opts_hint(
            self_: *mut whiteout_CascStorageWritable,
            file_id: i32,
            data: *const u8,
            data_size: usize,
            opts: *mut whiteout_CascWriteOptions,
            hint: i32,
        ) -> i32;
        pub fn whiteout_casc_CascStorageWritable_deleteFile(
            self_: *mut whiteout_CascStorageWritable,
            path: *const core::ffi::c_char,
        ) -> i32;
        pub fn whiteout_casc_CascStorageWritable_deleteFile_fileId_hint(
            self_: *mut whiteout_CascStorageWritable,
            file_id: i32,
            hint: i32,
        ) -> i32;
        pub fn whiteout_casc_CascStorageWritable_save(
            self_: *mut whiteout_CascStorageWritable,
        ) -> i32;
        pub fn whiteout_casc_CascStorageWritable_save_path(
            self_: *mut whiteout_CascStorageWritable,
            path: *const core::ffi::c_char,
        ) -> i32;
    }
}