delharc 0.8.0

A library for parsing and extracting files from LHA/LZH archives.
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
//! # Decoding algorithms.
use core::{error, fmt};
use crate::{
    crc::Crc16,
    error::{DecompressionError, LhaHeaderError, LhaError, LhaResult},
    header::{CompressionMethod, LhaHeader},
    stub_io::{Read, Take, discard_to_end},
};

#[cfg(feature = "lz")]
mod lzs;
#[cfg(feature = "lz")]
mod lz5;
#[cfg(feature = "lh1")]
mod lhv1;
mod lhv2;
#[cfg(feature = "pm")]
mod pmarc;

#[cfg(feature = "lz")]
#[cfg_attr(docsrs, doc(cfg(feature = "lz")))]
pub use lzs::*;
#[cfg(feature = "lz")]
#[cfg_attr(docsrs, doc(cfg(feature = "lz")))]
pub use lz5::*;
#[cfg(feature = "lh1")]
#[cfg_attr(docsrs, doc(cfg(feature = "lh1")))]
pub use lhv1::*;
pub use lhv2::*;
#[cfg(feature = "pm")]
#[cfg_attr(docsrs, doc(cfg(feature = "pm")))]
pub use pmarc::*;

/// The interface used by decompression engines.
pub trait Decoder<R> {
    /// The error type required by the underlying reader.
    type Error: error::Error;
    /// Consume the decoder and return the underlying reader.
    fn into_inner(self) -> R;
    /// Get a reference to the underlying reader.
    ///
    /// Care should be taken to avoid modifying the internal I/O state of the
    /// underlying readers as doing so may corrupt the internal state of this
    /// `Decoder`.
    fn get_ref(&self) -> &R;
    /// Get a mutable reference to the underlying reader.
    ///
    /// Care should be taken to avoid modifying the internal I/O state of the
    /// underlying readers as doing so may corrupt the internal state of this
    /// `Decoder`.
    fn get_mut(&mut self) -> &mut R;
    /// Fill the whole `buffer` slice with decoded data.
    ///
    /// The caller should be aware of how large a buffer can be provided to not
    /// exceed the size of the decompressed file. Otherwise it can result in
    /// an unexpected EOF error, the decoder could produce meaningless data,
    /// or the decoder could return an error specific to its algorithm.
    fn fill_buffer(&mut self, buffer: &mut[u8]) -> Result<(), LhaError<Self::Error>>;
}

/// `LhaDecodeReader` provides a convenient way to parse and decode LHA/LZH files.
///
/// To read the current archived file's content use the [`std::io::Read`] trait
/// methods on the instance of this object. After reading until EOF, the checksum,
/// calculated by `LhaDecodeReader` during data decoding, should be verified using
/// [`LhaDecodeReader::crc_check()`].
///
/// To parse and decode the next archive file, call [`LhaDecodeReader::next_file()`]
/// or [`LhaDecodeReader::seek_next_file()`].
///
/// After parsing the next LHA header, a decompressed content of a file can be simply
/// read from the `LhaDecodeReader`, which will decompress it using a proper decoder,
/// indicated in the header, while reading data from the underlying stream.
///
/// If the compression method is not supported by the decoder, but otherwise the
/// header has been parsed successfully, invoke [`Self::is_decoder_supported()`] to
/// ensure you can actually read the file. Otherwise, trying to read from an
/// unsupported decoder will result in an error.
///
/// # `no_std`
/// Without the `std` feature in the absence of `std::io` the crate's [`Read`] trait
/// methods should be used instead to read the content of the decompressed files.
#[derive(Debug)]
pub struct LhaDecodeReader<R> {
    header: LhaHeader,
    crc: Crc16,
    output_length: u64,
    decoder: Option<DecoderAny<Take<R>>>
}

/// A pass-through (null) decoder for stored data without any compression
#[derive(Debug)]
pub struct PassthroughDecoder<R> {
    inner: R
}

/// A phony decoder object, used when compression method is unsupported.
///
/// Reading from it will always produce an error!
#[derive(Debug)]
pub struct UnsupportedDecoder<R> {
    inner: R
}

/// An error returned from methods of [`LhaDecodeReader`].
///
/// The error contains a source stream object that can be accessed or
/// recovered.
///
/// Alternatively, the error can be converted to the underlying [`LhaError`]
/// using [`From`] trait, thus discarding the contained reader.
///
/// Use [`error::Error::source()`] to access the underlying error.
pub struct LhaDecodeError<R: Read> {
    read: R,
    source: LhaError<R::Error>
}

