chdlady-core 0.1.0

Core container manipulation for CHD v5 format
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
//! CHD container reader, decompression pipeline, and integrity verification.
use sha1::{Digest, Sha1};
use std::io::{Read, Seek, SeekFrom, Write};

use crate::codecs::decompress_hunk;
use crate::crc16::crc16;
use crate::error::ChdError;
use crate::header::ChdHeader;
use crate::map::{read_v34_map, read_v5_map, HunkType, MapEntry};
use crate::metadata::{compute_overall_sha1, read_all_metadata, MetadataEntry};
use crate::progress::{OperationPhase, ProgressStatus};
#[cfg(feature = "rayon")]
use rayon::prelude::*;

enum HunkPayload {
    Compressed {
        fourcc: u32,
        data: Vec<u8>,
        crc: u16,
    },
    Uncompressed {
        data: Vec<u8>,
        crc: u16,
    },
    Mini(u64),
    Direct(Vec<u8>),
}

/// A reader interface for accessing parent CHD data in differential containers.
pub trait ChdParentReader: Send {
    /// Returns the CHD header of the parent container.
    fn header(&self) -> &ChdHeader;
    /// Reads arbitrary slice of uncompressed parent data at `offset` into `dest`.
    fn read_bytes(&mut self, offset: u64, dest: &mut [u8]) -> Result<(), ChdError>;
    /// Reads a single hunk from the parent into `dest`.
    fn read_hunk(&mut self, hunknum: u64, dest: &mut [u8]) -> Result<(), ChdError>;
}

/// Verification results for a CHD container.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifyResult {
    /// True if container has compression enabled.
    pub is_compressed: bool,
    /// True if container has a non-zero raw SHA-1 checksum in header.
    pub has_checksum: bool,
    /// Actual raw SHA-1 computed across all logical bytes.
    pub actual_raw_sha1: [u8; 20],
    /// Expected raw SHA-1 from container header.
    pub expected_raw_sha1: [u8; 20],
    /// True if actual raw SHA-1 matches expected.
    pub raw_sha1_matched: bool,
    /// Actual overall SHA-1 computed over raw SHA-1 and metadata.
    pub actual_overall_sha1: [u8; 20],
    /// Expected overall SHA-1 from container header.
    pub expected_overall_sha1: [u8; 20],
    /// True if actual overall SHA-1 matches expected.
    pub overall_sha1_matched: bool,
}

/// Comprehensive information about a CHD container.
#[derive(Debug, Clone)]
pub struct ChdInfo {
    /// CHD format version (e.g. 5).
    pub version: u32,
    /// Total logical bytes in the uncompressed data.
    pub logical_bytes: u64,
    /// Size of each hunk in bytes.
    pub hunk_bytes: u32,
    /// Total number of hunks.
    pub hunk_count: u64,
    /// Size of each unit in bytes.
    pub unit_bytes: u32,
    /// Total number of units.
    pub unit_count: u64,
    /// Configured compressor codecs (up to 4 FourCC codes).
    pub compressors: [u32; 4],
    /// Total file size of the CHD on disk.
    pub file_size: u64,
    /// Expected raw SHA-1 checksum.
    pub raw_sha1: [u8; 20],
    /// Expected overall SHA-1 checksum.
    pub sha1: [u8; 20],
    /// Parent SHA-1 checksum.
    pub parent_sha1: [u8; 20],
    /// Number of metadata entries.
    pub metadata_count: usize,
}

/// A reader for CHD containers with hunk decompression and integrity verification.
pub struct ChdFile<R> {
    reader: R,
    header: ChdHeader,
    map: Vec<MapEntry>,
    cache: Vec<(u64, Vec<u8>)>,
    compressed_buffer: Vec<u8>,
    parent: Option<Box<dyn ChdParentReader>>,
}

impl<R: Read + Seek + Send> ChdParentReader for ChdFile<R> {
    fn header(&self) -> &ChdHeader {
        &self.header
    }

    fn read_bytes(&mut self, offset: u64, dest: &mut [u8]) -> Result<(), ChdError> {
        self.read_bytes(offset, dest)
    }

    fn read_hunk(&mut self, hunknum: u64, dest: &mut [u8]) -> Result<(), ChdError> {
        self.read_hunk(hunknum, dest)
    }
}

impl<R: Read + Seek> ChdFile<R> {
    /// Opens and parses a CHD container from a readable, seekable source.
    pub fn open(reader: R) -> Result<Self, ChdError> {
        Self::open_with_parent(reader, None)
    }

