From 9b5d05d9240766c5db4c6435984020b3fbdc9e8b Mon Sep 17 00:00:00 2001 From: Moritz Bunkus Date: Wed, 21 Sep 2022 15:58:09 +0200 Subject: [PATCH] table formatter: support for column alignments --- src/common/strings/table_formatter.cpp | 19 ++++++++++++++++++- src/common/strings/table_formatter.h | 9 +++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/common/strings/table_formatter.cpp b/src/common/strings/table_formatter.cpp index dbfc393a2..2860fa96c 100644 --- a/src/common/strings/table_formatter.cpp +++ b/src/common/strings/table_formatter.cpp @@ -24,6 +24,13 @@ table_formatter_c::set_header(std::vector const &header) { return *this; } +table_formatter_c & +table_formatter_c::set_alignment(std::vector const &alignment) { + m_alignment = alignment; + return *this; +} + + table_formatter_c & table_formatter_c::add_row(std::vector 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 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. diff --git a/src/common/strings/table_formatter.h b/src/common/strings/table_formatter.h index 889554524..5f6f9dc31 100644 --- a/src/common/strings/table_formatter.h +++ b/src/common/strings/table_formatter.h @@ -16,12 +16,21 @@ namespace mtx::string { class table_formatter_c { +public: + enum alignment_e { + align_left, + align_right, + align_center, + }; + private: std::vector m_header; + std::vector m_alignment; std::vector> m_rows; public: table_formatter_c &set_header(std::vector const &header); + table_formatter_c &set_alignment(std::vector const &alignment); table_formatter_c &add_row(std::vector const &row); std::string format() const; };