/// A decoder enum allowing to work with multiple decoders, using a single object.
#[non_exhaustive]
#[derive(Debug)]
pub enum DecoderAny<R> {
    /// A pass-through (null) decoder for stored data without any compression
    PassthroughDecoder(PassthroughDecoder<R>),
    /// A phony decoder object, used when compression method is unsupported.
    ///
    /// Reading from it will always produce an error!
    UnsupportedDecoder(UnsupportedDecoder<R>),
    #[cfg(feature = "lz")]
    #[cfg_attr(docsrs, doc(cfg(feature = "lz")))]
    /// A decoder for the `-lzs-` compression method
    LzsDecoder(LzsDecoder<R>),
    #[cfg(feature = "lz")]
    #[cfg_attr(docsrs, doc(cfg(feature = "lz")))]
    /// A decoder for the `-lz5-` compression method
    Lz5Decoder(Lz5Decoder<R>),
    #[cfg(feature = "lh1")]
    #[cfg_attr(docsrs, doc(cfg(feature = "lh1")))]
    /// A decoder for the `-lh1-` compression method
    Lh1Decoder(Lh1Decoder<R>),
    /// A decoder for the `-lh4-` compression method
    Lh4Decoder(Lh5Decoder<R>),
    /// A decoder for the `-lh5-` compression method
    Lh5Decoder(Lh5Decoder<R>),
    /// A decoder for the `-lh6-` compression method
    Lh6Decoder(Lh7Decoder<R>),
    /// A decoder for the `-lh7-` compression method
    Lh7Decoder(Lh7Decoder<R>),
    #[cfg(feature = "lhx")]
    #[cfg_attr(docsrs, doc(cfg(feature = "lhx")))]
    /// A decoder for the `-lhx-` compression method
    LhxDecoder(LhxDecoder<R>),
    #[cfg(feature = "pm")]
    #[cfg_attr(docsrs, doc(cfg(feature = "pm")))]
    /// A decoder for the `-pm1-` compression method
    Pm1Decoder(Pm1Decoder<R>),
    #[cfg(feature = "pm")]
    #[cfg_attr(docsrs, doc(cfg(feature = "pm")))]
    /// A decoder for the `-pm2-` compression method
    Pm2Decoder(Pm2Decoder<R>),
}

macro_rules! decoder_any_dispatch {
    (($model:expr)($($spec:tt)*) => $expr:expr) => {
        match $model {
            DecoderAny::PassthroughDecoder($($spec)*) => $expr,
            DecoderAny::UnsupportedDecoder($($spec)*) => $expr,
            #[cfg(feature = "lz")]
            DecoderAny::LzsDecoder($($spec)*) => $expr,
            #[cfg(feature = "lz")]
            DecoderAny::Lz5Decoder($($spec)*) => $expr,
            #[cfg(feature = "lh1")]
            DecoderAny::Lh1Decoder($($spec)*) => $expr,
            DecoderAny::Lh4Decoder($($spec)*)|
            DecoderAny::Lh5Decoder($($spec)*) => $expr,
            DecoderAny::Lh6Decoder($($spec)*)|
            DecoderAny::Lh7Decoder($($spec)*) => $expr,
            #[cfg(feature = "lhx")]
            DecoderAny::LhxDecoder($($spec)*) => $expr,
            #[cfg(feature = "pm")]
            DecoderAny::Pm1Decoder($($spec)*) => $expr,
            #[cfg(feature = "pm")]
            DecoderAny::Pm2Decoder($($spec)*) => $expr,
        }
    };
}

/// A default implementation creates an instance of `LhaDecodeReader<R>`
/// with no decoder present and with a phony header.
impl<R: Read> Default for LhaDecodeReader<R> {
    fn default() -> Self {
        LhaDecodeReader {
            header: Default::default(),
            crc: Crc16::default(),
            output_length: 0,
            decoder: None
        }
    } 
}

