rvz 0.1.5

RVZ compression 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
// SPDX-License-Identifier: LGPL-2.1-or-later OR GPL-2.0-or-later OR MPL-2.0
// SPDX-FileCopyrightText: 2024 Gabriel Marcano <gabemarcano@yahoo.com>

use crate::error::Error;
use crate::region::Region;
use crate::region::RegionType;

use std::cmp;
use std::fmt;
use std::io;
use std::io::Cursor;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;

use byteorder::BigEndian;
use byteorder::ReadBytesExt;

use bzip2::read::BzDecoder;
use zstd::Decoder;

use sha1::Digest;
use sha1::Sha1;

/// Contains the computed hashes for a single partition on the disk.
///
/// # Hash layout found per sector:
///
/// 31 SHA-1 hashes, H0, one for each block of 0x400 bytes of decrypted user
///    data in this sector (0x8000)
/// 20 bytes of padding (0x00)
/// 8 SHA-1 hashes, H1, one for cluster in a subgroup (8 sectors in a
///   subgroup). Each hash is a hash of the bytes [0x000, 0x26C), or the H0
///   hashes.
/// 32 bytes of padding (0x00)
/// 8 SHA-1 hashes, H2, for each subgroup in the current group (8 subgroups
///   per group). Hashes H1 for each subgroup.
/// 32 bytes of padding (0x00)
#[derive(Debug, Default)]
pub struct Hashes {
    pub h0: Vec<[[u8; 20]; 31]>,
    pub h1: Vec<[[u8; 20]; 8]>,
    pub h2: Vec<[[u8; 20]; 8]>,
    pub h3: Vec<[u8; 20]>,
}

/// Holds all of the [`Rvz`] metadata required to parse the archive.
///
/// It also holds computed hashes, if these are computed with [`Rvz::compute_hashes`].
#[derive(Debug)]
pub struct Metadata {
    /// Primary RVZ header metadata.
    pub header: Header,
    /// Metadata about the disk, compression, and regions
    pub disc: Disc,
    /// Metadata about partitions in Wii disks.
    pub partitions: Vec<Partition>,
    /// Metadata about data not in partitions.
    pub raw_data: Vec<RawData>,
    /// Contains all RVZ groups (and thus all archived data).
    pub groups: Vec<Group>,
    /// Describes all data regions of the disk (except for a little bit of trailing data at the end
    /// of the disk, which is assumed to be all zeroes).
    pub regions: Vec<Region>,
    /// Contains the hashes of each partition, if they have been computed.
    pub hashes: Vec<Hashes>,
}

struct Io<T: Seek + Read> {
    io: T,
    position: u64,
}

/// RVZ object representing the archive and IO.
pub struct Rvz<T: Seek + Read> {
    /// [`Rvz`] metadata.
    pub metadata: Metadata,
    io: Io<T>,
}

pub trait HeaderRead {
    /// Checks if the RVZ file magic is in the IO instance.
    fn has_rvz_magic(&mut self) -> bool;

    /// Reads the main RVZ header.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if an error occured while reading from the underlying IO instance.
    fn read_rvz_header(&mut self) -> Result<Header, Error>;

    /// Reads the RVZ disc header.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if an error occured while reading from the underlying IO instance.
    fn read_rvz_disc(&mut self) -> Result<Disc, Error>;

    /// Reads the RVZ partitions data headers.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if an error occured while reading from the underlying IO instance.
    fn read_rvz_partitions(&mut self, disc: &Disc) -> Result<Vec<Partition>, Error>;

    /// Reads the RVZ raw data section headers.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if an error occured while reading from the underlying IO instance.
    fn read_rvz_raw_datas(&mut self, disc: &Disc) -> Result<Vec<RawData>, Error>;

    /// Reads the RVZ group headers.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if an error occured while reading from the underlying IO instance.
    fn read_rvz_groups(&mut self, disc: &Disc) -> Result<Vec<Group>, Error>;
}

pub trait GroupExceptionRead {
    /// Reads the RVZ exception list at the current position.
    ///
    /// # Errors
    ///
    /// [`io::Error`] if an error occured while reading from the underlying IO instance.
    fn read_rvz_exceptions(&mut self) -> io::Result<ExceptionList>;
}

