kcheck_utils/
lib.rs

1// Copyright (c) 2023 Jake Swensen
2// SPDX-License-Identifier: MPL-2.0
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8use flate2::read::GzDecoder;
9use std::io::{Read, Result};
10use std::path::Path;
11
12/// Deflate a gzip'd file into a string.
13pub fn deflate_gzip_file<P: AsRef<Path>>(path: P) -> Result<String> {
14    let contents = file_contents_as_bytes(path)?;
15    let mut gz = GzDecoder::new(&contents[..]);
16    let mut s = String::new();
17    gz.read_to_string(&mut s)?;
18    Ok(s)
19}
20
21/// Open a file.
22///
23/// Function that provides basic file opening and error handling.
24pub fn open_file<P: AsRef<Path>>(path: P) -> Result<std::fs::File> {
25    if !path.as_ref().exists() {
26        let path_string: String = path.as_ref().to_string_lossy().to_string();
27        return Err(std::io::Error::new(
28            std::io::ErrorKind::NotFound,
29            format!("File does not exist: {}", path_string),
30        ));
31    }
32
33    let file = std::fs::File::open(path)?;
34    Ok(file)
35}
36
37/// Parse file contents into a vector of bytes.
38pub fn file_contents_as_bytes<P: AsRef<Path>>(path: P) -> Result<Vec<u8>> {
39    let mut file = open_file(path)?;
40    let mut contents = Vec::<u8>::new();
41    file.read_to_end(&mut contents)?;
42    Ok(contents)
43}
44
45/// Parse file contents into a string.
46pub fn file_contents_as_string<P: AsRef<Path>>(path: P) -> Result<String> {
47    let mut file = open_file(path)?;
48    let mut contents = String::new();
49    file.read_to_string(&mut contents)?;
50    Ok(contents)
51}
52
53/// Take two `Option<Vec<T>>` and append the second to the first.
54///
55/// Returns the resulting `Option<Vec<T>>`.
56/// todo: this could probably be written in a more ergonomic way
57pub fn option_vector_append<T>(mut orig: Option<Vec<T>>, mut other: Option<Vec<T>>) -> Option<Vec<T>> {
58    if other.is_some() {
59        if orig.is_none() {
60            // The orginal vector is empty, so just take the other vector
61            orig = other.take();
62        } else {
63            // At this point, both orig and other are `Some`
64            let mut new_orig = orig.take().unwrap();
65            let mut new_other = other.take().unwrap();
66            new_orig.append(&mut new_other);
67            orig = Some(new_orig);
68        }
69    }
70
71    orig
72}