impl<R: Read> LhaDecodeReader<R> where R::Error: error::Error {
    /// Return a new instance of `LhaDecodeReader<R>` after reading and parsing
    /// the first header from the stream.
    ///
    /// Provide a stream reader as `rd`.
    ///
    /// # Errors
    /// Return an error if the header could not be read or parsed.
    pub fn new(mut rd: R) -> Result<LhaDecodeReader<R>, LhaDecodeError<R>> {
        let header = match LhaHeader::read(rd.by_ref()).and_then(|h|
                    h.ok_or_else(|| LhaError::HeaderParse(LhaHeaderError::HeaderNotFound)))
        {
            Ok(h) => h,
            Err(e) => return Err(wrap_err(rd, e))
        };
        let decoder = DecoderAny::new_from_header(&header, rd);
        let crc = Crc16::default();
        Ok(LhaDecodeReader {
            header,
            crc,
            output_length: 0,
            decoder: Some(decoder)
        })
    }
    /// Attempt to read the first file header from a new source stream and initialize a decoder returning
    /// `Ok(true)` on success. Return `Ok(false)` if there are no more headers in the stream.
    ///
    /// Provide a stream reader as `rd`.
    ///
    /// When `Ok` is returned, regardles of the retuned boolean value, the inner reader is being always
    /// replaced with the given `rd`.
    ///
    /// When `Ok(false)` has been returned, trying to read from the decoder will result in an error.
    ///
    /// # Errors
    /// Returns an error if the header could not be read or parsed. In this instance the inner stream
    /// reader is not being replaced by a new one and the provided source stream can be retrieved from
    /// the returned error.
    pub fn begin_new(&mut self, mut rd: R) -> Result<bool, LhaDecodeError<R>> {
        let res = match LhaHeader::read(rd.by_ref()) {
            Ok(Some(header)) => {
                let decoder = DecoderAny::new_from_header(&header, rd);
                self.decoder = Some(decoder);
                self.header = header;
                true
            }
            Ok(None) => {
                let decoder = UnsupportedDecoder::new(rd.take(0));
                self.decoder = Some(DecoderAny::UnsupportedDecoder(decoder));
                false
            }
            Err(e) => return Err(wrap_err(rd, e))
        };
        self.crc.reset();
        self.output_length = 0;
        Ok(res)
    }
    /// Assign externally parsed header and decoder to this instance of `LhaDecodeReader<R>`.
    ///
    /// It is up to the caller to make sure the decoder matches the header.
    ///
    /// The decoder should be initialized with the reader limited by the [`Take`] wrapper
    /// with its limit set to the [`LhaHeader::compressed_size`] number of bytes.
    ///
    /// This method assumes the file will be read and decoded from its beginning.
    pub fn begin_with_header_and_decoder(&mut self, header: LhaHeader, decoder: DecoderAny<Take<R>>) {
        self.decoder = Some(decoder);
        self.header = header;
        self.crc.reset();
        self.output_length = 0;
    }
    /// Attempt to parse the header of the next archive's entry.
    ///
    /// The remaining content of the current file is being skipped if the
    /// current file's content has not been read entirely.
    ///
    /// On success returns `Ok(true)` if the next header has been read and
    /// parsed successfully. If there are no more headers, returns `Ok(false)`.
    ///
    /// # Note
    /// The remaining file data is being read and discarded into a buffer
    /// allocated on the stack. On the `std` platform, probably the better
    /// method is to call [`Self::seek_next_file()`] instead.
    ///
    /// # Errors
    /// Returns an error if the header could not be read or parsed. In this
    /// instance the underlying decoder will be destroyed, the stream source
    /// will be removed from this [`LhaDecodeReader`] and returned with an
    /// error object.
    ///
    /// # Panic
    /// Panics if called when the underlying stream reader has been already taken.
    ///
    /// # `no_std`
    /// To skip the remaining file data this function uses 8 KB stack-allocated
    /// buffer when called with `std` feature enabled. Without `std`, the buffer
    /// size is 512 bytes.
    ///
    /// See also [`LhaDecodeReader::next_file_with_sink()`].
    pub fn next_file(&mut self) -> Result<bool, LhaDecodeError<R>> {
        #[cfg(feature = "std")]
        {
            self.next_file_with_sink::<{8*1024}>()
        }
        #[cfg(not(feature = "std"))]
        {
            self.next_file_with_sink::<512>()
        }
    }
    /// Attempt to parse the header of the next archive's entry.
    ///
    /// See [`LhaDecodeReader::next_file()`] for a description of this method.
    ///
    /// Unlike [`Self::next_file()`] this method uses the [`std::io::Seek`]
    /// trait to skip over the remaining file data, but is only available with
    /// `std` feature enabled and requires `R` to implement `io::Seek`.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn seek_next_file(&mut self) -> Result<bool, LhaDecodeError<R>>
        where R: std::io::Seek + Read<Error=std::io::Error>
    {
        use std::io::SeekFrom;
        let limited_rd = self.decoder.take().expect("decoder not empty").into_inner();
        let remaining = limited_rd.limit();
        let mut rd = limited_rd.into_inner();
        if remaining != 0 {
            let res = match i64::try_from(remaining) {
                Ok(seek) => rd.seek_relative(seek),
                Err(..) => {
                    rd.stream_position().and_then(|current| {
                        let absolute = current.checked_add(remaining)
                                      .ok_or_else(|| R::unexpected_eof())?;
                        rd.seek(SeekFrom::Start(absolute))?;
                        Ok(())
                    })
                }
            };
            if let Err(e) = res {
                return Err(wrap_err(rd, LhaError::Io(e)))
            }
        }
        self.begin_new(rd)
    }
    /// Attempt to parse the header of the next archive's entry.
    ///
    /// See [`LhaDecodeReader::next_file()`] for a description of this method.
    ///
    /// This version allows to specify the sink buffer size, `BUF`, by the user.
    ///
    /// # Panics
    /// This method panics when `BUF` = `0`.
    pub fn next_file_with_sink<const BUF: usize>(&mut self) -> Result<bool, LhaDecodeError<R>> {
        let mut limited_rd = self.decoder.take().expect("decoder not empty").into_inner();
        if limited_rd.limit() != 0 &&
            let Err(e) = discard_to_end::<_, BUF>(&mut limited_rd).map_err(LhaError::Io)
        {
            return Err(wrap_err(limited_rd.into_inner(), e))
        }
        self.begin_new(limited_rd.into_inner())
    }
    /// Return a reference to the last parsed archive header.
    ///
    /// If this `LhaDecodeReader` has been initialized using [`Default::default()`]
    /// the returned `LhaHeader` fields will contain zeros.
    pub fn header(&self) -> &LhaHeader {
        &self.header
    }
    /// Unwrap and return the inner [`LhaHeader`] and optionally a decoder object
    /// if present.
    pub fn into_parts(self) -> (LhaHeader, Option<DecoderAny<Take<R>>>) {
        (self.header, self.decoder)
    }
    /// Consume the `LhaDecodeReader` and return the underlying stream reader.
    ///
    /// # Panics
    /// Panics if the reader has been already taken.
    pub fn into_inner(self) -> R {
        self.decoder.expect("decoder not empty").into_inner().into_inner()
    }
    /// Take the inner decoder object out of the decoder, leaving a none in its place.
    ///
    /// After this call, reading from this instance will result in a panic.
    pub fn take_decoder(&mut self) -> Option<DecoderAny<Take<R>>> {
        self.header.original_size = 0;
        self.output_length = 0;
        self.crc.reset();
        self.decoder.take()
    }
    /// Get a reference to the underlying `DecoderAny`, if the decoder is
    /// present in this `LhaDecodeReader`.
    ///
    /// Care should be taken to avoid modifying the internal state of the
    /// underlying decoder as doing so may corrupt the internal state of this
    /// `LhaDecodeReader`.
    pub fn get_decoder(&self) -> Option<&DecoderAny<Take<R>>> {
        self.decoder.as_ref()
    }
    /// Get a mutable reference to the underlying `DecoderAny`, if the decoder
    /// is present in this `LhaDecodeReader`.
    ///
    /// Care should be taken to avoid modifying the internal state of the
    /// underlying decoder as doing so may corrupt the internal state of this
    /// `LhaDecodeReader`.
    pub fn get_mut_decoder(&mut self) -> Option<&mut DecoderAny<Take<R>>> {
        self.decoder.as_mut()
    }
    /// Take the inner stream reader object out of the decoder, leaving a none
    /// in its place.
    ///
    /// After this call, reading from this instance will result in a panic.
    pub fn take_inner(&mut self) -> Option<R> {
        self.take_decoder().map(|decoder| decoder.into_inner().into_inner())
    }
    /// Get a reference to the underlying reader, if the decoder is present in
    /// this `LhaDecodeReader`.
    ///
    /// Care should be taken to avoid modifying the internal state of the
    /// underlying reader as doing so may corrupt the internal state of this
    /// `LhaDecodeReader`.
    pub fn get_ref(&self) -> Option<&R> {
        self.decoder.as_ref().map(|decoder| decoder.get_ref().get_ref())
    }
    /// Get a mutable reference to the underlying reader, if the decoder is
    /// present in this `LhaDecodeReader`.
    ///
    /// Care should be taken to avoid modifying the internal state of the
    /// underlying reader as doing so may corrupt the internal state of this
    /// `LhaDecodeReader`.
    pub fn get_mut(&mut self) -> Option<&mut R> {
        self.decoder.as_mut().map(|decoder| decoder.get_mut().get_mut())
    }
    /// Return the number of remaining bytes of the currently decompressed file to be read.
    pub fn len(&self) -> u64 {
        self.header.original_size - self.output_length
    }
    /// Return whether the current file has been finished reading or if the file is empty.
    pub fn is_empty(&self) -> bool {
        self.header.original_size == self.output_length
    }
    /// Return whether an underlying stream reader is present in the decoder.
    pub fn is_present(&self) -> bool {
        self.decoder.is_some()
    }
    /// Return whether an underlying stream reader is absent from the decoder.
    ///
    /// An attempt to read file's content in the abosent state will result in a panic.
    pub fn is_absent(&self) -> bool {
        self.decoder.is_none()
    }
    /// Return whether the CRC-16 checksum, computed during file decompression,
    /// matches the file checksum in the archive header.
    ///
    /// # Note
    /// This method should be called only **AFTER** the whole file has been
    /// decompressed.
    pub fn crc_is_ok(&self) -> bool {
        self.crc.sum16() == self.header.file_crc
    }
    /// Return the CRC-16 checksum, computed during file decompression, if it
    /// matches the file checksum in the archive header.
    ///
    /// Otherwise return an [`LhaError::Checksum`] error.
    ///
    /// # Note
    /// This method should be called only **AFTER** the whole file has been
    /// decompressed.
    pub fn crc_check(&self) -> LhaResult<u16, R> {
        if self.crc_is_ok() {
            Ok(self.header.file_crc)
        }
        else {
            Err(LhaError::Checksum)
        }
    }
    /// Return whether the current file's compression method is supported.
    ///
    /// If this method returns `false`, trying to read from the decoder will result in an error.
    /// In this instance it is still ok to skip to the next file.
    ///
    /// # Note
    /// If the variant of compression is [`CompressionMethod::Lhd`] this method will return `false`.
    /// In this instance check the result from header's [`LhaHeader::is_directory`] to determine
    /// what steps should be taken next.
    pub fn is_decoder_supported(&self) -> bool {
        self.decoder.as_ref().map(|d| d.is_supported()).unwrap_or(false)
    }
}