/// Returns the start of the next region relative to the current position.
fn next_start(position: u64, regions: &[Region]) -> Option<u64> {
    let mut result = None;
    for region in regions {
        if position < region.start() && !region.contains(position) {
            result = Some(region.start());
        }
    }
    result
}

impl<T: Read + Seek> Seek for Rvz<T> {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        Ok(self.io.seek_io(pos, &self.metadata.header))
    }
}

impl<T: Read + Seek> Rvz<T> {
    /// Pre-computes the partition hashes so that when reading from the RVZ hash offsets return
    /// valid data.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if some IO error took place.
    pub fn compute_hashes(&mut self) -> Result<&Vec<Hashes>, Error> {
        self.metadata.hashes = self.io.compute_hashes(&self.metadata)?;
        Ok(&self.metadata.hashes)
    }
}

const H0_ZERO_HASH: [u8; 20] = [
    0x26, 0x94, 0x62, 0xc3, 0xc0, 0x85, 0xad, 0x49, 0x3d, 0x26, 0xca, 0x70, 0xa0, 0x0c, 0xb7, 0x26,
    0x8c, 0x7b, 0xa0, 0x4c,
];
const H1_ZERO_HASH: [u8; 20] = [
    0x9e, 0x69, 0xb0, 0xac, 0x67, 0x72, 0x95, 0xa0, 0xb4, 0x57, 0x14, 0xdd, 0x84, 0xd5, 0xfd, 0x4d,
    0x24, 0x63, 0x93, 0x66,
];

impl<T: Read + Seek> Io<T> {
    /// Seeks to the requested position.
    pub fn seek_io(&mut self, pos: SeekFrom, header: &Header) -> u64 {
        // It's valid if the position is past the end-- this should return act as EOF on any
        // subsequent reads
        self.position = match pos {
            SeekFrom::Start(offset) => offset,
            SeekFrom::End(offset) => u64::from(header.disc_size).wrapping_add_signed(-offset),
            SeekFrom::Current(offset) => self.position.wrapping_add_signed(offset),
        };
        self.position
    }

    /// Reads data into the specified buffer, and returns how much was read.
    ///
    /// This function handles all of the logic for unpacking and reading the RVZ compressed data.
    ///
    /// # Errors
    ///
    /// [`io::Error`] if any kind of IO error takes place (while reading or seeking).
    pub fn read_io(&mut self, buf: &mut [u8], metadata: &Metadata) -> io::Result<usize> {
        let mut left = buf.len();
        let mut buf = Cursor::new(buf);
        let total = left;

        let mut position = self.position;
        let header = &metadata.header;
        let disc = &metadata.disc;
        let regions = &metadata.regions;

        while left != 0 {
            // EOF handling
            if position >= header.iso_file_size {
                self.position = position;
                return Ok(total - left);
            }

            let region = regions.iter().find(|r| r.contains(position));

            if let Some(region) = region {
                let amount = if position < 0x80 {
                    // Special case, when reading from the header don't read from the
                    // compressed block
                    let amount = cmp::min(0x80 - usize::try_from(position).unwrap(), left);
                    let tmp_position = usize::try_from(position).unwrap();
                    buf.write_all(&disc.disc_head[tmp_position..tmp_position + amount])?;
                    u64::try_from(amount).unwrap()
                } else {
                    region.read_region(&mut self.io, metadata, position, &mut buf)?
                };
                left -= usize::try_from(amount).unwrap();
                position += amount;
            } else {
                // Treat the space between position and the next region as padding
                let end = next_start(position, regions);

                // If we can't find a next region, assume it's all padding until the end of the
                // disk
                let end = end.unwrap_or(header.iso_file_size);
                let amount = cmp::min(end - position, u64::try_from(left).unwrap());
                let mut null = io::repeat(0).take(amount);
                let amount = io::copy(&mut null, &mut buf)?;
                left -= usize::try_from(amount).unwrap();
                position += amount;
            }
        }

        self.position = position;

        Ok(total)
    }

