about summary refs log tree commit diff
path: root/utils/optimin/src/ProgressBar.h
blob: 9b75594b6f94fdf4f93e125bc887849ea3e073c6 (plain) (blame)
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
/**
 *  Progress bar.
 *
 *  Adapted from https://www.bfilipek.com/2020/02/inidicators.html
 */

#pragma once

#include <llvm/ADT/StringRef.h>
#include <llvm/Support/raw_ostream.h>

/// Display a progress bar in the terminal
class ProgressBar {

 private:
  const size_t      BarWidth;
  const std::string Fill;
  const std::string Remainder;

 public:
  ProgressBar() : ProgressBar(60, "#", " ") {

  }

  ProgressBar(size_t Width, const llvm::StringRef F, const llvm::StringRef R)
      : BarWidth(Width), Fill(F), Remainder(R) {

  }

  void update(float Progress, const llvm::StringRef Status = "",
              llvm::raw_ostream &OS = llvm::outs()) {

    // No need to write once progress is 100%
    if (Progress > 100.0f) return;

    // Move cursor to the first position on the same line and flush
    OS << '\r';
    OS.flush();

    // Start bar
    OS << '[';

    const auto Completed =
        static_cast<size_t>(Progress * static_cast<float>(BarWidth) / 100.0);
    for (size_t I = 0; I < BarWidth; ++I) {

      if (I <= Completed) {

        OS << Fill;

      } else {

        OS << Remainder;

      }

    }

    // End bar
    OS << ']';

    // Write progress percentage
    OS << ' ' << std::min(static_cast<size_t>(Progress), size_t(100)) << '%';

    // Write status text
    OS << "  " << Status;

  }

};