#[cfg(feature = "std")]
impl<R: Read<Error=std::io::Error>> std::io::Read for LhaDecodeReader<R> {
    fn read(&mut self, buf: &mut[u8]) -> std::io::Result<usize> {
        let len = buf.len().min((self.header.original_size - self.output_length) as usize);
        let target = &mut buf[..len];
        self.decoder.as_mut().unwrap().fill_buffer(target)?;
        self.output_length += len as u64;
        self.crc.digest(target);
        Ok(len)
    }
}

#[cfg(not(feature = "std"))]
impl<R: Read> Read for LhaDecodeReader<R> where R::Error: error::Error {
    type Error = LhaError<R::Error>;

    fn unexpected_eof() -> Self::Error {
        LhaError::Io(R::unexpected_eof())
    }

    fn read_all(&mut self, buf: &mut[u8]) -> Result<usize, Self::Error> {
        let len = buf.len().min((self.header.original_size - self.output_length) as usize);
        let target = &mut buf[..len];
        self.decoder.as_mut().unwrap().fill_buffer(target)?;
        self.output_length += len as u64;
        self.crc.digest(target);
        Ok(len)
    }
}

impl<R: Read> DecoderAny<R> {
    /// Creates an instance of `DecoderAny<Take<R>>` from the given `LhaHeader` reference and a stream reader.
    pub fn new_from_header(header: &LhaHeader, rd: R) -> DecoderAny<Take<R>> {
        let limited_rd = rd.take(header.compressed_size);
        match header.compression_method() {
            Ok(compression) => DecoderAny::new_from_compression(compression, limited_rd),
            Err(..) => DecoderAny::UnsupportedDecoder(UnsupportedDecoder::new(limited_rd))
        }
    }
    /// Creates an instance of `DecoderAny<R>` from the given compression method and a stream reader.
    pub fn new_from_compression(
            compression: CompressionMethod,
            rd: R
        ) -> Self
    {
        match compression {
            CompressionMethod::Pm0|
            CompressionMethod::Lz4|
            CompressionMethod::Lh0 => DecoderAny::PassthroughDecoder(PassthroughDecoder::new(rd)),
            #[cfg(feature = "lz")]
            CompressionMethod::Lzs => DecoderAny::LzsDecoder(LzsDecoder::new(rd)),
            #[cfg(feature = "lz")]
            CompressionMethod::Lz5 => DecoderAny::Lz5Decoder(Lz5Decoder::new(rd)),
            #[cfg(feature = "lh1")]
            CompressionMethod::Lh1 => DecoderAny::Lh1Decoder(Lh1Decoder::new(rd)),
            CompressionMethod::Lh4 => DecoderAny::Lh4Decoder(Lh5Decoder::new(rd)),
            CompressionMethod::Lh5 => DecoderAny::Lh5Decoder(Lh5Decoder::new(rd)),
            CompressionMethod::Lh6 => DecoderAny::Lh6Decoder(Lh7Decoder::new(rd)),
            CompressionMethod::Lh7 => DecoderAny::Lh7Decoder(Lh7Decoder::new(rd)),
            #[cfg(feature = "lhx")]
            CompressionMethod::Lhx => DecoderAny::LhxDecoder(LhxDecoder::new(rd)),
            #[cfg(feature = "pm")]
            CompressionMethod::Pm1 => DecoderAny::Pm1Decoder(Pm1Decoder::new(rd)),
            #[cfg(feature = "pm")]
            CompressionMethod::Pm2 => DecoderAny::Pm2Decoder(Pm2Decoder::new(rd)),
            _ => DecoderAny::UnsupportedDecoder(UnsupportedDecoder::new(rd))
        }
    }
    /// Returns `true` if the decoder is able to decode the file's content.
    pub fn is_supported(&self) -> bool {
        !matches!(self, DecoderAny::UnsupportedDecoder(..))
    }
}

