P4C
The P4 Compiler
Loading...
Searching...
No Matches
table_printer.h
1
19#ifndef BF_P4C_COMMON_TABLE_PRINTER_H_
20#define BF_P4C_COMMON_TABLE_PRINTER_H_
21
22#include <iomanip>
23
24#include "lib/exceptions.h"
25#include "lib/log.h"
26
41 public:
42 enum Align { LEFT, CENTER, RIGHT };
43
44 TablePrinter(std::ostream &s, std::vector<std::string> headers, Align align = RIGHT)
45 : _s(s), _headers(headers), _align(align) {
46 for (auto &h : headers) _colWidth.push_back(h.length());
47 }
48
49 bool empty() { return _data.empty(); }
50
51 void addRow(std::vector<std::string> row) {
52 BUG_CHECK(row.size() == _headers.size(), "row size does not match header");
53
54 _data.push_back(row);
55
56 for (unsigned i = 0; i < row.size(); i++) {
57 if (row[i].length() > _colWidth[i]) _colWidth[i] = row[i].length();
58 }
59 }
60
61 void addSep(unsigned start_col = 0) { _seps[_data.size()] = start_col; }
62
63 void addBlank() {
64 unsigned cols = _colWidth.size();
65 if (cols) {
66 std::vector<std::string> blank(cols, "");
67 addRow(blank);
68 }
69 }
70
71 void print() const {
72 printSep();
73 printRow(_headers);
74 printSep();
75
76 for (unsigned i = 0; i < _data.size(); i++) {
77 printRow(_data.at(i));
78 if (_seps.count(i + 1) && i + 1 != _data.size()) printSep(_seps.at(i + 1));
79 }
80
81 printSep();
82 }
83
84 private:
85 unsigned getTableWidth() const {
86 unsigned rv = 0;
87 for (auto cw : _colWidth) rv += cw + cellPad;
88 return rv + _headers.size() + 1;
89 }
90
91 void printSep(unsigned start_col = 0) const {
92 for (unsigned i = 0; i < _colWidth.size(); i++) {
93 _s << (i < start_col ? "|" : "+")
94 << std::string(_colWidth.at(i) + cellPad, i >= start_col ? '-' : ' ');
95 }
96
97 _s << "+" << std::endl;
98 }
99
100 void printCell(unsigned col, std::string data) const {
101 unsigned width = _colWidth.at(col);
102 if (_align == LEFT) _s << std::left;
103 _s << std::setw(width + cellPad);
104 if (_align == CENTER) data += std::string((width + cellPad - data.length() + 1) / 2, ' ');
105 _s << data;
106 }
107
108 void printRow(const std::vector<std::string> &row) const {
109 for (unsigned i = 0; i < row.size(); i++) {
110 _s << "|";
111
112 printCell(i, row.at(i));
113
114 if (i == row.size() - 1) _s << "|";
115 }
116 _s << std::endl;
117 }
118
119 std::ostream &_s;
120
121 std::vector<std::vector<std::string>> _data;
122 std::map<unsigned, unsigned> _seps; // maps line numbers to starting column
123
124 std::vector<std::string> _headers;
125 std::vector<unsigned> _colWidth;
126
127 Align _align = RIGHT;
128 const unsigned cellPad = 2;
129};
130
131#endif /* BF_P4C_COMMON_TABLE_PRINTER_H_ */
Definition table_printer.h:40