    fn compute_h0(
        &mut self,
        metadata: &Metadata,
        partition: &Partition,
    ) -> io::Result<Vec<[[u8; 20]; 31]>> {
        // H0
        let mut h0_table = vec![];
        for data in partition.partition_data {
            for sector in data.first_sector..data.first_sector + data.sector_count {
                let offset = u64::from(sector) * 0x8000 + 0x400;
                self.seek_io(SeekFrom::Start(offset), &metadata.header);
                let mut data = [0u8; 0x7C00];
                self.read_io(&mut data, metadata)?;
                let mut input_cursor = Cursor::new(&data);
                let mut h0 = [[0u8; 20]; 31];
                for hash in &mut h0 {
                    let mut sha1 = Sha1::new();
                    io::copy(&mut (&mut input_cursor).take(0x400), &mut sha1)?;
                    hash.clone_from_slice(sha1.finalize().as_slice());
                }

                h0_table.push(h0);
            }
        }
        Ok(h0_table)
    }

    fn compute_h1(partition: &Partition, h0_table: &[[[u8; 20]; 31]]) -> Vec<[[u8; 20]; 8]> {
        // H1
        let mut h1_table = vec![];

        let sector_count =
            partition.partition_data[0].sector_count + partition.partition_data[1].sector_count;
        let subgroup_count = usize::try_from(sector_count / 8).unwrap();
        let partial_subgroup = !sector_count.is_multiple_of(8);

        for i in 0..subgroup_count {
            let mut h1_hash = [[0u8; 20]; 8];
            for j in 0..8 {
                let mut h1_sha1 = Sha1::new();
                for hash in &h0_table[j + i * 8] {
                    h1_sha1.update(hash);
                }
                h1_hash[j] = h1_sha1.finalize().into();
            }
            h1_table.push(h1_hash);
        }

        if partial_subgroup {
            let mut h1_hash = [[0u8; 20]; 8];

            let have = (sector_count % 8) as usize;
            let missing = 8 - have;
            for j in 0..have {
                let mut h1_sha1 = Sha1::new();
                for hash in &h0_table[subgroup_count * 8 + j] {
                    h1_sha1.update(hash);
                }
                h1_hash[j] = h1_sha1.finalize().into();
            }

            for j in 0..missing {
                h1_hash[have + j] = H0_ZERO_HASH;
            }
            h1_table.push(h1_hash);
        }
        h1_table
    }

    fn compute_h2(h1_table: &[[[u8; 20]; 8]]) -> Vec<[[u8; 20]; 8]> {
        let mut h2_table = vec![];
        // H2
        let group_count = h1_table.len() / 8;
        let subgroup_leftover = h1_table.len() % 8;
        let partial_group = !subgroup_leftover.is_multiple_of(8);

        for i in 0..group_count {
            let mut h2_hash = [[0u8; 20]; 8];
            for j in 0..8 {
                let mut h2_sha1 = Sha1::new();
                for hash in &h1_table[j + i * 8] {
                    h2_sha1.update(hash);
                }
                h2_hash[j] = h2_sha1.finalize().into();
            }
            h2_table.push(h2_hash);
        }

        if partial_group {
            let mut h2_hash = [[0u8; 20]; 8];
            let have = subgroup_leftover;
            let missing = 8 - have;
            for j in 0..have {
                let mut h2_sha1 = Sha1::new();
                for hash in &h1_table[group_count * 8 + j] {
                    h2_sha1.update(hash);
                }
                h2_hash[j] = h2_sha1.finalize().into();
            }

            for j in 0..missing {
                h2_hash[have + j] = H1_ZERO_HASH;
            }
            h2_table.push(h2_hash);
        }
        h2_table
    }

    /// Pre-computes the partition hashes so that subsequent [`Io`] calls return valid data when
    /// reading partition hash offsets.
    ///
    /// This function reads all of the data from all of the partitions to compute SHA1 H0, H1, and
    /// H2 hashes. As a result, this is extremely slow. If this function is not called before
    /// reading any hash offset in a partition, those bytes will be returned as zeroes.
    ///
    /// See <https://wiibrew.org/wiki/Wii_disc> for details about the hashes and what they mean (in
    /// summary, H0 contains hashes for a sector, H1 for a collection of sectors, and H2 for a
    /// collection of those collection of sectors).
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if any IO error took place while reading or seeking.
    pub fn compute_hashes(&mut self, metadata: &Metadata) -> Result<Vec<Hashes>, Error> {
        // Hash layout:
        // 31 SHA-1 hashes, H0, one for each block of 0x400 bytes of decrypted user
        //    data in this cluster (0x8000)
        // 20 bytes of padding (0x00)
        // 8 SHA-1 hashes, H1, one for cluster in a subgroup (8 clusters in
        //   subgroup). Each hash is a hash of the bytes [0x000, 0x26C), or the H0
        //   hashes.
        // 32 bytes of padding (0x00)
        // 8 SHA-1 hashes, H2, for each subgroup in the current group (8 subgroups
        //   per group). Hashes H1 for each subgroup.
        // 32 bytes of padding (0x00)

        let mut hashes = vec![];
        for partition in &metadata.partitions {
            let h0_table = self.compute_h0(metadata, partition)?;
            let h1_table = Self::compute_h1(partition, &h0_table);
            let h2_table = Self::compute_h2(&h1_table);

            // FIXME H3

            hashes.push(Hashes {
                h0: h0_table,
                h1: h1_table,
                h2: h2_table,
                h3: Vec::default(),
            });
        }
        Ok(hashes)
    }
}