impl<R: Read> Decoder<R> for DecoderAny<R> where R::Error: error::Error {
    type Error = R::Error;

    fn into_inner(self) -> R {
        decoder_any_dispatch!((self)(decoder) => decoder.into_inner())
    }

    fn get_ref(&self) -> &R {
        decoder_any_dispatch!((self)(decoder) => decoder.get_ref())
    }

    fn get_mut(&mut self) -> &mut R {
        decoder_any_dispatch!((self)(decoder) => decoder.get_mut())
    }

    #[inline]
    fn fill_buffer(&mut self, buf: &mut[u8]) -> Result<(), LhaError<Self::Error>> {
        decoder_any_dispatch!((self)(decoder) => decoder.fill_buffer(buf))
    }
}

impl<R: Read> PassthroughDecoder<R> {
    /// Create a new decoder instance from the given data read stream
    pub fn new(inner: R) -> Self {
        PassthroughDecoder { inner }
    }
}

impl<R: Read> Decoder<R> for PassthroughDecoder<R> where R::Error: error::Error {
    type Error = R::Error;

    fn into_inner(self) -> R {
        self.inner
    }

    fn get_ref(&self) -> &R {
        &self.inner
    }

    fn get_mut(&mut self) -> &mut R {
        &mut self.inner
    }

