table formatter: support for column alignments

This commit is contained in:
Moritz Bunkus 2022-09-21 15:58:09 +02:00
parent 1fe4b87e40
commit 9b5d05d924
No known key found for this signature in database
GPG Key ID: 74AF00ADF2E32C85
2 changed files with 27 additions and 1 deletions

View File

@ -24,6 +24,13 @@ table_formatter_c::set_header(std::vector<std::string> const &header) {
return *this;
}
table_formatter_c &
table_formatter_c::set_alignment(std::vector<alignment_e> const &alignment) {
m_alignment = alignment;
return *this;
}
table_formatter_c &
table_formatter_c::add_row(std::vector<std::string> const &row) {
m_rows.emplace_back(row);
@ -37,6 +44,10 @@ table_formatter_c::format()
return {};
auto num_columns = m_header.size();
auto alignment = m_alignment;
while (alignment.size() < num_columns)
alignment.push_back(align_left);
// 1. Calculate column widths.
std::vector<uint64_t> column_widths(num_columns, 0ull);
@ -53,10 +64,16 @@ table_formatter_c::format()
column_formats.reserve(num_columns);
auto row_size = 1u + (num_columns - 1) * 3;
auto idx = 0;
for (auto width : column_widths) {
column_formats.emplace_back(fmt::format("{{0:{0:}s}}", width));
auto fmt_alignment = alignment[idx] == align_left ? "<"
: alignment[idx] == align_right ? ">"
: "^";
column_formats.emplace_back(fmt::format("{{0:{0}{1}s}}", fmt_alignment, width));
row_size += width;
++idx;
}
// 3. Reserve space for full output & create row formatting lambda.

View File

@ -16,12 +16,21 @@
namespace mtx::string {
class table_formatter_c {
public:
enum alignment_e {
align_left,
align_right,
align_center,
};
private:
std::vector<std::string> m_header;
std::vector<alignment_e> m_alignment;
std::vector<std::vector<std::string>> m_rows;
public:
table_formatter_c &set_header(std::vector<std::string> const &header);
table_formatter_c &set_alignment(std::vector<alignment_e> const &alignment);
table_formatter_c &add_row(std::vector<std::string> const &row);
std::string format() const;
};