Skip to content

Commit b710b0a

Browse files
ziuziakowskaengdoreis
authored andcommitted
clear trailing characters in progress bar if printing less than before
Signed-off-by: Alice Ziuziakowska <a.ziuziakowska@lowrisc.org>
1 parent 7930c5a commit b710b0a

1 file changed

Lines changed: 26 additions & 7 deletions

File tree

lib/visuals/progressbar.hh

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
#include "throughput.hh"
77

88
struct ProgressBar {
9-
bool finished = false;
10-
int width = 100;
11-
int total = 0;
12-
float progress = 0;
9+
bool finished = false;
10+
int width = 100;
11+
int total = 0;
12+
float progress = 0;
13+
int last_length = 0;
1314
std::string label;
1415
std::optional<Throughput> tp;
1516

@@ -40,10 +41,28 @@ struct ProgressBar {
4041
for (int i = 0; i < width; ++i) {
4142
std::print("{}", i < filled ? "" : " ");
4243
}
43-
std::cout << "] " << (int)(this->progress * 100) << "%\033[33m " << tp_str << "\033[0m "
44-
<< std::flush;
44+
45+
std::string output =
46+
std::format("] {}%\033[33m {}\033[0m", (int)(this->progress * 100), tp_str);
47+
48+
std::cout << output;
49+
50+
if (tp) {
51+
auto current_length = output.length();
52+
if (this->last_length > current_length) {
53+
/* There are some trailing characters left over from the last time
54+
* throughput was printed. Overwrite them with spaces, and then
55+
* backspace back to the current string length. */
56+
auto n = this->last_length - current_length;
57+
std::cout << std::string(n, ' ') << std::string(n, '\b');
58+
}
59+
this->last_length = current_length;
60+
}
61+
62+
std::cout << std::flush;
63+
4564
if (this->finished) {
46-
std::println("");
65+
std::cout << '\n';
4766
}
4867
}
4968
};

0 commit comments

Comments
 (0)