Moving bytes.rs implementation to utils.rs
[ouch.git] / src / decompressors / to_memory.rs
bloba76e06006b4667453cfe71f11d16f246ba00d079
1 use std::{
2     io::{self, Read},
3     path::Path,
4 };
6 use colored::Colorize;
8 use super::decompressor::{DecompressionResult, Decompressor};
9 use crate::{extension::CompressionFormat, file::File, utils};
11 struct DecompressorToMemory;
12 pub struct GzipDecompressor;
13 pub struct LzmaDecompressor;
14 pub struct BzipDecompressor;
16 fn get_decoder<'a>(
17     format: CompressionFormat,
18     buffer: Box<dyn io::Read + Send + 'a>,
19 ) -> Box<dyn io::Read + Send + 'a> {
20     match format {
21         CompressionFormat::Bzip => Box::new(bzip2::read::BzDecoder::new(buffer)),
22         CompressionFormat::Gzip => Box::new(flate2::read::MultiGzDecoder::new(buffer)),
23         CompressionFormat::Lzma => Box::new(xz2::read::XzDecoder::new_multi_decoder(buffer)),
24         _other => unreachable!(),
25     }
28 impl DecompressorToMemory {
29     fn unpack_file(path: &Path, format: CompressionFormat) -> crate::Result<Vec<u8>> {
30         let file = std::fs::read(path)?;
32         let mut reader = get_decoder(format, Box::new(&file[..]));
34         let mut buffer = Vec::new();
35         let bytes_read = reader.read_to_end(&mut buffer)?;
37         println!(
38             "{}: {:?} extracted into memory ({}).",
39             "info".yellow(),
40             path,
41             utils::Bytes::new(bytes_read as u64)
42         );
44         Ok(buffer)
45     }
47     fn decompress(
48         from: File,
49         format: CompressionFormat,
50         into: &Option<File>,
51     ) -> crate::Result<DecompressionResult> {
52         let destination_path = utils::get_destination_path(into);
54         utils::create_path_if_non_existent(destination_path)?;
56         let bytes = Self::unpack_file(&from.path, format)?;
58         Ok(DecompressionResult::FileInMemory(bytes))
59     }
62 impl Decompressor for GzipDecompressor {
63     fn decompress(
64         &self,
65         from: File,
66         into: &Option<File>,
67         _: &oof::Flags,
68     ) -> crate::Result<DecompressionResult> {
69         DecompressorToMemory::decompress(from, CompressionFormat::Gzip, into)
70     }
73 impl Decompressor for BzipDecompressor {
74     fn decompress(
75         &self,
76         from: File,
77         into: &Option<File>,
78         _: &oof::Flags,
79     ) -> crate::Result<DecompressionResult> {
80         DecompressorToMemory::decompress(from, CompressionFormat::Bzip, into)
81     }
84 impl Decompressor for LzmaDecompressor {
85     fn decompress(
86         &self,
87         from: File,
88         into: &Option<File>,
89         _: &oof::Flags,
90     ) -> crate::Result<DecompressionResult> {
91         DecompressorToMemory::decompress(from, CompressionFormat::Lzma, into)
92     }