udif 0.3.4

cross-platform Apple disk image (aka DMG, UDIF) library
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
//! DPP - DMG + PKG + PBZX parser
//!
//! A cross-platform library for working with Apple disk images (DMG files).
//!
//! # Features
//!
//! - **List** partitions in DMG files
//! - **Extract** raw partition data
//! - **Create** DMG files with various compression methods
//! - **Cross-platform** - works on Windows, Linux, and macOS
//!
//! # Supported Compression
//!
//! - Raw (uncompressed)
//! - Zlib
//! - Bzip2
//! - LZFSE (Apple's native compression)
//! - XZ (LZMA)
//!
//! # Example
//!
//! ```no_run
//! use udif::{DmgArchive, Result};
//!
//! fn main() -> Result<()> {
//!     // Open a DMG file
//!     let mut archive = DmgArchive::open("image.dmg")?;
//!
//!     // List partitions
//!     for partition in archive.partitions() {
//!         println!("{}: {} sectors", partition.name, partition.sectors);
//!     }
//!
//!     // Extract main partition
//!     let data = archive.extract_main_partition()?;
//!     std::fs::write("partition.raw", &data)?;
//!
//!     Ok(())
//! }
//! ```

pub mod checksum;
pub mod error;
pub mod format;
pub mod reader;
pub mod writer;

pub use checksum::{CHECKSUM_TYPE_CRC32, CHECKSUM_TYPE_NONE, crc32};
pub use error::{DppError, Result};
pub use format::{BlockType, KolyHeader, MishHeader, PartitionEntry};
pub use reader::{CompressionInfo, DmgReader, DmgReaderOptions, DmgStats, is_dmg, open};
pub use writer::{CompressionMethod, DmgWriter, create, create_from_data, create_from_file};

/// Partition filesystem type detected from the partition name
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PartitionType {
    /// HFS+ (case-insensitive)
    Hfs,
    /// HFSX (case-sensitive HFS+)
    Hfsx,
    /// Apple APFS
    Apfs,
    /// Other or unknown partition type
    Other,
}

impl PartitionType {
    /// Classify a partition from its DMG partition name (e.g. "Apple_HFSX")
    pub fn from_partition_name(name: &str) -> Self {
        if name.contains("Apple_HFSX") {
            PartitionType::Hfsx
        } else if name.contains("Apple_HFS") {
            PartitionType::Hfs
        } else if name.contains("Apple_APFS") {
            PartitionType::Apfs
        } else {
            PartitionType::Other
        }
    }

    /// Returns `true` if this partition can be parsed as HFS+
    pub fn is_hfs_compatible(&self) -> bool {
        matches!(self, PartitionType::Hfs | PartitionType::Hfsx)
    }
}

use std::fs::File;
use std::io::BufReader;
use std::path::Path;

/// High-level DMG archive interface
pub struct DmgArchive {
    reader: DmgReader<BufReader<File>>,
}

/// Partition information
#[derive(Debug, Clone)]
pub struct PartitionInfo {
    /// Partition name
    pub name: String,
    /// Partition ID
    pub id: i32,
    /// Number of sectors (512 bytes each)
    pub sectors: u64,
    /// Uncompressed size in bytes
    pub size: u64,
    /// Compressed size in bytes
    pub compressed_size: u64,
    /// Filesystem type detected from partition name
    pub partition_type: PartitionType,
}

