From f52f58b9e99181b35ffe5daf298729049232adcc Mon Sep 17 00:00:00 2001 From: Vitaliy Filippov Date: Tue, 25 Jul 2023 01:39:47 +0000 Subject: [PATCH] Support UTF-8 in vitastor-cli table output --- src/cli_ls.cpp | 10 ++++++---- src/str_util.cpp | 16 ++++++++++++++++ src/str_util.h | 2 ++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/cli_ls.cpp b/src/cli_ls.cpp index 529f1a76..de60109e 100644 --- a/src/cli_ls.cpp +++ b/src/cli_ls.cpp @@ -379,16 +379,18 @@ resume_1: std::string print_table(json11::Json items, json11::Json header, bool use_esc) { + int header_sizes[header.array_items().size()]; std::vector sizes; for (int i = 0; i < header.array_items().size(); i++) { - sizes.push_back(header[i]["title"].string_value().length()); + header_sizes[i] = utf8_length(header[i]["title"].string_value()); + sizes.push_back(header_sizes[i]); } for (auto & item: items.array_items()) { for (int i = 0; i < header.array_items().size(); i++) { - int l = item[header[i]["key"].string_value()].as_string().length(); + int l = utf8_length(item[header[i]["key"].string_value()].as_string()); sizes[i] = sizes[i] < l ? l : sizes[i]; } } @@ -400,7 +402,7 @@ std::string print_table(json11::Json items, json11::Json header, bool use_esc) // Separator str += " "; } - int pad = sizes[i]-header[i]["title"].string_value().length(); + int pad = sizes[i]-header_sizes[i]; if (header[i]["right"].bool_value()) { // Align right @@ -428,7 +430,7 @@ std::string print_table(json11::Json items, json11::Json header, bool use_esc) // Separator str += " "; } - int pad = sizes[i] - item[header[i]["key"].string_value()].as_string().length(); + int pad = sizes[i] - utf8_length(item[header[i]["key"].string_value()].as_string()); if (header[i]["right"].bool_value()) { // Align right diff --git a/src/str_util.cpp b/src/str_util.cpp index 5171be17..d39263d7 100644 --- a/src/str_util.cpp +++ b/src/str_util.cpp @@ -308,3 +308,19 @@ std::string str_repeat(const std::string & str, int times) r += str; return r; } + +size_t utf8_length(const std::string & s) +{ + size_t len = 0; + for (size_t i = 0; i < s.size(); i++) + len += (s[i] & 0xC0) != 0x80; + return len; +} + +size_t utf8_length(const char *s) +{ + size_t len = 0; + for (; *s; s++) + len += (*s & 0xC0) != 0x80; + return len; +} diff --git a/src/str_util.h b/src/str_util.h index e0a85569..ff528d19 100644 --- a/src/str_util.h +++ b/src/str_util.h @@ -18,3 +18,5 @@ void print_help(const char *help_text, std::string exe_name, std::string cmd, bo uint64_t parse_time(std::string time_str, bool *ok = NULL); std::string read_all_fd(int fd); std::string str_repeat(const std::string & str, int times); +size_t utf8_length(const std::string & s); +size_t utf8_length(const char *s);