    /// Opens and parses a CHD container with an optional parent reader.
    pub fn open_with_parent(
        mut reader: R,
        parent: Option<Box<dyn ChdParentReader>>,
    ) -> Result<Self, ChdError> {
        let header = ChdHeader::read(&mut reader)?;
        if header.parent_sha1 != [0u8; 20] {
            if let Some(ref p) = parent {
                if p.header().sha1 != header.parent_sha1 {
                    return Err(ChdError::InvalidParent);
                }
            }
        } else if parent.is_some() {
            return Err(ChdError::InvalidParameter(
                "parent CHD specified for non-differential CHD".into(),
            ));
        }

        let map = if header.version >= 5 {
            read_v5_map(&mut reader, &header)?
        } else {
            read_v34_map(&mut reader, &header)?
        };

        Ok(Self {
            reader,
            header,
            map,
            cache: Vec::with_capacity(4),
            compressed_buffer: Vec::new(),
            parent,
        })
    }

    /// Returns a reference to the parsed CHD header.
    pub fn header(&self) -> &ChdHeader {
        &self.header
    }

    /// Returns a slice of the parsed hunk map entries.
    pub fn map(&self) -> &[MapEntry] {
        &self.map
    }

    /// Reads and decompresses a single hunk into `dest`.
    ///
    /// `dest` must have a length of exactly `header.hunk_bytes`.
    pub fn read_hunk(&mut self, hunknum: u64, dest: &mut [u8]) -> Result<(), ChdError> {
        self.read_hunk_internal(hunknum, dest, 0)
    }

    fn read_hunk_internal(
        &mut self,
        hunknum: u64,
        dest: &mut [u8],
        depth: usize,
    ) -> Result<(), ChdError> {
        if depth > 64 {
            return Err(ChdError::InvalidData(
                "exceeded maximum self-reference recursion depth".into(),
            ));
        }

        let total_hunks = self.header.hunk_count();
        if hunknum >= total_hunks {
            return Err(ChdError::HunkOutOfRange {
                index: hunknum,
                total: total_hunks,
            });
        }

        let hunk_bytes = self.header.hunk_bytes as usize;
        if dest.len() != hunk_bytes {
            return Err(ChdError::Codec(format!(
                "destination buffer size mismatch: expected {}, got {}",
                hunk_bytes,
                dest.len()
            )));
        }

        let entry = self.map[hunknum as usize];
        match entry.hunk_type {
            HunkType::Compressed(codec_idx) => {
                let fourcc = self.header.compressors[codec_idx as usize];
                let comp_len = entry.length as usize;

                if self.compressed_buffer.len() < comp_len {
                    self.compressed_buffer.resize(comp_len, 0);
                }
                self.reader.seek(SeekFrom::Start(entry.offset))?;
                self.reader
                    .read_exact(&mut self.compressed_buffer[..comp_len])?;

                decompress_hunk(fourcc, &self.compressed_buffer[..comp_len], dest)?;

                if self.header.version >= 5 {
                    let calculated_crc = crc16(dest, 0xffff);
                    if calculated_crc != entry.crc16 {
                        return Err(ChdError::CrcMismatch {
                            expected: entry.crc16,
                            found: calculated_crc,
                        });
                    }
                }
                Ok(())
            }
            HunkType::Uncompressed => {
                self.reader.seek(SeekFrom::Start(entry.offset))?;
                self.reader.read_exact(dest)?;

                if self.header.version >= 5 && self.header.is_compressed() {
                    let calculated_crc = crc16(dest, 0xffff);
                    if calculated_crc != entry.crc16 {
                        return Err(ChdError::CrcMismatch {
                            expected: entry.crc16,
                            found: calculated_crc,
                        });
                    }
                }
                Ok(())
            }
            HunkType::SelfRef(target_hunk) => self.read_hunk_internal(target_hunk, dest, depth + 1),
            HunkType::Parent(unit_offset) => {
                if let Some(ref mut parent) = self.parent {
                    let parent_offset = if self.header.version <= 4 {
                        unit_offset * (self.header.hunk_bytes as u64)
                    } else {
                        let parent_unit_bytes = parent.header().unit_bytes as u64;
                        unit_offset * parent_unit_bytes
                    };
                    parent.read_bytes(parent_offset, dest)
                } else if self.header.parent_sha1 == [0u8; 20] {
                    dest.fill(0);
                    Ok(())
                } else {
                    Err(ChdError::RequiresParent)
                }
            }
            HunkType::Mini(val) => {
                let be = val.to_be_bytes();
                for chunk in dest.chunks_mut(8) {
                    let len = chunk.len().min(8);
                    chunk.copy_from_slice(&be[..len]);
                }
                Ok(())
            }
        }
    }

