diff options
Diffstat (limited to 'src/common/util.cpp')
-rw-r--r-- | src/common/util.cpp | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/common/util.cpp b/src/common/util.cpp index 80b8a9e81..728efc294 100644 --- a/src/common/util.cpp +++ b/src/common/util.cpp @@ -80,6 +80,7 @@ using namespace epee; #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> +#include <boost/format.hpp> #include <openssl/sha.h> #undef MONERO_DEFAULT_LOG_CATEGORY @@ -1063,4 +1064,39 @@ std::string get_nix_version_display_string() strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm); return std::string(buffer); } + + std::string get_human_readable_bytes(uint64_t bytes) + { + // Use 1024 for "kilo", 1024*1024 for "mega" and so on instead of the more modern and standard-conforming + // 1000, 1000*1000 and so on, to be consistent with other Monero code that also uses base 2 units + struct byte_map + { + const char* const format; + const std::uint64_t bytes; + }; + + static constexpr const byte_map sizes[] = + { + {"%.0f B", 1024}, + {"%.2f KB", 1024 * 1024}, + {"%.2f MB", std::uint64_t(1024) * 1024 * 1024}, + {"%.2f GB", std::uint64_t(1024) * 1024 * 1024 * 1024}, + {"%.2f TB", std::uint64_t(1024) * 1024 * 1024 * 1024 * 1024} + }; + + struct bytes_less + { + bool operator()(const byte_map& lhs, const byte_map& rhs) const noexcept + { + return lhs.bytes < rhs.bytes; + } + }; + + const auto size = std::upper_bound( + std::begin(sizes), std::end(sizes) - 1, byte_map{"", bytes}, bytes_less{} + ); + const std::uint64_t divisor = size->bytes / 1024; + return (boost::format(size->format) % (double(bytes) / divisor)).str(); + } + } |