From d04c1dfad422d9ea8c2b460ff01b88911d9fd3ef Mon Sep 17 00:00:00 2001 From: Alexander Tkachev Date: Mon, 15 Jul 2019 18:35:24 +0700 Subject: COMMON: Add getHumanReadableBytes() in util.h This function was used in cloud-related DownloadDialog before, and now it is also used in Options > Cloud tab. --- common/util.cpp | 39 +++++++++++++++++++++++++++++++++++++++ common/util.h | 12 ++++++++++++ 2 files changed, 51 insertions(+) (limited to 'common') diff --git a/common/util.cpp b/common/util.cpp index 9a4214eda8..7c309ce364 100644 --- a/common/util.cpp +++ b/common/util.cpp @@ -163,4 +163,43 @@ bool isGraph(int c) { return isgraph((byte)c); } + +#pragma mark - + + +Common::String getHumanReadableBytes(uint64 bytes, Common::String &unitsOut) { + Common::String result = Common::String::format("%lu", bytes); + unitsOut = "B"; + + if (bytes >= 1024) { + bytes /= 1024; + result = Common::String::format("%lu", bytes); + unitsOut = "KB"; + } + + double floating = bytes; + + if (bytes >= 1024) { + bytes /= 1024; + floating /= 1024.0; + unitsOut = "MB"; + } + + if (bytes >= 1024) { + bytes /= 1024; + floating /= 1024.0; + unitsOut = "GB"; + } + + if (bytes >= 1024) { // woah + bytes /= 1024; + floating /= 1024.0; + unitsOut = "TB"; + } + + // print one digit after floating point + result = Common::String::format("%.1f", floating); + return result; +} + } // End of namespace Common diff --git a/common/util.h b/common/util.h index a90ea72167..8254e972d0 100644 --- a/common/util.h +++ b/common/util.h @@ -220,6 +220,18 @@ bool isCntrl(int c); */ bool isGraph(int c); + +/** + * Represent bytes size of a file as a number with floating point and + * largest suitable units. For example, 1474560 bytes as 1.4 MB. + * + * @param bytes size in bytes to be represented + * @param unitsOut (out-parameter) string with units + * @note use _() to translate units correctly + * @return string with a floating point number representing given size + */ +Common::String getHumanReadableBytes(uint64 bytes, Common::String &unitsOut); + } // End of namespace Common #endif -- cgit v1.2.3