use crate::errors::*;
use std::fs::{self, OpenOptions};
use std::io;
use std::io::{Read, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
use zstd::{Decoder, Encoder};
pub fn secs_to_human(duration: i64) -> String {
let secs = duration % 60;
let mins = duration / 60;
let hours = mins / 60;
let mins = mins % 60;
let mut out = Vec::new();
if hours > 0 {
out.push(format!("{:2}h", hours));
}
if mins > 0 || hours > 0 {
out.push(format!("{:2}m", mins));
}
out.push(format!("{:2}s", secs));
out.join(" ")
}
pub const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd];
pub const ZSTD_CHUNK_SIZE: usize = 1024 * 128;
pub async fn zstd_compress(data: &[u8]) -> io::Result<Vec<u8>> {
let mut encoder = Encoder::new(Vec::new(), 11)?;
for slice in data.chunks(ZSTD_CHUNK_SIZE) {
tokio::task::yield_now().await;
encoder.write_all(slice)?;
}
encoder.finish()
}
pub async fn zstd_decompress(data: &[u8]) -> io::Result<Vec<u8>> {
let mut decoder = Decoder::new(data)?;
let mut data = vec![];
let mut buf = vec![0u8; ZSTD_CHUNK_SIZE];
loop {
tokio::task::yield_now().await;
let read_bytes = decoder.read(&mut buf)?;
if read_bytes == 0 {
break;
}
data.extend_from_slice(&buf[0..read_bytes]);
}
Ok(data)
}
pub fn is_zstd_compressed(data: &[u8]) -> bool {
data.starts_with(&ZSTD_MAGIC)
}
pub fn load_or_create<F: Fn() -> Result<Vec<u8>>>(path: &Path, func: F) -> Result<Vec<u8>> {
let data = match OpenOptions::new()
.mode(0o640)
.write(true)
.create_new(true)
.open(path)
{
Ok(mut file) => {
let data = func()?;
file.write_all(&data[..])?;
data
}
Err(_err) => {
debug!("Loading data from file: {path:?}");
fs::read(path)?
}
};
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_secs_to_human_0s() {
let x = secs_to_human(0);
assert_eq!(x, " 0s");
}
#[test]
fn test_secs_to_human_1s() {
let x = secs_to_human(1);
assert_eq!(x, " 1s");
}
#[test]
fn test_secs_to_human_1m() {
let x = secs_to_human(60);
assert_eq!(x, " 1m 0s");
}
#[test]
fn test_secs_to_human_1m_30s() {
let x = secs_to_human(90);
assert_eq!(x, " 1m 30s");
}
#[test]
fn test_secs_to_human_10m_30s() {
let x = secs_to_human(630);
assert_eq!(x, "10m 30s");
}
#[test]
fn test_secs_to_human_1h() {
let x = secs_to_human(3600);
assert_eq!(x, " 1h 0m 0s");
}
#[test]
fn test_secs_to_human_12h_10m_30s() {
let x = secs_to_human(3600 * 12 + 600 + 30);
assert_eq!(x, "12h 10m 30s");
}
#[test]
fn test_secs_to_human_100h() {
let x = secs_to_human(3600 * 100);
assert_eq!(x, "100h 0m 0s");
}
}