impl<T: Read + Seek> Read for Rvz<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.io.read_io(buf, &self.metadata)
    }
}

impl Compression {
    /// Wraps the given Read object to treat it per the compression type .
    ///
    /// # Errors
    ///
    /// [`io::Error`] for any error while trying to parse/prepare the compression decoder.
    pub fn io<'io, T: Read + 'io>(&self, io: T) -> io::Result<Box<dyn Read + 'io>> {
        let io: Box<dyn Read> = match self {
            Self::None => Box::new(io),
            Self::Zstd => Box::new(Decoder::new(io)?),
            Self::Bzip2 => Box::new(BzDecoder::new(io)),
            // FIXME missing LZMA and LZMA2, since we need to handle special parameters, found in
            // disc.compressor_data
            //Self::Lzma => Box::new(LzmaDecoder::new(io)),
            //Self::Lzma2 => Box::new(Lzma2Decoder::new(io)),
            _ => panic!("LZMA/2 not implemented"),
        };
        Ok(io)
    }
}

impl<T: Read + Seek> HeaderRead for T {
    fn has_rvz_magic(&mut self) -> bool {
        let Ok(_) = self.seek(SeekFrom::Start(0)) else {
            return false;
        };
        let Ok(magic) = self.read_u32::<BigEndian>() else {
            return false;
        };

        magic == 0x5256_5a01
    }

    fn read_rvz_header(&mut self) -> Result<Header, Error> {
        self.seek(SeekFrom::Start(0))?;
        let mut magic = [0u8; 4];
        self.read_exact(&mut magic)?;
        let version = self.read_u32::<BigEndian>()?;
        let version_compatible = self.read_u32::<BigEndian>()?;
        let disc_size = self.read_u32::<BigEndian>()?;
        let mut disc_hash = [0u8; 20];
        self.read_exact(&mut disc_hash)?;
        let iso_file_size = self.read_u64::<BigEndian>()?;
        let rvz_file_size = self.read_u64::<BigEndian>()?;
        let mut file_head_hash = [0u8; 20];
        self.read_exact(&mut file_head_hash)?;

        Ok(Header {
            magic,
            version,
            version_compatible,
            disc_size,
            disc_hash,
            iso_file_size,
            rvz_file_size,
            file_head_hash,
        })
    }

    fn read_rvz_disc(&mut self) -> Result<Disc, Error> {
        self.seek(SeekFrom::Start(0x48))?;
        let disc_type = self.read_u32::<BigEndian>()?.try_into()?;
        let compression = self.read_u32::<BigEndian>()?.try_into()?;
        let compression_level = self.read_i32::<BigEndian>()?;
        let chunk_size = self.read_u32::<BigEndian>()?;
        let mut disc_head = [0u8; 0x80];
        self.read_exact(&mut disc_head)?;
        let partition_count = self.read_u32::<BigEndian>()?;
        let partition_size = self.read_u32::<BigEndian>()?;
        let partitions_offset = self.read_u64::<BigEndian>()?;
        let mut partitions_hash = [0u8; 20];
        self.read_exact(&mut partitions_hash)?;
        let raw_data_count = self.read_u32::<BigEndian>()?;
        let raw_data_offset = self.read_u64::<BigEndian>()?;
        let raw_data_size = self.read_u32::<BigEndian>()?;
        let group_count = self.read_u32::<BigEndian>()?;
        let group_offset = self.read_u64::<BigEndian>()?;
        let group_size = self.read_u32::<BigEndian>()?;
        let compressor_data_length = self.read_u8()?;
        let mut compressor_data = [0u8; 7];
        self.read_exact(&mut compressor_data)?;

        Ok(Disc {
            disc_type,
            compression,
            compression_level,
            chunk_size,
            disc_head,
            partition_count,
            partition_size,
            partitions_offset,
            partitions_hash,
            raw_data_count,
            raw_data_offset,
            raw_data_size,
            group_count,
            group_offset,
            group_size,
            compressor_data_length,
            compressor_data,
        })
    }

