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
#[cfg(feature = "bzip")]
pub use self::bzip2::Bzip2;

#[cfg(feature = "bzip")]
mod bzip2 {
    use std::fs::{create_dir_all, File};
    use std::io::{copy, Read};
    use std::path::Path;

    use bzip2::read::BzDecoder;

    use crate::{Compressed, Error};

    pub struct Bzip2<R: Read> {
        archive: BzDecoder<R>,
    }

    impl Bzip2<File> {
        pub fn open(path: &Path) -> std::io::Result<Self> {
            let archive = File::open(path)?;

            Self::new(archive)
        }
    }

    impl<R: Read> Bzip2<R> {
        pub fn new(r: R) -> std::io::Result<Self> {
            let archive = BzDecoder::new(r);

            Ok(Self { archive })
        }
    }

    impl<R: Read> Compressed for Bzip2<R> {
        fn decompress(&mut self, target: &Path) -> Result<(), Error> {
            if let Some(p) = target.parent() {
                if !p.exists() {
                    create_dir_all(&p)?;
                }
            }

            let mut output = File::create(target)?;
            copy(&mut self.archive, &mut output)?;

            Ok(())
        }
    }

    impl<R: Read> Read for Bzip2<R> {
        fn read(&mut self, into: &mut [u8]) -> std::io::Result<usize> {
            self.archive.read(into)
        }
    }
}