use std::cmp::Ordering;
pub use cxx::Exception;
use crate::config;
pub fn terminal_height() -> usize {
if let Some(size) = termsize::get() {
usize::from(size.rows)
} else {
24
}
}
pub fn terminal_width() -> usize {
if let Some(size) = termsize::get() {
usize::from(size.cols)
} else {
80
}
}
pub fn cmp_versions(ver1: &str, ver2: &str) -> Ordering {
let result = raw::cmp_versions(ver1.to_owned(), ver2.to_owned());
match result {
_ if result < 0 => Ordering::Less,
_ if result == 0 => Ordering::Equal,
_ => Ordering::Greater,
}
}
pub enum DiskSpace {
Require(u64),
Free(u64),
}
pub enum NumSys {
Binary,
Decimal,
}
pub fn unit_str(val: u64, base: NumSys) -> String {
let val = val as f64;
let (num, tera, giga, mega, kilo) = match base {
NumSys::Binary => (1024.0_f64, "TiB", "GiB", "MiB", "KiB"),
NumSys::Decimal => (1000.0_f64, "TB", "GB", "MB", "KB"),
};
let powers = [
(num.powi(4), tera),
(num.powi(3), giga),
(num.powi(2), mega),
(num, kilo),
];
for (divisor, unit) in powers {
if val > divisor {
return format!("{:.2} {unit}", val / divisor);
}
}
format!("{val} B")
}
pub fn time_str(seconds: u64) -> String {
if seconds > 60 * 60 * 24 {
return format!(
"{}d {}h {}min {}s",
seconds / 60 / 60 / 24,
(seconds / 60 / 60) % 24,
(seconds / 60) % 60,
seconds % 60,
);
}
if seconds > 60 * 60 {
return format!(
"{}h {}min {}s",
(seconds / 60 / 60) % 24,
(seconds / 60) % 60,
seconds % 60,
);
}
if seconds > 60 {
return format!("{}min {}s", (seconds / 60) % 60, seconds % 60,);
}
format!("{seconds}s")
}
pub fn get_apt_progress_string(percent: f32, output_width: u32) -> String {
raw::get_apt_progress_string(percent, output_width)
}
pub fn apt_lock() -> Result<(), Exception> {
config::init_config_system();
raw::apt_lock()
}
pub fn apt_unlock() {
config::init_config_system();
raw::apt_unlock()
}
pub fn apt_lock_inner() -> Result<(), Exception> {
config::init_config_system();
raw::apt_lock_inner()
}
pub fn apt_unlock_inner() {
config::init_config_system();
raw::apt_unlock_inner()
}
pub fn apt_is_locked() -> bool {
config::init_config_system();
raw::apt_is_locked()
}
#[cxx::bridge]
pub mod raw {
unsafe extern "C++" {
include!("rust-apt/apt-pkg-c/util.h");
pub fn cmp_versions(ver1: String, ver2: String) -> i32;
pub fn get_apt_progress_string(percent: f32, output_width: u32) -> String;
pub fn apt_lock() -> Result<()>;
pub fn apt_unlock();
pub fn apt_lock_inner() -> Result<()>;
pub fn apt_unlock_inner();
pub fn apt_is_locked() -> bool;
}
}