From d4deb347229adbe079845ff69c9fa9cd258f7c79 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Sun, 1 Nov 2026 01:38:24 +0300 Subject: [PATCH] add util::format_count --- src/util/stringutil.cpp | 67 ++++++++++++++++++++++++++--------------- src/util/stringutil.hpp | 1 + 2 files changed, 44 insertions(+), 24 deletions(-) diff --git a/src/util/stringutil.cpp b/src/util/stringutil.cpp index a2743a8ba..a41ceaf00 100644 --- a/src/util/stringutil.cpp +++ b/src/util/stringutil.cpp @@ -1,11 +1,11 @@ -#include "stringutil.hpp" - -#include -#include -#include -#include -#include -#include +#include "stringutil.hpp" + +#include +#include +#include +#include +#include +#include #include #include @@ -511,22 +511,22 @@ int util::replaceAll( return replace_all(str, from, to); } -double util::parse_double(const std::string& str) { - const char* begin = str.data(); - const char* end = begin + str.size(); - while (begin != end && std::isspace(static_cast(*begin))) { - begin++; - } - if (begin != end && *begin == '+') { - begin++; - } - double d = 0.0; - const auto result = std::from_chars(begin, end, d); - if (result.ec != std::errc()) { - throw std::runtime_error("invalid number format"); - } - return d; -} +double util::parse_double(const std::string& str) { + const char* begin = str.data(); + const char* end = begin + str.size(); + while (begin != end && std::isspace(static_cast(*begin))) { + begin++; + } + if (begin != end && *begin == '+') { + begin++; + } + double d = 0.0; + const auto result = std::from_chars(begin, end, d); + if (result.ec != std::errc()) { + throw std::runtime_error("invalid number format"); + } + return d; +} double util::parse_double(const std::string& str, size_t offset, size_t len) { return parse_double(str.substr(offset, len)); @@ -667,6 +667,25 @@ std::string util::format_data_size(size_t size) { postfixes[group]; } +std::string util::format_count(size_t count) { + if (count < 1000) { + return std::to_string(count); + } + const std::string postfixes[] { + "", " K", " M", " B" + }; + int group = 0; + size_t remainder = 0; + while (count >= 1000) { + group++; + remainder = count % 1000; + count /= 1000; + } + return std::to_string(count) + "." + + std::to_string(static_cast(round(remainder / 1000.0f))) + + postfixes[group]; +} + std::pair util::split_at( std::string_view view, char c ) { diff --git a/src/util/stringutil.hpp b/src/util/stringutil.hpp index 3f2263efb..4e2ff39c2 100644 --- a/src/util/stringutil.hpp +++ b/src/util/stringutil.hpp @@ -118,6 +118,7 @@ namespace util { std::vector split(const std::wstring& str, char delimiter); std::string format_data_size(size_t size); + std::string format_count(size_t size); std::pair split_at(std::string_view view, char c);