    #[inline]
    fn fill_buffer(&mut self, buf: &mut[u8]) -> Result<(), LhaError<Self::Error>> {
        self.inner.read_exact(buf).map_err(LhaError::Io)
    }
}

impl<R: Read> UnsupportedDecoder<R> {
    /// Create a new phony decoder instance from the given data read stream
    pub fn new(inner: R) -> Self {
        UnsupportedDecoder { inner }
    }
}

impl<R: Read> Decoder<R> for UnsupportedDecoder<R> where R::Error: error::Error {
    type Error = R::Error;

    fn into_inner(self) -> R {
        self.inner
    }

    fn get_ref(&self) -> &R {
        &self.inner
    }

    fn get_mut(&mut self) -> &mut R {
        &mut self.inner
    }

    #[inline]
    fn fill_buffer(&mut self, _buf: &mut[u8]) -> Result<(), LhaError<Self::Error>> {
        Err(LhaError::Decompress(DecompressionError::UnsupportedCompression))
    }
}

impl<R: Read> LhaDecodeError<R> {
    /// Unwrap this `LhaDecodeError<R>`, returning the contained reader.
    pub fn into_inner(self) -> R {
        self.read
    }
    /// Get a reference to the contained reader.
    pub fn get_ref(&self) -> &R {
        &self.read
    }
    /// Get a mutable reference to the contained reader.
    pub fn get_mut(&mut self) -> &mut R {
        &mut self.read
    }
}

impl<R: Read> error::Error for LhaDecodeError<R>
    where LhaError<R::Error>: error::Error + 'static
{
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        Some(&self.source)
    }
}

impl<R: Read> fmt::Debug for LhaDecodeError<R>
    where LhaError<R::Error>: fmt::Debug
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LhaDecodeError")
         .field("source", &self.source)
         .finish()
    }
}

impl<R: Read> fmt::Display for LhaDecodeError<R>
    where LhaError<R::Error>: fmt::Display
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "LHA decode error: {}", self.source)
    }
}

impl<R: Read> From<LhaDecodeError<R>> for LhaError<R::Error> {
    fn from(e: LhaDecodeError<R>) -> Self {
        e.source
    }
}

#[cfg(feature = "std")]
impl<R: Read> From<LhaDecodeError<R>> for std::io::Error
    where std::io::Error: From<LhaError<R::Error>>
{
    fn from(e: LhaDecodeError<R>) -> Self {
        e.source.into()
    }
}

fn wrap_err<R: Read>(read: R, source: LhaError<R::Error>) -> LhaDecodeError<R> {
    LhaDecodeError { read, source }
}

macro_rules! unsafe_assert {
    ($expr:expr) => {
        #[cfg(all(not(feature = "no-unsafe-assertions"), not(debug_assertions)))]
        unsafe {
            core::hint::assert_unchecked($expr)
        }
        debug_assert!($expr)
    };
}

use unsafe_assert;

#[cfg(feature = "std")]
#[cfg(test)]
/// build a random tree lengths with an upper num of values and max depth
/// this is used by unit tests only
fn build_random_tree_lengths(
        max_values: usize,
        mut max_depth: u8,
        final_size: usize,
        rng: &mut impl rand::Rng,
        out: &mut Vec<u8>
    )
{
    use rand::{RngExt, seq::SliceRandom};

    out.clear();
    let mut max_leaves = 2usize;
    for level in 1..max_depth {
        let n = out.len();
        let remaining = max_values - n;
        let num_leaves;
        if let Some(margin) = (max_leaves * 2).checked_sub(remaining)  {
            if remaining <= max_leaves {
                max_depth = level;
                break
            }
            num_leaves = margin;
        }
        else {
            num_leaves = rng.random_range(0..max_leaves);
        };
        max_leaves = (max_leaves - num_leaves) * 2;
        out.resize(n + num_leaves, level);
    }
    out.resize(out.len() + max_leaves, max_depth);
    assert!(final_size >= out.len(), "final_size: {} < out.len: {}", final_size, out.len());
    out.resize(final_size, 0);
    out.shuffle(rng);
}

#[cfg(test)]
mod tests {
    #[cfg(not(feature = "std"))]
    use alloc::string::ToString;
    #[cfg(not(feature = "std"))]
    use crate::UnexpectedEofError;
    #[cfg(feature = "std")]
    use std::{io, error::Error};
    use crate::OsType;
    use super::*;

    #[test]
    fn decode_error_works() {
        let mut data: &[u8] = &[0u8;3];
        let rd = &mut data;
        let mut err = LhaDecodeReader::new(rd).unwrap_err();
        assert_eq!(err.to_string(), "LHA decode error: while parsing LHA header: header not found");
        assert_eq!(err.get_ref(), &&[0u8;2]);
        assert_eq!(err.get_mut(), &mut &[0u8;2]);
        assert_eq!(err.into_inner(), &[0u8;2]);
        #[cfg(not(feature = "std"))]
        assert_eq!(<LhaDecodeReader::<&[u8]> as Read>::unexpected_eof(),
                   LhaError::Io(UnexpectedEofError));
    }