    fn read_rvz_partitions(&mut self, disc: &Disc) -> Result<Vec<Partition>, Error> {
        self.seek(SeekFrom::Start(disc.partitions_offset))?;

        let mut partitions = vec![];
        for _ in 0..disc.partition_count {
            let mut partition_key = [0u8; 16];
            self.read_exact(&mut partition_key)?;
            let partition_data = [
                PartitionData {
                    first_sector: self.read_u32::<BigEndian>()?,
                    sector_count: self.read_u32::<BigEndian>()?,
                    group_index: self.read_u32::<BigEndian>()?,
                    group_count: self.read_u32::<BigEndian>()?,
                },
                PartitionData {
                    first_sector: self.read_u32::<BigEndian>()?,
                    sector_count: self.read_u32::<BigEndian>()?,
                    group_index: self.read_u32::<BigEndian>()?,
                    group_count: self.read_u32::<BigEndian>()?,
                },
            ];

            partitions.push(Partition {
                partition_key,
                partition_data,
            });
        }
        Ok(partitions)
    }

    fn read_rvz_raw_datas(&mut self, disc: &Disc) -> Result<Vec<RawData>, Error> {
        self.seek(SeekFrom::Start(disc.raw_data_offset))?;
        let mut io = self.take(disc.raw_data_size.into());

        let mut decompressor = disc.compression.io(&mut io)?;

        let mut result = vec![];
        for _ in 0..disc.raw_data_count {
            let raw_data_offset = decompressor.read_u64::<BigEndian>()?;
            let raw_data_size = decompressor.read_u64::<BigEndian>()?;
            let group_index = decompressor.read_u32::<BigEndian>()?;
            let group_count = decompressor.read_u32::<BigEndian>()?;

            result.push(RawData {
                raw_data_offset,
                raw_data_size,
                group_index,
                group_count,
            });
        }
        Ok(result)
    }

    fn read_rvz_groups(&mut self, disc: &Disc) -> Result<Vec<Group>, Error> {
        self.seek(SeekFrom::Start(disc.group_offset))?;

        let mut io = self.take(disc.group_size.into());
        let mut decompressor = disc.compression.io(&mut io)?;
        let mut result = vec![];
        for _ in 0..disc.group_count {
            let data_offset_div4 = decompressor.read_u32::<BigEndian>()?;
            let data_size = decompressor.read_u32::<BigEndian>()?;
            let packed_size = decompressor.read_u32::<BigEndian>()?;

            result.push(Group {
                data_offset_div4,
                data_size,
                packed_size,
            });
        }
        Ok(result)
    }
}

impl<T: Read> GroupExceptionRead for T {
    fn read_rvz_exceptions(&mut self) -> Result<ExceptionList, io::Error> {
        let exception_count = self.read_u16::<BigEndian>()?;

        let mut exception_list = vec![];
        for _ in 0..exception_count {
            let offset = self.read_u16::<BigEndian>()?;
            let mut hash = [0u8; 20];
            self.read_exact(&mut hash)?;
            exception_list.push(Exception { offset, hash });
        }

        Ok(ExceptionList(exception_list))
    }
}