    /// Reads arbitrary slice of uncompressed data at `offset` into `dest`.
    pub fn read_bytes(&mut self, offset: u64, dest: &mut [u8]) -> Result<(), ChdError> {
        if dest.is_empty() {
            return Ok(());
        }

        let total_bytes = self.header.logical_bytes;
        let read_end = offset
            .checked_add(dest.len() as u64)
            .ok_or_else(|| ChdError::InvalidData("read range overflow".into()))?;

        if read_end > total_bytes {
            return Err(ChdError::InvalidData(format!(
                "read beyond logical bytes: {} > {}",
                read_end, total_bytes
            )));
        }

        let hunk_bytes = self.header.hunk_bytes as u64;
        let first_hunk = offset / hunk_bytes;
        let last_hunk = (read_end - 1) / hunk_bytes;

        let mut dest_offset = 0;
        for cur_hunk in first_hunk..=last_hunk {
            let start_offs = if cur_hunk == first_hunk {
                (offset % hunk_bytes) as usize
            } else {
                0
            };
            let end_offs = if cur_hunk == last_hunk {
                ((read_end - 1) % hunk_bytes) as usize
            } else {
                (hunk_bytes - 1) as usize
            };
            let chunk_len = end_offs + 1 - start_offs;

            if start_offs == 0 && chunk_len == hunk_bytes as usize {
                self.read_hunk(cur_hunk, &mut dest[dest_offset..dest_offset + chunk_len])?;
            } else {
                let cached_idx = self.cache.iter().position(|(h, _)| *h == cur_hunk);
                let buf_idx = if let Some(idx) = cached_idx {
                    idx
                } else {
                    let mut hunk_buf = vec![0u8; hunk_bytes as usize];
                    self.read_hunk(cur_hunk, &mut hunk_buf)?;
                    if self.cache.len() >= 4 {
                        self.cache.remove(0);
                    }
                    self.cache.push((cur_hunk, hunk_buf));
                    self.cache.len() - 1
                };
                let (_, cached_buf) = &self.cache[buf_idx];
                dest[dest_offset..dest_offset + chunk_len]
                    .copy_from_slice(&cached_buf[start_offs..start_offs + chunk_len]);
            }

            dest_offset += chunk_len;
        }

        Ok(())
    }

