~james/gengo

gengo/samples-test/samples/C++/progress-bar.cpp -rw-r--r-- 2.2 KiB
50871857 — james chore(import): snapshot james.dad.town/gengo at 8f775550b0ee 16 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "progress-bar.h"
#include <iostream>
#include <sstream>

ProgressBar::ProgressBar(char symbol, int length, int total)
    : symbol(symbol)
    , length(length)
    , progress(0)
    , total(total)
    , startSymbol('[')
    , endSymbol(']')
    , format("{bar} {percent} {count}")
    , showPercent(false)
    , showCount(false) {}

ProgressBar& ProgressBar::update(int progress) {
    this->progress = progress;
    return *this;
}

ProgressBar& ProgressBar::showPercentage(bool show) {
    showPercent = show;
    return *this;
}

ProgressBar& ProgressBar::showCounter(bool show) {
    showCount = show;
    return *this;
}

ProgressBar& ProgressBar::setStartEndSymbols(char start, char end) {
    startSymbol = start;
    endSymbol = end;
    return *this;
}

ProgressBar& ProgressBar::setCustomFormat(const std::string& format) {
    this->format = format;
    return *this;
}

ProgressBar& ProgressBar::tick() {
    progress++;
    return *this;
}

void ProgressBar::print() const {
    std::ostringstream bar;
    std::string percent_str;
    std::string count_str;
    std::string result;

    // Generate bar component
    bar << startSymbol;
    int scaled_progress = static_cast<int>(static_cast<float>(progress) * length / total);

    for (int i = 0; i < length; i++) {
        bar << (i < scaled_progress ? symbol : ' ');
    }
    bar << endSymbol;

    // Generate percent component
    int percent = (progress * 100) / total;
    if (showPercent) {
        percent_str = std::to_string(percent) + "%";
    }

    // Generate count component
    if (showCount) {
        count_str = std::to_string(progress) + "/" + std::to_string(total);
    }

    // Process format string
    size_t pos = 0;
    std::string formatStr = format;

    // Replace placeholders with actual values
    while ((pos = formatStr.find("{bar}")) != std::string::npos) {
        formatStr.replace(pos, 5, bar.str());
    }
    while ((pos = formatStr.find("{percent}")) != std::string::npos) {
        formatStr.replace(pos, 9, percent_str);
    }
    while ((pos = formatStr.find("{count}")) != std::string::npos) {
        formatStr.replace(pos, 7, count_str);
    }

    std::cout << formatStr << (percent < 100 ? "\r" : "\n");
    std::cout.flush();
}