impl<T: Read + Seek> Rvz<T> {
    /// Builds a new RVZ object.
    ///
    /// This reads from the given IO object to populate RVZ headers.
    ///
    /// # Errors
    ///
    /// [`Error::Io`] if some IO error took place while reading data from the underlying IO object.
    /// [`Error::Parse`] if the [`Disc::partition_size`] field is not equal to the expected 48.
    pub fn new(mut io: T) -> Result<Self, Error> {
        let header = io.read_rvz_header()?;
        let disc = io.read_rvz_disc()?;

        if disc.partition_size != 48 {
            return Err(Error::Parse("unexpected RVZ disc partition size".into()));
        }

        let partitions = io.read_rvz_partitions(&disc)?;
        let raw_data = io.read_rvz_raw_datas(&disc)?;
        let groups = io.read_rvz_groups(&disc)?;

        // build a table of regions, used in Read to figure out where to extract data from.
        let mut regions = vec![];
        for raw in &raw_data {
            let start = raw.raw_data_offset & !0x7FFF;
            let extra = raw.raw_data_offset & 0x7FFF;
            let size = raw.raw_data_size + extra;
            let end = start + size;
            regions.push(Region {
                range: (start..end).into(),
                type_: RegionType::Raw(*raw),
            });
        }
        for partition in &partitions {
            for data in &partition.partition_data {
                let start = u64::from(data.first_sector) * 0x8000;
                let end = start + u64::from(data.sector_count) * 0x8000;
                regions.push(Region {
                    range: (start..end).into(),
                    type_: RegionType::Partition(*partition, *data),
                });
            }
        }

        let metadata = Metadata {
            header,
            disc,
            partitions,
            raw_data,
            groups,
            regions,
            hashes: Vec::default(),
        };

        let io = Io { io, position: 0 };

        Ok(Self { metadata, io })
    }
}

/// Represents the metadata held by the RVZ main header.
#[derive(Debug)]
pub struct Header {
    /// The magic bytes of the RVZ header (should be "RVZ\x1")
    pub magic: [u8; 4],
    /// The RVZ format version
    pub version: u32,
    /// The RVZ format version this RVZ is compatible with
    pub version_compatible: u32,
    /// The size of the [`Disc`] header in the RVZ file.
    pub disc_size: u32,
    /// The SHA-1 of the [`Disc`] header in the RVZ file.
    pub disc_hash: [u8; 20],
    /// The original file size of the disk that's currently packed into the RVZ file.
    pub iso_file_size: u64,
    /// The size of the RVZ file.
    pub rvz_file_size: u64,
    /// The SHA-1 of the [`Header`] (this) header in the RVZ file, excluding this field.
    pub file_head_hash: [u8; 20],
}

#[derive(Debug, Clone, Copy)]
pub enum DiscType {
    Unknown,
    GameCube,
    Wii,
}

impl fmt::Display for DiscType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Unknown => write!(f, "unknown"),
            Self::GameCube => write!(f, "GameCube"),
            Self::Wii => write!(f, "Wii"),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum Compression {
    None,
    Bzip2,
    Lzma,
    Lzma2,
    Zstd,
}

impl fmt::Display for Compression {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::None => write!(f, "none"),
            Self::Bzip2 => write!(f, "BZIP2"),
            Self::Lzma => write!(f, "LZMA"),
            Self::Lzma2 => write!(f, "LZMA2"),
            Self::Zstd => write!(f, "ZSTD"),
        }
    }
}

impl TryFrom<u32> for Compression {
    type Error = Error;
    fn try_from(val: u32) -> Result<Self, Error> {
        match val {
            0 => Ok(Self::None),
            2 => Ok(Self::Bzip2),
            3 => Ok(Self::Lzma),
            4 => Ok(Self::Lzma2),
            5 => Ok(Self::Zstd),
            _ => Err(Error::Parse("unknown compression found".into())),
        }
    }
}

impl TryFrom<u32> for DiscType {
    type Error = Error;
    fn try_from(val: u32) -> Result<Self, Error> {
        match val {
            0 => Ok(Self::Unknown),
            1 => Ok(Self::GameCube),
            2 => Ok(Self::Wii),
            _ => Err(Error::Parse("unknown disc type found".into())),
        }
    }
}