    /// Decompresses a range of hunks using multi-threaded parallel decompression and invokes `for_each_hunk`
    /// for each decompressed hunk in strictly sequential hunk order.
    ///
    /// # Ordering Guarantee
    /// Even though decompression happens concurrently across worker threads, `for_each_hunk` is guaranteed
    /// to be invoked sequentially and in strictly monotonically increasing hunk order (`start_hunk`, `start_hunk + 1`, ...).
    /// Callers can safely write directly to sequential output sinks (such as files or streaming formats).
    pub fn read_hunks_parallel<F>(
        &mut self,
        start_hunk: u64,
        count: u64,
        mut for_each_hunk: F,
    ) -> Result<(), ChdError>
    where
        F: FnMut(u64, &[u8]) -> Result<(), ChdError>,
    {
        if count == 0 {
            return Ok(());
        }

        let total_hunks = self.header.hunk_count();
        if start_hunk >= total_hunks {
            return Ok(());
        }
        let end_hunk = (start_hunk + count - 1).min(total_hunks - 1);
        let hunk_bytes = self.header.hunk_bytes as u64;

        #[cfg(feature = "rayon")]
        let threads = rayon::current_num_threads();
        #[cfg(not(feature = "rayon"))]
        let threads = 1;

        // Cap batch size to prevent excessive RAM allocations on large hunk containers
        const MAX_BATCH_BYTES: u64 = 64 * 1024 * 1024;
        let max_hunks_by_mem = (MAX_BATCH_BYTES / hunk_bytes.max(1)).max(threads as u64);

        let batch_size = if hunk_bytes <= 4096 {
            (threads * 64).clamp(128, 1024) as u64
        } else if hunk_bytes <= 19584 {
            (threads * 16).clamp(32, 256) as u64
        } else {
            (threads * 4).clamp(8, 64) as u64
        }
        .min(max_hunks_by_mem);

        let mut cur_hunk = start_hunk;
        let mut cur_reader_pos: Option<u64> = None;
        let mut self_ref_cache: std::collections::HashMap<u64, Vec<u8>> =
            std::collections::HashMap::new();

        let hb = hunk_bytes as usize;
        let max_batch_hunks = (batch_size).min(end_hunk - start_hunk + 1) as usize;
        let mut batch_output = vec![0u8; max_batch_hunks * hb];

        while cur_hunk <= end_hunk {
            let batch_end = (cur_hunk + batch_size - 1).min(end_hunk);
            let mut batch_items = Vec::with_capacity((batch_end - cur_hunk + 1) as usize);

            for h in cur_hunk..=batch_end {
                let entry = self.map[h as usize];
                match entry.hunk_type {
                    HunkType::Compressed(codec_idx) => {
                        let fourcc = self.header.compressors[codec_idx as usize];
                        let comp_len = entry.length as usize;
                        let mut comp_data = vec![0u8; comp_len];
                        if cur_reader_pos != Some(entry.offset) {
                            self.reader.seek(SeekFrom::Start(entry.offset))?;
                        }
                        self.reader.read_exact(&mut comp_data)?;
                        cur_reader_pos = Some(entry.offset + comp_len as u64);
                        batch_items.push((
                            h,
                            HunkPayload::Compressed {
                                fourcc,
                                data: comp_data,
                                crc: entry.crc16,
                            },
                        ));
                    }
                    HunkType::Uncompressed => {
                        let mut raw_data = vec![0u8; hunk_bytes as usize];
                        if cur_reader_pos != Some(entry.offset) {
                            self.reader.seek(SeekFrom::Start(entry.offset))?;
                        }
                        self.reader.read_exact(&mut raw_data)?;
                        cur_reader_pos = Some(entry.offset + hunk_bytes);
                        batch_items.push((
                            h,
                            HunkPayload::Uncompressed {
                                data: raw_data,
                                crc: entry.crc16,
                            },
                        ));
                    }
                    HunkType::Mini(val) => {
                        batch_items.push((h, HunkPayload::Mini(val)));
                    }
                    HunkType::SelfRef(target_hunk) => {
                        let buf = if let Some(cached) = self_ref_cache.get(&target_hunk) {
                            cached.clone()
                        } else {
                            let mut b = vec![0u8; hunk_bytes as usize];
                            self.read_hunk(target_hunk, &mut b)?;
                            cur_reader_pos = None;
                            if self_ref_cache.len() < 128 {
                                self_ref_cache.insert(target_hunk, b.clone());
                            }
                            b
                        };
                        batch_items.push((h, HunkPayload::Direct(buf)));
                    }
                    HunkType::Parent(_) => {
                        let mut buf = vec![0u8; hunk_bytes as usize];
                        self.read_hunk(h, &mut buf)?;
                        cur_reader_pos = None;
                        batch_items.push((h, HunkPayload::Direct(buf)));
                    }
                }
            }

            let version = self.header.version;
            let is_compressed = self.header.is_compressed();
            let batch_count = (batch_end - cur_hunk + 1) as usize;
            let current_batch_output = &mut batch_output[..batch_count * hb];

            #[cfg(feature = "rayon")]
            let decompressed_results: Result<(), ChdError> = current_batch_output
                .par_chunks_exact_mut(hb)
                .zip(batch_items.into_par_iter())
                .try_for_each(|(dest, (_h, payload))| -> Result<(), ChdError> {
                    match payload {
                        HunkPayload::Compressed { fourcc, data, crc } => {
                            decompress_hunk(fourcc, &data, dest)?;
                            if version >= 5 {
                                let calculated_crc = crc16(dest, 0xffff);
                                if calculated_crc != crc {
                                    return Err(ChdError::CrcMismatch {
                                        expected: crc,
                                        found: calculated_crc,
                                    });
                                }
                            }
                        }
                        HunkPayload::Uncompressed { data, crc } => {
                            dest.copy_from_slice(&data);
                            if version >= 5 && is_compressed {
                                let calculated_crc = crc16(dest, 0xffff);
                                if calculated_crc != crc {
                                    return Err(ChdError::CrcMismatch {
                                        expected: crc,
                                        found: calculated_crc,
                                    });
                                }
                            }
                        }
                        HunkPayload::Mini(val) => {
                            let be = val.to_be_bytes();
                            for chunk in dest.chunks_mut(8) {
                                let len = chunk.len().min(8);
                                chunk.copy_from_slice(&be[..len]);
                            }
                        }
                        HunkPayload::Direct(buf) => {
                            dest.copy_from_slice(&buf);
                        }
                    }
                    Ok(())
                });

            #[cfg(not(feature = "rayon"))]
            let decompressed_results: Result<(), ChdError> = current_batch_output
                .chunks_exact_mut(hb)
                .zip(batch_items)
                .try_for_each(|(dest, (_h, payload))| -> Result<(), ChdError> {
                    match payload {
                        HunkPayload::Compressed { fourcc, data, crc } => {
                            decompress_hunk(fourcc, &data, dest)?;
                            if version >= 5 {
                                let calculated_crc = crc16(dest, 0xffff);
                                if calculated_crc != crc {
                                    return Err(ChdError::CrcMismatch {
                                        expected: crc,
                                        found: calculated_crc,
                                    });
                                }
                            }
                        }
                        HunkPayload::Uncompressed { data, crc } => {
                            dest.copy_from_slice(&data);
                            if version >= 5 && is_compressed {
                                let calculated_crc = crc16(dest, 0xffff);
                                if calculated_crc != crc {
                                    return Err(ChdError::CrcMismatch {
                                        expected: crc,
                                        found: calculated_crc,
                                    });
                                }
                            }
                        }
                        HunkPayload::Mini(val) => {
                            let be = val.to_be_bytes();
                            for chunk in dest.chunks_mut(8) {
                                let len = chunk.len().min(8);
                                chunk.copy_from_slice(&be[..len]);
                            }
                        }
                        HunkPayload::Direct(buf) => {
                            dest.copy_from_slice(&buf);
                        }
                    }
                    Ok(())
                });

            decompressed_results?;

            for (i, h) in (cur_hunk..=batch_end).enumerate() {
                for_each_hunk(h, &current_batch_output[i * hb..(i + 1) * hb])?;
            }

            cur_hunk = batch_end + 1;
        }

        Ok(())
    }

