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
// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use flate2::{Compression, GzBuilder};
use std::fs::File;
use std::io;
use std::path::Path;
use xz2::stream::MtStreamBuilder;
use xz2::write::XzEncoder;

use crate::error::{Error, ErrorKind};

/// # Errors
/// Returns error if failed to create archive file.
#[allow(dead_code)]
pub fn create_gz(in_path: &Path, out_path: &Path) -> Result<(), Error> {
    log::info!("create_gz(), in: {:?}, out: {:?}", in_path, out_path);
    let out_file = File::create(out_path)?;
    let mut encoder = GzBuilder::new().write(out_file, Compression::default());
    let mut in_file = File::open(in_path)?;
    io::copy(&mut in_file, &mut encoder)?;
    encoder.finish()?;

    Ok(())
}

/// # Errors
/// Returns error if failed to create archive file.
#[allow(clippy::cast_possible_truncation)]
pub fn create_xz2(in_path: &Path, out_path: &Path) -> Result<(), Error> {
    log::info!("create_xz2(), in: {:?}, out: {:?}", in_path, out_path);
    let xz_level = 6;
    let stream = MtStreamBuilder::new()
        .preset(xz_level)
        .threads(num_cpus::get() as u32)
        .encoder()?;

    let out_file = File::create(out_path).map_err(|err| {
        Error::from_string(
            ErrorKind::IoError,
            format!("Failed to create out file: {out_path:?}, error: {err:?}"),
        )
    })?;

    log::info!("Create xz encoder");
    let mut encoder = XzEncoder::new_stream(out_file, stream);
    let mut in_file = File::open(in_path).map_err(|err| {
        Error::from_string(
            ErrorKind::IoError,
            format!("Failed to open file {in_path:?}, err: {err:?}"),
        )
    })?;
    io::copy(&mut in_file, &mut encoder).map_err(|err| {
        Error::from_string(
            ErrorKind::IoError,
            format!("Failed to copy file from {in_file:?} to {out_path:?}, err: {err:?}"),
        )
    })?;
    encoder.finish()?;

    Ok(())
}