/// Represents the metadata held by the RVZ disc descriptor header.
#[derive(Debug)]
pub struct Disc {
    /// The type of disk (1: GCN, 2: Wii, 0: Unknown)
    pub disc_type: DiscType,
    /// The compression algorithm to use
    pub compression: Compression,
    /// The compression level to use with the algorithm selected
    pub compression_level: i32,
    /// The size of the chunks of data compressed.
    ///
    /// Typically a multiple of 2MB, but RVZ allows for 32 KiB minimum sized chunks, and above but
    /// these must be powers of two. Sizes larger than 2 MiB do not need to be powers of 2, just an
    /// integer multiple of 2 MiB.
    pub chunk_size: u32,
    /// Raw data held in the first 0x80 bytes of the original disk image.
    pub disc_head: [u8; 0x80],
    /// The number of [`Partition`] stored.
    pub partition_count: u32,
    /// The size in the file of a single [`Partition`].
    pub partition_size: u32,
    /// The offset in the file where all of the [`Partition`] are stored sequentially
    /// (uncompressed).
    pub partitions_offset: u64,
    /// The SHA-1 of all of the [`Partition`].
    pub partitions_hash: [u8; 20],
    /// The number of [`RawData`] in the file (compressed).
    pub raw_data_count: u32,
    /// The offset to the [`RawData`] in the file.
    pub raw_data_offset: u64,
    /// The total compressed size of all [`RawData`].
    pub raw_data_size: u32,
    /// The number of [`Group`] in the file.
    pub group_count: u32,
    /// The offset to the [`Group`] in the file (compressed).
    pub group_offset: u64,
    /// The total compressed size of all [`Group`].
    pub group_size: u32,
    /// The number of used bytes in the [`Disc::compressor_data`] field.
    pub compressor_data_length: u8,
    /// Compressor specific data.
    ///
    /// LZMA or LZMA2 use this. The data is the same as used by the 7-Zip SDK apparently. For
    /// example, for LZMA the data is 5 bytes long, where the first byte encodes the `lc`, `pb`,
    /// and `lp` parameters, and the other four bytes encode the dictionary size in little endian.
    pub compressor_data: [u8; 7],
}

/// Describes the location of data on the disc, as well as where in the RVZ group list it resides.
#[derive(Debug, Copy, Clone)]
pub struct PartitionData {
    /// The first sector of the original disk image covered by this structure.
    pub first_sector: u32,
    /// The number of sectors covered.
    pub sector_count: u32,
    /// The index to the first group containing the sector data.
    pub group_index: u32,
    /// The number of groups used.
    pub group_count: u32,
}

/// Describes Wii partitions
#[derive(Debug, Copy, Clone)]
pub struct Partition {
    /// The title key for this partition (128-bit AES), used for re-encrypting the partition data.
    ///
    /// This key can be used as is, without decrypting it using the Wii common key.
    pub partition_key: [u8; 16],
    /// Apparently index 0 contains all data in the partition through to the end of the FST,
    /// rounded to the next 2 MiB boundary. index 1 contains all other data.
    pub partition_data: [PartitionData; 2],
}

/// Describes the location of raw data on the disc, as well as where in the RVZ group list it
/// resides.
#[derive(Debug, Copy, Clone)]
pub struct RawData {
    /// The offset on the original disk image of the raw data.
    pub raw_data_offset: u64,
    /// The size of the raw data on the original disk image covered.
    pub raw_data_size: u64,
    /// The [`Group`] index of the first group that covers the raw data.
    pub group_index: u32,
    /// The number of [`Group`] used to cover this raw data.
    pub group_count: u32,
}

/// Describes an RVZ group, which describes where actual data is stored.
#[derive(Debug)]
pub struct Group {
    /// The offset to the group data in the RVZ file, divided by 4.
    pub data_offset_div4: u32,
    /// The size of the compressed data, including any [`ExceptionList`]s.
    ///
    /// The top bit is set when the data is compressed, and cleared otherwise. If the lower 31
    /// bytes are 0 it means that all data in the group is `0x00`, and the [`ExceptionList`]s if
    /// any contain no exceptions.
    pub data_size: u32,
    /// The size after decompressing but before decoding the RVZ packing. If 0 RVZ packing is not
    /// used.
    ///
    /// RVZ packing is an encoding scheme describing pseudo-random padding on GCN and Wii disks,
    /// which uses a lagged Fibonacci generator with parameters `f = xor`, `j = 32`, and `k = 521`.
    pub packed_size: u32,
}

/// Describes a hash exception. FIXME I don't really understand yet what these are.
#[derive(Debug)]
pub struct Exception {
    pub offset: u16,
    pub hash: [u8; 20],
}

/// A list of hash exceptions.
#[derive(Debug)]
pub struct ExceptionList(pub Vec<Exception>);