Files
LLS/src/Table.cpp
T
2026-10-17 03:29:11 -03:00

58 lines
1.5 KiB
C++

#include "Table.h"
#include <algorithm>
#include "StringUtil.h"
TextTable::TextTable(const std::vector<std::string>& headers) : headers_(headers) {}
void TextTable::addRow(const std::vector<std::string>& cells) {
std::vector<std::string> row = cells;
row.resize(headers_.size());
rows_.push_back(row);
}
std::size_t TextTable::rowCount() const {
return rows_.size();
}
std::string TextTable::render() const {
std::vector<std::size_t> widths;
for (const std::string& header : headers_) {
widths.push_back(StringUtil::displayWidth(header));
}
for (const std::vector<std::string>& row : rows_) {
for (std::size_t c = 0; c < row.size(); ++c) {
widths[c] = std::max(widths[c], StringUtil::displayWidth(row[c]));
}
}
auto formatLine = [&widths](const std::vector<std::string>& cells) {
std::string line;
for (std::size_t c = 0; c < cells.size(); ++c) {
if (c > 0) {
line += " | ";
}
line += cells[c];
line.append(widths[c] - StringUtil::displayWidth(cells[c]), ' ');
}
return line + "\n";
};
std::string out = formatLine(headers_);
for (std::size_t c = 0; c < widths.size(); ++c) {
if (c > 0) {
out += "-+-";
}
out.append(widths[c], '-');
}
out += "\n";
for (const std::vector<std::string>& row : rows_) {
out += formatLine(row);
}
if (rows_.empty()) {
out += "(none)\n";
}
return out;
}