diff --git a/include/bx/string.h b/include/bx/string.h index 2c6e44a..bcecc8b 100644 --- a/include/bx/string.h +++ b/include/bx/string.h @@ -12,6 +12,15 @@ namespace bx { + struct Units + { + enum Enum + { + Kilo, + Kibi, + }; + }; + /// Non-zero-terminated string view. class StringView { @@ -212,8 +221,8 @@ namespace bx /// Extract base file name from file path. const char* baseName(const char* _filePath); - /// Convert size in bytes to human readable string. - void prettify(char* _out, int32_t _count, uint64_t _size); + /// Convert size in bytes to human readable string kibi units. + int32_t prettify(char* _out, int32_t _count, uint64_t _size, Units::Enum _units = Units::Kibi); /// int32_t toString(char* _out, int32_t _max, double _value); diff --git a/src/string.cpp b/src/string.cpp index add9a29..b6b5780 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -906,19 +906,36 @@ namespace bx return _filePath; } - void prettify(char* _out, int32_t _count, uint64_t _size) + static const char s_units[] = { 'B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' }; + + template + static int32_t prettify(char* _out, int32_t _count, uint64_t _size) { uint8_t idx = 0; double size = double(_size); while (_size != (_size&0x7ff) - && idx < 9) + && idx < BX_COUNTOF(s_units) ) { - _size >>= 10; - size *= 1.0/1024.0; + _size /= Kilo; + size *= 1.0/double(Kilo); ++idx; } - snprintf(_out, _count, "%0.2f %c%c", size, "BkMGTPEZY"[idx], idx > 0 ? 'B' : '\0'); + return snprintf(_out, _count, "%0.2f %c%c%c", size + , s_units[idx] + , idx > 0 ? KiloCh0 : '\0' + , KiloCh1 + ); + } + + int32_t prettify(char* _out, int32_t _count, uint64_t _size, Units::Enum _units) + { + if (Units::Kilo == _units) + { + return prettify<1000, 'B', '\0'>(_out, _count, _size); + } + + return prettify<1024, 'i', 'B'>(_out, _count, _size); } } // namespace bx