    /// Extracts a range of bytes directly to a writer, using multi-threaded parallel decompression where possible.
    pub fn extract_range_parallel<W: Write>(
        &mut self,
        offset: u64,
        length: u64,
        writer: &mut W,
    ) -> Result<(), ChdError> {
        self.extract_range_parallel_with_progress(offset, length, writer, |_| {})
    }

    /// Extracts a range of bytes directly to a writer with progress reporting,
    /// using multi-threaded parallel decompression where possible.
    pub fn extract_range_parallel_with_progress<W: Write, F>(
        &mut self,
        offset: u64,
        length: u64,
        writer: &mut W,
        mut progress: F,
    ) -> Result<(), ChdError>
    where
        F: FnMut(ProgressStatus),
    {
        if length == 0 {
            return Ok(());
        }

        let total_bytes = self.header.logical_bytes;
        let read_end = offset
            .checked_add(length)
            .ok_or_else(|| ChdError::InvalidData("read range overflow".into()))?;

        if read_end > total_bytes {
            return Err(ChdError::InvalidData(format!(
                "read beyond logical bytes: {} > {}",
                read_end, total_bytes
            )));
        }

        let hunk_bytes = self.header.hunk_bytes as u64;
        let first_hunk = offset / hunk_bytes;
        let last_hunk = (read_end - 1) / hunk_bytes;
        let count = last_hunk - first_hunk + 1;

        let mut completed_bytes = 0u64;
        progress(ProgressStatus::new(
            OperationPhase::Extracting,
            0,
            length,
            None,
        ));

        self.read_hunks_parallel(first_hunk, count, |h, hunk_slice| {
            let start = if h == first_hunk {
                (offset % hunk_bytes) as usize
            } else {
                0
            };
            let end = if h == last_hunk {
                ((read_end - 1) % hunk_bytes) as usize + 1
            } else {
                hunk_slice.len()
            };
            writer.write_all(&hunk_slice[start..end])?;
            completed_bytes += (end - start) as u64;
            progress(ProgressStatus::new(
                OperationPhase::Extracting,
                completed_bytes,
                length,
                None,
            ));
            Ok(())
        })
    }

    /// Reads all metadata entries from the container.
    pub fn read_all_metadata(&mut self) -> Result<Vec<MetadataEntry>, ChdError> {
        read_all_metadata(&mut self.reader, self.header.meta_offset)
    }