impl DmgArchive {
    /// Open a DMG file with default options (checksum verification enabled)
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let reader = DmgReader::open(path)?;
        Ok(DmgArchive { reader })
    }

    /// Open a DMG file with custom options
    pub fn open_with_options<P: AsRef<Path>>(
        path: P,
        options: reader::DmgReaderOptions,
    ) -> Result<Self> {
        let reader = DmgReader::open_with_options(path, options)?;
        Ok(DmgArchive { reader })
    }

    /// Get archive statistics
    pub fn stats(&self) -> DmgStats {
        self.reader.stats()
    }

    /// Get compression info
    pub fn compression_info(&self) -> CompressionInfo {
        self.reader.compression_info()
    }

    /// List all partitions
    pub fn partitions(&self) -> Vec<PartitionInfo> {
        self.reader
            .partitions()
            .iter()
            .map(|p| PartitionInfo {
                name: p.name.clone(),
                id: p.id,
                sectors: p.block_map.sector_count,
                size: p.block_map.uncompressed_size(),
                compressed_size: p.block_map.compressed_size(),
                partition_type: PartitionType::from_partition_name(&p.name),
            })
            .collect()
    }

    /// Get partition by name
    pub fn partition(&self, name: &str) -> Option<PartitionInfo> {
        self.reader.partition(name).map(|p| PartitionInfo {
            name: p.name.clone(),
            id: p.id,
            sectors: p.block_map.sector_count,
            size: p.block_map.uncompressed_size(),
            compressed_size: p.block_map.compressed_size(),
            partition_type: PartitionType::from_partition_name(&p.name),
        })
    }

    /// Extract a partition by ID.
    ///
    /// When the `parallel` feature is enabled, blocks are decompressed in
    /// parallel using rayon for significantly faster extraction.
    pub fn extract_partition(&mut self, id: i32) -> Result<Vec<u8>> {
        self.reader.decompress_partition_auto(id)
    }

    /// Extract a partition by name.
    ///
    /// When the `parallel` feature is enabled, blocks are decompressed in
    /// parallel using rayon for significantly faster extraction.
    pub fn extract_partition_by_name(&mut self, name: &str) -> Result<Vec<u8>> {
        let partition = self
            .reader
            .partition(name)
            .ok_or_else(|| DppError::FileNotFound(name.to_string()))?;
        self.reader.decompress_partition_auto(partition.id)
    }

    /// Extract the main HFS+/APFS partition.
    ///
    /// When the `parallel` feature is enabled, blocks are decompressed in
    /// parallel using rayon for significantly faster extraction.
    pub fn extract_main_partition(&mut self) -> Result<Vec<u8>> {
        self.reader.decompress_main_partition_auto()
    }

    /// Extract all partitions as a raw disk image
    pub fn extract_all(&mut self) -> Result<Vec<u8>> {
        self.reader.decompress_all()
    }

    /// Stream a partition to a writer block-by-block (low memory usage)
    pub fn extract_partition_to<W: std::io::Write>(
        &mut self,
        id: i32,
        writer: &mut W,
    ) -> Result<u64> {
        self.reader.decompress_partition_to(id, writer)
    }

    /// Stream the main HFS+/APFS partition to a writer (low memory usage)
    pub fn extract_main_partition_to<W: std::io::Write>(&mut self, writer: &mut W) -> Result<u64> {
        self.reader.decompress_main_partition_to_auto(writer)
    }

    /// Get the ID of the main HFS+/APFS partition
    pub fn main_partition_id(&self) -> Result<i32> {
        self.reader.main_partition_id()
    }

    /// Get the ID of the main HFS+/HFSX partition (excludes APFS).
    /// Returns `Err(FileNotFound)` if no HFS-compatible partition exists.
    pub fn hfs_partition_id(&self) -> Result<i32> {
        self.reader.hfs_partition_id()
    }

    /// Extract a partition to a file
    pub fn extract_partition_to_file<P: AsRef<Path>>(&mut self, id: i32, path: P) -> Result<()> {
        let data = self.reader.decompress_partition_auto(id)?;
        std::fs::write(path, &data)?;
        Ok(())
    }

    /// Extract main partition to a file
    pub fn extract_main_partition_to_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        let data = self.reader.decompress_main_partition_auto()?;
        std::fs::write(path, &data)?;
        Ok(())
    }

    /// Get the raw koly header
    pub fn koly(&self) -> &KolyHeader {
        self.reader.koly()
    }
}

/// Builder for creating DMG files
pub struct DmgBuilder {
    compression: CompressionMethod,
    compression_level: u32,
    chunk_size: usize,
    partitions: Vec<(String, Vec<u8>)>,
    skip_checksums: bool,
}

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

impl DmgBuilder {
    /// Create a new DMG builder
    pub fn new() -> Self {
        DmgBuilder {
            compression: CompressionMethod::Zlib,
            compression_level: 6,
            chunk_size: 1024 * 1024,
            partitions: Vec::new(),
            skip_checksums: false,
        }
    }

    /// Set compression method
    pub fn compression(mut self, method: CompressionMethod) -> Self {
        self.compression = method;
        self
    }

    /// Set compression level (0-9)
    pub fn compression_level(mut self, level: u32) -> Self {
        self.compression_level = level;
        self
    }

    /// Set chunk size
    pub fn chunk_size(mut self, size: usize) -> Self {
        self.chunk_size = size;
        self
    }

    /// Skip checksum generation for faster DMG creation
    pub fn skip_checksums(mut self, skip: bool) -> Self {
        self.skip_checksums = skip;
        self
    }

    /// Add a partition
    pub fn add_partition(mut self, name: &str, data: Vec<u8>) -> Self {
        self.partitions.push((name.to_string(), data));
        self
    }