    #[cfg(feature = "std")]
    #[test]
    fn decode_std_error_works() {
        static HEADER_BAD: &[u8] = {
            b"\x01\0-lh0-\0\0\0\0\0\0\0\0\0\0\0\0\x20\x04"
        };
        let mut reader = LhaDecodeReader::default();
        println!("{:?}", reader);
        let mut data: &[u8] = HEADER_BAD;
        let err = reader.begin_new(&mut data).unwrap_err();
        assert_eq!(err.source().unwrap()
                      .downcast_ref::<LhaError::<io::Error>>().unwrap()
                      .source().unwrap()
                      .downcast_ref::<LhaHeaderError>().unwrap(),
                        &LhaHeaderError::UnknownLevel);
        assert!(matches!(LhaError::from(err), LhaError::HeaderParse(LhaHeaderError::UnknownLevel)));

        let rdlimit = io::Cursor::new(Vec::new()).take(u64::MAX);
        let header = reader.header().clone();
        let mut reader = LhaDecodeReader::default();
        reader.begin_with_header_and_decoder(header.clone(),
                    DecoderAny::new_from_compression(CompressionMethod::Lh0, rdlimit));
        reader.seek_next_file().unwrap();

        assert_eq!(data, &[]);

        struct PhonySeek;
        impl io::Read for PhonySeek {
            fn read(&mut self, _buf: &mut[u8]) -> io::Result<usize> {
                Err(io::ErrorKind::UnexpectedEof.into())
            }
        }
        impl io::Seek for PhonySeek {
            fn seek(&mut self, _style: io::SeekFrom) -> io::Result<u64> {
                Err(io::ErrorKind::UnexpectedEof.into())
            }
        }

        let rdlimit = PhonySeek.take(u64::MAX);
        let mut reader = LhaDecodeReader::<PhonySeek>::default();
        reader.begin_with_header_and_decoder(header.clone(),
                    DecoderAny::new_from_compression(CompressionMethod::Lh0, rdlimit));
        let err = reader.seek_next_file().unwrap_err();
        assert!(reader.take_inner().is_none());
        assert_eq!(io::Error::from(err).kind(), io::ErrorKind::UnexpectedEof);

        let rdlimit = PhonySeek.take(u64::MAX);
        reader.begin_with_header_and_decoder(header,
                    DecoderAny::new_from_compression(CompressionMethod::Lh0, rdlimit));
        let err = reader.next_file().unwrap_err();
        assert_eq!(io::Error::from(err).kind(), io::ErrorKind::UnexpectedEof);

        let mut data: &[u8] = &[];
        let err = LhaDecodeReader::new(&mut data).unwrap_err();
        println!("{:?}", err);
        assert_eq!(err.to_string(), "LHA decode error: while parsing LHA header: header not found");
        assert_eq!(io::Error::from(err).to_string(), "while parsing LHA header: header not found");

        assert_eq!(<LhaDecodeReader::<&[u8]> as Read>::unexpected_eof().kind(),
                   io::ErrorKind::UnexpectedEof);
    }

    #[should_panic]
    #[test]
    fn decode_into_inner_panics() {
        LhaDecodeReader::<&[u8]>::default().into_inner();
    }

    #[should_panic]
    #[test]
    fn decode_next_file_panics() {
        let _ = LhaDecodeReader::<&[u8]>::default().next_file();
    }

    #[cfg(feature = "std")]
    #[should_panic]
    #[test]
    fn decode_seek_next_file_panics() {
        let _ = LhaDecodeReader::<std::fs::File>::default().seek_next_file();
    }

