summaryrefslogtreecommitdiff
path: root/src/progress_bar.rs
diff options
context:
space:
mode:
authormo8it <mo8it@proton.me>2024-04-09 19:37:39 +0200
committermo8it <mo8it@proton.me>2024-04-09 19:37:39 +0200
commit850c1d0234b2c1ae09a8f1c8f669e23a324fd644 (patch)
tree08955740594e3336534da3828b1930aece2f864e /src/progress_bar.rs
parentee7d9762832241b34dc5533bad4ed151e21acab1 (diff)
Add progress bar to list
Diffstat (limited to 'src/progress_bar.rs')
-rw-r--r--src/progress_bar.rs41
1 files changed, 41 insertions, 0 deletions
diff --git a/src/progress_bar.rs b/src/progress_bar.rs
new file mode 100644
index 0000000..b4abbfc
--- /dev/null
+++ b/src/progress_bar.rs
@@ -0,0 +1,41 @@
+use anyhow::{bail, Result};
+use std::fmt::Write;
+
+pub fn progress_bar(progress: u16, total: u16, line_width: u16) -> Result<String> {
+ if progress > total {
+ bail!("The progress of the progress bar is higher than the maximum");
+ }
+
+ // "Progress: [".len() == 11
+ // "] xxx/xxx".len() == 9
+ // 11 + 9 = 20
+ let wrapper_width = 20;
+
+ // If the line width is too low for a progress bar, just show the ratio.
+ if line_width < wrapper_width + 4 {
+ return Ok(format!("Progress: {progress}/{total}"));
+ }
+
+ let mut line = String::with_capacity(usize::from(line_width));
+ line.push_str("Progress: [");
+
+ let remaining_width = line_width.saturating_sub(wrapper_width);
+ let filled = (remaining_width * progress) / total;
+
+ for _ in 0..filled {
+ line.push('=');
+ }
+
+ if filled < remaining_width {
+ line.push('>');
+ }
+
+ for _ in 0..(remaining_width - filled).saturating_sub(1) {
+ line.push(' ');
+ }
+
+ line.write_fmt(format_args!("] {progress:>3}/{total:<3}"))
+ .unwrap();
+
+ Ok(line)
+}