    /// Build and write the DMG to a file
    pub fn build<P: AsRef<Path>>(self, path: P) -> Result<()> {
        let mut writer = DmgWriter::create(path)?
            .compression(self.compression)
            .compression_level(self.compression_level)
            .chunk_size(self.chunk_size)
            .skip_checksums(self.skip_checksums);

        for (name, data) in self.partitions {
            writer.add_partition(&name, &data)?;
        }

        writer.finish()
    }
}

/// Quick check if a file is a valid DMG
pub fn check_dmg<P: AsRef<Path>>(path: P) -> bool {
    is_dmg(path)
}

/// Get statistics about a DMG file
pub fn stats<P: AsRef<Path>>(path: P) -> Result<DmgStats> {
    let reader = DmgReader::open(path)?;
    Ok(reader.stats())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn test_block_type_conversion() {
        assert_eq!(
            BlockType::try_from(0x00000000).unwrap(),
            BlockType::ZeroFill
        );
        assert_eq!(BlockType::try_from(0x80000005).unwrap(), BlockType::Zlib);
        assert_eq!(BlockType::try_from(0x80000006).unwrap(), BlockType::Bzip2);
        assert_eq!(BlockType::try_from(0x80000007).unwrap(), BlockType::Lzfse);
        assert_eq!(BlockType::try_from(0x80000008).unwrap(), BlockType::Xz);
        assert_eq!(BlockType::try_from(0xFFFFFFFF).unwrap(), BlockType::End);
        assert_eq!(BlockType::try_from(0x7FFFFFFE).unwrap(), BlockType::Comment);

        // Unknown block type should error
        assert!(BlockType::try_from(0x12345678).is_err());
    }

    #[test]
    fn test_compression_method() {
        assert_eq!(CompressionMethod::default(), CompressionMethod::Zlib);
    }

    // =========================================================================
    // TRICKY PIECE #1: Koly header must be exactly 512 bytes at -512 from EOF
    // =========================================================================
    #[test]
    fn test_koly_header_size_is_512() {
        use crate::format::{KOLY_MAGIC, KOLY_SIZE, KolyHeader};

        assert_eq!(KOLY_SIZE, 512, "KOLY_SIZE constant must be 512");

        // Create a koly header and serialize it
        let koly = KolyHeader {
            magic: *KOLY_MAGIC,
            version: 4,
            header_size: 512,
            flags: 1,
            running_data_fork_offset: 0,
            data_fork_offset: 0,
            data_fork_length: 1000,
            rsrc_fork_offset: 0,
            rsrc_fork_length: 0,
            segment_number: 1,
            segment_count: 1,
            segment_id: [0u8; 16],
            data_checksum_type: 2,
            data_checksum_size: 32,
            data_checksum: [0u8; 128],
            plist_offset: 1000,
            plist_length: 500,
            reserved: [0u8; 64],
            master_checksum_type: 2,
            master_checksum_size: 32,
            master_checksum: [0u8; 128],
            image_variant: 1,
            sector_count: 100,
        };

        let mut buf = Vec::new();
        koly.write(&mut buf).unwrap();

        assert_eq!(
            buf.len(),
            512,
            "Koly header serialization must be exactly 512 bytes"
        );
    }

    #[test]
    fn test_koly_magic_position() {
        use crate::format::{KOLY_MAGIC, KolyHeader};

        // Create a minimal DMG-like structure
        let mut dmg_data = vec![0u8; 1024]; // Some data

        // Append plist placeholder
        let plist = b"<?xml version=\"1.0\"?><plist></plist>";
        let plist_offset = dmg_data.len() as u64;
        dmg_data.extend_from_slice(plist);
        let plist_length = plist.len() as u64;

        // Create and append koly header
        let koly = KolyHeader {
            magic: *KOLY_MAGIC,
            version: 4,
            header_size: 512,
            flags: 1,
            running_data_fork_offset: 0,
            data_fork_offset: 0,
            data_fork_length: plist_offset,
            rsrc_fork_offset: 0,
            rsrc_fork_length: 0,
            segment_number: 1,
            segment_count: 1,
            segment_id: [0u8; 16],
            data_checksum_type: 2,
            data_checksum_size: 32,
            data_checksum: [0u8; 128],
            plist_offset,
            plist_length,
            reserved: [0u8; 64],
            master_checksum_type: 2,
            master_checksum_size: 32,
            master_checksum: [0u8; 128],
            image_variant: 1,
            sector_count: 2,
        };
        koly.write(&mut dmg_data).unwrap();

        // Verify koly magic is at exactly -512 from end
        let total_len = dmg_data.len();
        let koly_start = total_len - 512;
        assert_eq!(&dmg_data[koly_start..koly_start + 4], b"koly");
    }

    // =========================================================================
    // TRICKY PIECE #2: Mish header actual_block_count is at offset 200, not 36
    // =========================================================================
    #[test]
    fn test_mish_block_count_at_offset_200() {
        use crate::format::{MISH_MAGIC, MishHeader};
        use byteorder::{BigEndian, WriteBytesExt};

        // Create a mish header manually with known values
        let mut mish_data = Vec::new();

        // Header (204 bytes)
        mish_data.extend_from_slice(MISH_MAGIC); // 0-3: magic
        mish_data.write_u32::<BigEndian>(1).unwrap(); // 4-7: version
        mish_data.write_u64::<BigEndian>(0).unwrap(); // 8-15: first_sector
        mish_data.write_u64::<BigEndian>(10).unwrap(); // 16-23: sector_count
        mish_data.write_u64::<BigEndian>(0).unwrap(); // 24-31: data_offset
        mish_data.write_u32::<BigEndian>(0).unwrap(); // 32-35: buffers_needed
        mish_data.write_u32::<BigEndian>(999).unwrap(); // 36-39: WRONG block count (should be ignored)
        mish_data.extend_from_slice(&[0u8; 24]); // 40-63: reserved
        mish_data.write_u32::<BigEndian>(2).unwrap(); // 64-67: checksum_type
        mish_data.write_u32::<BigEndian>(32).unwrap(); // 68-71: checksum_size
        mish_data.extend_from_slice(&[0u8; 128]); // 72-199: checksum
        mish_data.write_u32::<BigEndian>(2).unwrap(); // 200-203: ACTUAL block count

        // Add 2 block runs (40 bytes each)
        // Block 0: ZeroFill
        mish_data.write_u32::<BigEndian>(0x00000000).unwrap(); // type
        mish_data.write_u32::<BigEndian>(0).unwrap(); // comment
        mish_data.write_u64::<BigEndian>(0).unwrap(); // sector_number
        mish_data.write_u64::<BigEndian>(10).unwrap(); // sector_count
        mish_data.write_u64::<BigEndian>(0).unwrap(); // compressed_offset
        mish_data.write_u64::<BigEndian>(0).unwrap(); // compressed_length

        // Block 1: End marker
        mish_data.write_u32::<BigEndian>(0xFFFFFFFF).unwrap(); // type
        mish_data.write_u32::<BigEndian>(0).unwrap();
        mish_data.write_u64::<BigEndian>(10).unwrap();
        mish_data.write_u64::<BigEndian>(0).unwrap();
        mish_data.write_u64::<BigEndian>(0).unwrap();
        mish_data.write_u64::<BigEndian>(0).unwrap();

        // Parse
        let mish = MishHeader::from_bytes(&mish_data).unwrap();

        // Should have 2 block runs (from offset 200), not 999 (from offset 36)
        assert_eq!(mish.block_runs.len(), 2);
        assert_eq!(mish.actual_block_count, 2);
        assert_eq!(mish.block_descriptor_count, 999); // This field is at 36 but not used for counting
    }

    #[test]
    fn test_mish_header_size_is_204() {
        use crate::format::{MISH_MAGIC, MishHeader};
        use byteorder::{BigEndian, WriteBytesExt};

        // Build minimal mish header
        let mut mish_data = Vec::new();
        mish_data.extend_from_slice(MISH_MAGIC);
        mish_data.write_u32::<BigEndian>(1).unwrap();
        mish_data.write_u64::<BigEndian>(0).unwrap();
        mish_data.write_u64::<BigEndian>(1).unwrap();
        mish_data.write_u64::<BigEndian>(0).unwrap();
        mish_data.write_u32::<BigEndian>(0).unwrap();
        mish_data.write_u32::<BigEndian>(0).unwrap();
        mish_data.extend_from_slice(&[0u8; 24]);
        mish_data.write_u32::<BigEndian>(2).unwrap();
        mish_data.write_u32::<BigEndian>(32).unwrap();
        mish_data.extend_from_slice(&[0u8; 128]);
        mish_data.write_u32::<BigEndian>(0).unwrap(); // actual_block_count = 0

        // Header should be exactly 204 bytes
        assert_eq!(mish_data.len(), 204);

        // Should parse successfully with 0 block runs
        let mish = MishHeader::from_bytes(&mish_data).unwrap();
        assert_eq!(mish.block_runs.len(), 0);
    }

    // =========================================================================
    // TRICKY PIECE #3: LZFSE decoder needs buffer larger than output size
    // =========================================================================
    #[test]
    fn test_lzfse_needs_larger_buffer() {
        // Compress some test data with LZFSE
        let original = b"Hello, World! This is a test of LZFSE compression. ".repeat(10);

        let mut compressed = vec![0u8; original.len() + 4096];
        let compressed_len = lzfse::encode_buffer(&original, &mut compressed).unwrap();
        compressed.truncate(compressed_len);

        // Try to decompress with exact-sized buffer - should fail
        let mut exact_buf = vec![0u8; original.len()];
        let result = lzfse::decode_buffer(&compressed, &mut exact_buf);

        // This might fail with BufferTooSmall
        if result.is_err() {
            // Retry with 2x buffer - should work
            let mut large_buf = vec![0u8; original.len() * 2];
            let decoded_len = lzfse::decode_buffer(&compressed, &mut large_buf).unwrap();
            assert_eq!(decoded_len, original.len());
            assert_eq!(&large_buf[..decoded_len], &original[..]);
        }
    }

    // =========================================================================
    // TRICKY PIECE #4: Zlib decompressed size might be less than sector_count * 512
    // =========================================================================
    #[test]
    fn test_zlib_partial_sector() {
        use flate2::Compression;
        use flate2::read::ZlibDecoder;
        use flate2::write::ZlibEncoder;
        use std::io::{Read, Write};

        // Create data that's not sector-aligned (100 bytes, not multiple of 512)
        let original = b"This is test data that is not aligned to 512-byte sectors!";

        // Compress it
        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(original).unwrap();
        let compressed = encoder.finish().unwrap();

        // Try to decompress into a full sector buffer (512 bytes)
        let mut sector_buf = vec![0u8; 512];
        let mut decoder = ZlibDecoder::new(&compressed[..]);

        // read() should return actual bytes, not error
        let bytes_read = decoder.read(&mut sector_buf).unwrap();

        assert_eq!(bytes_read, original.len());
        assert_eq!(&sector_buf[..bytes_read], &original[..]);

        // Rest of buffer should be zeros
        assert!(sector_buf[bytes_read..].iter().all(|&b| b == 0));
    }

    // =========================================================================
    // TRICKY PIECE #5: DMG roundtrip with various data sizes
    // =========================================================================
    #[test]
    fn test_roundtrip_sector_aligned() {
        // Test with sector-aligned data (1024 bytes = 2 sectors)
        let original = vec![0x42u8; 1024];

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // Read back
        let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let extracted = reader.decompress_partition(0).unwrap();

        // Should match (might be padded to sector boundary)
        assert!(extracted.len() >= original.len());
        assert_eq!(&extracted[..original.len()], &original[..]);
    }

    #[test]
    fn test_roundtrip_non_sector_aligned() {
        // Test with non-sector-aligned data (100 bytes)
        let original = b"Short test data that is not sector aligned".to_vec();

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // Read back
        let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let extracted = reader.decompress_partition(0).unwrap();

        // First bytes should match original
        assert!(extracted.len() >= original.len());
        assert_eq!(&extracted[..original.len()], &original[..]);
    }

    #[test]
    fn test_roundtrip_empty_data() {
        // Edge case: empty data
        let original: Vec<u8> = vec![];

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("empty", &original).unwrap();
            writer.finish().unwrap();
        }

        let reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let partitions = reader.partitions();
        assert_eq!(partitions.len(), 1);
    }

    #[test]
    fn test_roundtrip_zeros() {
        // Test that zero-filled blocks are handled correctly
        let original = vec![0u8; 2048]; // 4 sectors of zeros

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("zeros", &original).unwrap();
            writer.finish().unwrap();
        }

        let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let extracted = reader.decompress_partition(0).unwrap();

        assert_eq!(extracted.len(), original.len());
        assert!(extracted.iter().all(|&b| b == 0));
    }

    // =========================================================================
    // TRICKY PIECE #6: Block run structure is exactly 40 bytes
    // =========================================================================
    #[test]
    fn test_block_run_size() {
        use crate::format::{BlockRun, BlockType};

        let block_run = BlockRun {
            block_type: BlockType::Zlib,
            comment: 0,
            sector_number: 100,
            sector_count: 50,
            compressed_offset: 1000,
            compressed_length: 500,
        };

        let bytes = block_run.to_bytes();
        assert_eq!(bytes.len(), 40, "Block run must be exactly 40 bytes");

        // Verify round-trip
        let parsed = BlockRun::from_bytes(&bytes).unwrap();
        assert_eq!(parsed.block_type, BlockType::Zlib);
        assert_eq!(parsed.sector_number, 100);
        assert_eq!(parsed.sector_count, 50);
        assert_eq!(parsed.compressed_offset, 1000);
        assert_eq!(parsed.compressed_length, 500);
    }

    // =========================================================================
    // TRICKY PIECE #7: is_dmg checks magic at -512, not -4
    // =========================================================================
    #[test]
    fn test_is_dmg_checks_correct_offset() {
        use crate::format::is_dmg;

        // Create a file that has "koly" at -4 but not at -512 (should NOT be valid)
        let mut fake_dmg = vec![0u8; 600];
        // Put "koly" at the wrong place (-4 from end)
        let len = fake_dmg.len();
        fake_dmg[len - 4..].copy_from_slice(b"koly");

        let mut cursor = Cursor::new(&fake_dmg);
        assert!(
            !is_dmg(&mut cursor),
            "Should not detect koly at wrong offset"
        );

        // Create a file that has "koly" at -512 (should be valid)
        let mut real_dmg = vec![0u8; 600];
        let len = real_dmg.len();
        real_dmg[len - 512..len - 508].copy_from_slice(b"koly");

        let mut cursor = Cursor::new(&real_dmg);
        assert!(is_dmg(&mut cursor), "Should detect koly at correct offset");
    }

    // =========================================================================
    // TRICKY PIECE #8: Different compression methods
    // =========================================================================
    #[test]
    fn test_compression_methods() {
        let original = b"Test data for compression testing. ".repeat(100);

        for method in [
            CompressionMethod::Raw,
            CompressionMethod::Zlib,
            CompressionMethod::Bzip2,
            // LZFSE tested separately due to buffer quirks
        ] {
            let mut dmg_buf = Vec::new();
            {
                let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf)).compression(method);
                writer.add_partition("test", &original).unwrap();
                writer.finish().unwrap();
            }

            let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
            let extracted = reader.decompress_partition(0).unwrap();

            assert!(
                extracted.len() >= original.len(),
                "Extracted should be at least as large as original for {:?}",
                method
            );
            assert_eq!(
                &extracted[..original.len()],
                &original[..],
                "Data mismatch for {:?}",
                method
            );
        }
    }

    #[test]
    fn test_lzfse_compression_roundtrip() {
        let original = b"LZFSE compression test data. ".repeat(100);

        let mut dmg_buf = Vec::new();
        {
            let mut writer =
                DmgWriter::new(Cursor::new(&mut dmg_buf)).compression(CompressionMethod::Lzfse);
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let extracted = reader.decompress_partition(0).unwrap();

        assert!(extracted.len() >= original.len());
        assert_eq!(&extracted[..original.len()], &original[..]);
    }

    #[test]
    fn test_xz_roundtrip() {
        use std::io::Write;
        use xz2::read::XzDecoder;
        use xz2::write::XzEncoder;

        let original = b"XZ compression roundtrip test data. ".repeat(100);

        // Compress
        let mut encoder = XzEncoder::new(Vec::new(), 6);
        encoder.write_all(&original).unwrap();
        let compressed = encoder.finish().unwrap();

        // Verify XZ magic bytes
        assert_eq!(&compressed[..6], &[0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00]);

        // Decompress
        let mut decoder = XzDecoder::new(&compressed[..]);
        let mut decompressed = vec![0u8; original.len()];
        let n = crate::reader::read_full(&mut decoder, &mut decompressed).unwrap();

        assert_eq!(n, original.len());
        assert_eq!(&decompressed[..], &original[..]);
    }

    // =========================================================================
    // Integration test with real DMG file (requires fixture)
    // =========================================================================

    /// Requires ../tests/kdk.dmg fixture.
    /// Run with `cargo test -- --ignored`.
    #[test]
    #[ignore]
    fn test_real_dmg_if_available() {
        let test_dmg = "../tests/kdk.dmg";

        let archive = DmgArchive::open(test_dmg).unwrap();
        let stats = archive.stats();

        assert_eq!(stats.version, 4);
        assert!(stats.partition_count > 0);
        assert!(stats.total_uncompressed > stats.total_compressed);

        let partitions = archive.partitions();
        assert!(!partitions.is_empty());

        let hfsx = partitions.iter().find(|p| p.name.contains("HFSX"));
        assert!(hfsx.is_some(), "Should have HFSX partition");
    }

    /// Requires ../tests/kdk.dmg fixture.
    /// Run with `cargo test -- --ignored`.
    #[test]
    #[ignore]
    fn test_real_dmg_decompress() {
        let test_dmg = "../tests/kdk.dmg";

        let mut archive = DmgArchive::open(test_dmg).unwrap();
        let data = archive.extract_main_partition().unwrap();
        assert_eq!(&data[1024..1026], &[0x48, 0x58], "Should be HFSX signature");

        let mut archive2 = DmgArchive::open(test_dmg).unwrap();
        let mut buf = Vec::new();
        let _n = archive2.extract_main_partition_to(&mut buf).unwrap();
        assert_eq!(&buf[1024..1026], &[0x48, 0x58], "Should be HFSX signature");

        assert_eq!(data.len(), buf.len());
        assert_eq!(
            data, buf,
            "Buffered and streaming should produce identical output"
        );
    }

    /// Requires ../tests/googlechrome.dmg fixture (XZ-compressed DMG).
    /// Run with `cargo test -- --ignored`.
    #[test]
    #[ignore]
    fn test_xz_dmg_googlechrome() {
        let test_dmg = "../tests/googlechrome.dmg";

        let archive = DmgArchive::open(test_dmg).unwrap();
        let comp_info = archive.compression_info();

        // googlechrome.dmg uses XZ (block type 0x80000008)
        assert!(comp_info.xz_blocks > 0, "Should have XZ blocks");

        // Decompress main partition and verify non-zero data
        let mut archive = DmgArchive::open(test_dmg).unwrap();
        let data = archive.extract_main_partition().unwrap();
        assert!(
            !data.iter().all(|&b| b == 0),
            "Decompressed data should not be all zeros"
        );

        // Check for HFS+ signature (0x482B at offset 1024) or HFSX (0x4858)
        if data.len() > 1026 {
            let sig = &data[1024..1026];
            assert!(
                sig == [0x48, 0x2B] || sig == [0x48, 0x58],
                "Should have HFS+/HFSX signature, got {:02X}{:02X}",
                sig[0],
                sig[1]
            );
        }
    }

    // =========================================================================
    // TRICKY PIECE #9: Checksum verification
    // =========================================================================
    #[test]
    fn test_checksum_verification_disabled() {
        // Create a DMG and verify we can read it with checksums disabled
        let original = b"Test data for checksum verification".repeat(20);

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // Read with checksums disabled
        let options = reader::DmgReaderOptions {
            verify_checksums: false,
        };
        let mut reader = DmgReader::with_options(Cursor::new(&dmg_buf), options).unwrap();
        let extracted = reader.decompress_partition(0).unwrap();

        assert!(extracted.len() >= original.len());
        assert_eq!(&extracted[..original.len()], &original[..]);
    }

    #[test]
    fn test_checksum_verification_enabled_with_zero_checksums() {
        // Create a DMG (writer currently writes zero checksums)
        // This should still work because zero checksums are skipped
        let original = b"Test data for checksum verification".repeat(20);

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // Read with checksums enabled (default)
        let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let extracted = reader.decompress_partition(0).unwrap();

        assert!(extracted.len() >= original.len());
        assert_eq!(&extracted[..original.len()], &original[..]);
    }

    #[test]
    fn test_dmg_archive_with_options() {
        // Test that DmgArchive::open_with_options works
        let original = b"Test data".repeat(10);

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // Write to temp file
        let temp_dir = tempfile::tempdir().unwrap();
        let temp_path = temp_dir.path().join("test.dmg");
        std::fs::write(&temp_path, &dmg_buf).unwrap();

        // Open with custom options
        let options = reader::DmgReaderOptions {
            verify_checksums: false,
        };
        let mut archive = DmgArchive::open_with_options(&temp_path, options).unwrap();
        let extracted = archive.extract_partition(0).unwrap();

        assert!(extracted.len() >= original.len());
        assert_eq!(&extracted[..original.len()], &original[..]);
    }

    // =========================================================================
    // TRICKY PIECE #10: Checksum roundtrip verification
    // =========================================================================
    #[test]
    fn test_checksum_roundtrip_with_verification() {
        // Test that checksums are written and verified correctly
        let original = b"Test data for checksum roundtrip verification. ".repeat(50);

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // Read with checksum verification enabled (default)
        // This will fail if checksums don't match
        let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let extracted = reader.decompress_partition(0).unwrap();

        assert!(extracted.len() >= original.len());
        assert_eq!(&extracted[..original.len()], &original[..]);

        // Verify checksums are non-zero in koly header
        let koly = reader.koly();
        assert_eq!(koly.data_checksum_type, 2); // CRC32
        assert_ne!(&koly.data_checksum[..4], &[0u8; 4]); // Non-zero checksum
        assert_eq!(koly.master_checksum_type, 2); // CRC32
        assert_ne!(&koly.master_checksum[..4], &[0u8; 4]); // Non-zero checksum
    }

    #[test]
    fn test_checksum_detection_corrupted_data() {
        // Test that corrupted data fork is detected
        let original = b"Test data for corruption detection".repeat(20);

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // Corrupt the data fork (first 100 bytes)
        for byte in dmg_buf.iter_mut().take(100) {
            *byte ^= 0xFF;
        }

        // Try to read with checksum verification - should fail
        let result = DmgReader::new(Cursor::new(&dmg_buf));
        assert!(result.is_err());
        if let Err(DppError::ChecksumMismatch { expected, actual }) = result {
            assert_ne!(expected, actual); // Checksums should differ
        } else {
            panic!("Expected ChecksumMismatch error");
        }
    }

    #[test]
    fn test_checksum_all_compression_methods() {
        // Test checksum verification with all compression methods
        let original = b"Testing checksums with all compressions! ".repeat(100);

        for method in [
            CompressionMethod::Raw,
            CompressionMethod::Zlib,
            CompressionMethod::Bzip2,
            CompressionMethod::Lzfse,
        ] {
            let mut dmg_buf = Vec::new();
            {
                let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf)).compression(method);
                writer.add_partition("test", &original).unwrap();
                writer.finish().unwrap();
            }

            // Read with checksum verification
            let mut reader = DmgReader::new(Cursor::new(&dmg_buf))
                .unwrap_or_else(|e| panic!("Failed to open DMG with {:?}: {:?}", method, e));

            let extracted = reader
                .decompress_partition(0)
                .unwrap_or_else(|e| panic!("Failed to decompress with {:?}: {:?}", method, e));

            assert!(
                extracted.len() >= original.len(),
                "Extracted size mismatch for {:?}",
                method
            );
            assert_eq!(
                &extracted[..original.len()],
                &original[..],
                "Data mismatch for {:?}",
                method
            );
        }
    }
}