    #[test]
    fn decode_works() {
        static HEADER_0: &[u8] = {
            b"\x1F\xC1-lh0-\0\0\0\0\0\0\0\0\xCA\x83\xE7\x2C\x20\x00\x09test\\test\xFF\xFF"
        };

        let mut data = HEADER_0;
        let mut reader = LhaDecodeReader::new(&mut data).unwrap();
        assert!(reader.is_present());

        assert!(matches!(reader.get_decoder().unwrap(), &DecoderAny::PassthroughDecoder(..))); 
        assert!(matches!(reader.get_mut_decoder().unwrap(), &mut DecoderAny::PassthroughDecoder(..))); 
        assert_eq!(reader.get_ref().unwrap(), &&mut &[]); 
        assert_eq!(reader.get_mut().unwrap(), &mut &mut &[]);
        assert!(matches!(reader.crc_check().unwrap_err(), LhaError::Checksum));
        let (header, decoder) = reader.into_parts();
        let mut decoder = decoder.unwrap();
        assert!(decoder.is_supported());
        assert!(matches!(decoder, DecoderAny::PassthroughDecoder(..)));
        assert_eq!(decoder.get_ref().get_ref(), &&mut &[]);
        assert_eq!(decoder.get_mut().get_mut(), &mut &mut &[]);
        let data = decoder.into_inner().into_inner();
        assert!(data.is_empty());
        assert_eq!(header.level, 0);
        assert_eq!(header.original_size, 0);
        assert_eq!(header.compressed_size, 0);
        assert_eq!(header.parse_os_type().unwrap(), OsType::Generic);
        assert!(!header.is_directory());
        assert!(!header.compression_method().unwrap().is_compressed());
        assert_eq!(header.parse_pathname_to_str(), "test/test");
        assert_eq!(header.file_crc, u16::MAX);

        static HEADER_1: &[u8] = {
            b"\x1D\xFF-lh0-\x0D\0\0\0\0\0\0\0\xCA\x83\xE7\x2C\x20\x01\x04test\0\0J\x05\x00\x00\x40\x7F\x08\x00\x02test\xFF\0\0"
        };
        let mut data = HEADER_1;
        let mut reader = LhaDecodeReader::new(&mut data).unwrap();
        assert!(reader.is_present());
        assert!(!reader.is_absent());
        {
            let header = reader.header();
            assert_eq!(header.level, 1);
            assert_eq!(header.original_size, 0);
            assert_eq!(header.compressed_size, 0);
            assert_eq!(header.parse_os_type().unwrap(), OsType::Java);
            assert!(!header.compression_method().unwrap().is_compressed());
            assert!(!header.is_directory());
            assert_eq!(header.parse_pathname_to_str(), "test/test");
            assert_eq!(header.file_crc, 0);
        }
        assert!(matches!(reader.get_decoder().unwrap(), &DecoderAny::PassthroughDecoder(..))); 
        assert!(matches!(reader.get_mut_decoder().unwrap(), &mut DecoderAny::PassthroughDecoder(..))); 
        assert_eq!(reader.get_ref().unwrap(), &&mut &[]); 
        assert_eq!(reader.get_mut().unwrap(), &mut &mut &[]);
        let mut decoder = reader.take_decoder().unwrap();
        assert!(decoder.is_supported());
        assert!(matches!(decoder, DecoderAny::PassthroughDecoder(..)));
        assert_eq!(decoder.get_ref().get_ref(), &&mut &[]);
        assert_eq!(decoder.get_mut().get_mut(), &mut &mut &[]);
        let data = decoder.into_inner().into_inner();
        assert!(data.is_empty());
        let decoder = DecoderAny::new_from_header(&header, data);
        assert!(!reader.is_present());
        assert!(reader.is_absent());
        reader.begin_with_header_and_decoder(header.clone(), decoder);
        assert_eq!(&header, reader.header());
        assert_eq!(reader.header().level, 0);
        let rd = reader.take_decoder().unwrap().into_inner();
        reader.begin_with_header_and_decoder(header.clone(),
            DecoderAny::new_from_compression(CompressionMethod::Lhd, rd));
        assert!(matches!(reader.get_decoder().unwrap(), &DecoderAny::UnsupportedDecoder(..))); 
        assert!(matches!(reader.get_mut_decoder().unwrap(), &mut DecoderAny::UnsupportedDecoder(..))); 
        assert_eq!(reader.get_ref().unwrap(), &&mut &[]); 
        assert_eq!(reader.get_mut().unwrap(), &mut &mut &[]);
        assert!(!reader.next_file().unwrap());

        static HEADER_1A: &[u8] = {
            static INNER: [[u8; 16];11] = [
                *b"\x19\x85-lh0-\x8A\0\0\0\0\0\0\0\xBC",
                *b"\x54\xF1\x2C\x20\x01\x00\0\0\x4A\x05\0\0\x63\xAF\x85\0",
                *b"\x01use a filename ", *b"header as a subs",
                *b"titute for the f", *b"ilename field wh",
                *b"en byte count of", *b" filename is in ",
                *b"excess of the fo", *b"regoing restrict",
                *b"ion\0\0___________",
            ];
            INNER.as_flattened()
        };
        let mut data = HEADER_1A;
        let mut reader = LhaDecodeReader::new(&mut data).unwrap();
        {
            let header = reader.header();
            assert_eq!(header.level, 1);
            assert_eq!(header.original_size, 0);
            assert_eq!(header.compressed_size, 0);
            assert!(!header.is_directory());
            assert_eq!(header.parse_os_type().unwrap(), OsType::Java);
            assert!(!header.compression_method().unwrap().is_compressed());
            assert_eq!(header.parse_pathname_to_str(), concat!(
                "use a filename header as a substitute for the filename field when ",
                "byte count of filename is in excess of the foregoing restriction"));
            assert_eq!(header.file_crc, 0);
        }
        let data = reader.take_inner().unwrap();
        assert_eq!(data, b"___________");
        let mut data = HEADER_0;
        reader.begin_new(&mut data).unwrap();
        assert_eq!(&header, reader.header());
        assert_eq!(reader.header().level, 0);
        let data = reader.into_inner();
        assert_eq!(data, &[]);
    }
}