    /// Verifies the raw and overall SHA-1 integrity of the container.
    pub fn verify<F>(&mut self, mut progress: F) -> Result<VerifyResult, ChdError>
    where
        F: FnMut(ProgressStatus),
    {
        if !self.header.is_compressed() {
            return Ok(VerifyResult {
                is_compressed: false,
                has_checksum: true,
                actual_raw_sha1: self.header.raw_sha1,
                expected_raw_sha1: self.header.raw_sha1,
                raw_sha1_matched: true,
                actual_overall_sha1: self.header.sha1,
                expected_overall_sha1: self.header.sha1,
                overall_sha1_matched: true,
            });
        }

        if self.header.raw_sha1 == [0u8; 20] {
            return Ok(VerifyResult {
                is_compressed: true,
                has_checksum: false,
                actual_raw_sha1: [0u8; 20],
                expected_raw_sha1: [0u8; 20],
                raw_sha1_matched: true,
                actual_overall_sha1: [0u8; 20],
                expected_overall_sha1: [0u8; 20],
                overall_sha1_matched: true,
            });
        }

        let total_bytes = self.header.logical_bytes;
        let mut hasher = Sha1::new();
        let chunk_size = 65536.min(total_bytes) as usize;
        let mut buffer = vec![0u8; chunk_size];

        let mut offset = 0u64;
        while offset < total_bytes {
            progress(ProgressStatus::new(
                OperationPhase::Verifying,
                offset,
                total_bytes,
                None,
            ));
            let to_read = ((total_bytes - offset) as usize).min(buffer.len());
            self.read_bytes(offset, &mut buffer[..to_read])?;
            hasher.update(&buffer[..to_read]);
            offset += to_read as u64;
        }
        progress(ProgressStatus::new(
            OperationPhase::Verifying,
            total_bytes,
            total_bytes,
            None,
        ));

        let actual_raw_sha1: [u8; 20] = hasher.finalize().into();
        let raw_sha1_matched = actual_raw_sha1 == self.header.raw_sha1;

        let metadata = self.read_all_metadata()?;
        let actual_overall_sha1 = compute_overall_sha1(actual_raw_sha1, &metadata);
        let overall_sha1_matched = actual_overall_sha1 == self.header.sha1;

        Ok(VerifyResult {
            is_compressed: true,
            has_checksum: true,
            actual_raw_sha1,
            expected_raw_sha1: self.header.raw_sha1,
            raw_sha1_matched,
            actual_overall_sha1,
            expected_overall_sha1: self.header.sha1,
            overall_sha1_matched,
        })
    }

    /// Gathers high-level information about the CHD container.
    pub fn info(&mut self) -> Result<ChdInfo, ChdError> {
        let file_size = self.reader.seek(SeekFrom::End(0))?;
        let metadata = self.read_all_metadata()?;

        Ok(ChdInfo {
            version: self.header.version,
            logical_bytes: self.header.logical_bytes,
            hunk_bytes: self.header.hunk_bytes,
            hunk_count: self.header.hunk_count(),
            unit_bytes: self.header.unit_bytes,
            unit_count: self.header.unit_count(),
            compressors: self.header.compressors,
            file_size,
            raw_sha1: self.header.raw_sha1,
            sha1: self.header.sha1,
            parent_sha1: self.header.parent_sha1,
            metadata_count: metadata.len(),
        })
    }
}

impl<R: Read + Write + Seek> ChdFile<R> {
    /// Updates the raw SHA-1 and overall SHA-1 in the file header in-place.
    pub fn set_raw_sha1(&mut self, new_raw_sha1: [u8; 20]) -> Result<(), ChdError> {
        let raw_offset = self.header.raw_sha1_offset();
        self.reader.seek(SeekFrom::Start(raw_offset))?;
        self.reader.write_all(&new_raw_sha1)?;
        self.header.raw_sha1 = new_raw_sha1;

        if self.header.version >= 4 {
            let metadata = self.read_all_metadata()?;
            let new_overall_sha1 = compute_overall_sha1(new_raw_sha1, &metadata);

            let overall_offset = self.header.sha1_offset();
            self.reader.seek(SeekFrom::Start(overall_offset))?;
            self.reader.write_all(&new_overall_sha1)?;
            self.header.sha1 = new_overall_sha1;
        } else {
            self.header.sha1 = new_raw_sha1;
        }

        self.reader.flush()?;
        Ok(())
    }
}