#[cfg(test)]
#[cfg(feature = "parallel")]
mod parallel_tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn test_parallel_matches_sequential() {
        let original = b"Test data for parallel decompression. ".repeat(100);

        for method in [
            CompressionMethod::Raw,
            CompressionMethod::Zlib,
            CompressionMethod::Bzip2,
            CompressionMethod::Lzfse,
        ] {
            let mut dmg_buf = Vec::new();
            {
                let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf)).compression(method);
                writer.add_partition("test", &original).unwrap();
                writer.finish().unwrap();
            }

            // Sequential decompress
            let mut reader1 = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
            let sequential = reader1.decompress_partition(0).unwrap();

            // Parallel decompress
            let mut reader2 = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
            let parallel = reader2.decompress_partition_parallel(0).unwrap();

            assert_eq!(sequential, parallel, "Parallel mismatch for {:?}", method);
        }
    }

    #[test]
    fn test_parallel_to_writer() {
        let original = b"Test data for parallel writer. ".repeat(100);

        let mut dmg_buf = Vec::new();
        {
            let mut writer =
                DmgWriter::new(Cursor::new(&mut dmg_buf)).compression(CompressionMethod::Zlib);
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // Sequential decompress
        let mut reader1 = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let sequential = reader1.decompress_partition(0).unwrap();

        // Parallel via decompress_partition_to_parallel
        let mut reader2 = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let mut output = Vec::new();
        reader2
            .decompress_partition_to_parallel(0, &mut output)
            .unwrap();

        assert_eq!(sequential, output);
    }

    #[test]
    fn test_parallel_empty_partition() {
        let original: Vec<u8> = vec![];

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("empty", &original).unwrap();
            writer.finish().unwrap();
        }

        let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let result = reader.decompress_partition_parallel(0).unwrap();
        assert!(result.iter().all(|&b| b == 0));
    }

    #[test]
    fn test_parallel_zeros() {
        let original = vec![0u8; 2048]; // 4 sectors of zeros

        let mut dmg_buf = Vec::new();
        {
            let mut writer = DmgWriter::new(Cursor::new(&mut dmg_buf));
            writer.add_partition("zeros", &original).unwrap();
            writer.finish().unwrap();
        }

        let mut reader = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let result = reader.decompress_partition_parallel(0).unwrap();

        assert_eq!(result.len(), original.len());
        assert!(result.iter().all(|&b| b == 0));
    }

    #[test]
    fn test_auto_selects_parallel() {
        let original = b"Auto-select test data. ".repeat(50);

        let mut dmg_buf = Vec::new();
        {
            let mut writer =
                DmgWriter::new(Cursor::new(&mut dmg_buf)).compression(CompressionMethod::Zlib);
            writer.add_partition("test", &original).unwrap();
            writer.finish().unwrap();
        }

        // decompress_partition_auto should use parallel when feature is enabled
        let mut reader1 = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let auto_result = reader1.decompress_partition_auto(0).unwrap();

        let mut reader2 = DmgReader::new(Cursor::new(&dmg_buf)).unwrap();
        let parallel_result = reader2.decompress_partition_parallel(0).unwrap();

        assert_eq!(auto_result, parallel_result);
    }
}