use std::io::Write;
#[derive(Debug, Clone)]
pub struct TransferProgress {
pub done: u64,
pub total: u64,
pub filename: String,
}
impl TransferProgress {
pub fn new(done: u64, total: u64, filename: impl Into<String>) -> Self {
Self {
done,
total,
filename: filename.into(),
}
}
pub fn percent(&self) -> f64 {
if self.total == 0 {
return 0.0;
}
(self.done as f64 / self.total as f64) * 100.0
}
pub fn is_complete(&self) -> bool {
self.done >= self.total
}
}
pub type ProgressCallback = Box<dyn FnMut(&TransferProgress) -> bool + Send>;
pub fn make_progress_bar() -> ProgressCallback {
Box::new(|progress: &TransferProgress| {
let percent = progress.percent();
let bar_width = 40;
let filled = (percent / 100.0 * bar_width as f64) as usize;
let empty = bar_width - filled;
print!(
"\r[{}{}] {:.1}% {} - {}/{} bytes",
"=".repeat(filled),
" ".repeat(empty),
percent,
progress.filename,
progress.done,
progress.total
);
if progress.is_complete() {
println!();
}
let _ = std::io::stdout().flush();
true })
}