Luna/luna/Units.cpp

16 lines
435 B
C++
Raw Normal View History

2022-11-30 11:42:11 +00:00
#include <Format.h>
#include <Units.h>
Result<usize> to_dynamic_unit(usize value, char* buffer, size_t max)
{
if (value < 1024) { return string_format(buffer, max, "%u bytes", value); }
const char* unit_prefixes = "KMGTPE";
2022-11-30 13:41:35 +00:00
while (value > (1024 * 1024))
2022-11-30 11:42:11 +00:00
{
2022-11-30 13:41:35 +00:00
value /= 1024;
2022-11-30 11:42:11 +00:00
unit_prefixes++;
}
return string_format(buffer, max, "%u.%u %ciB", value / 1024, (value % 1024) / 103, *unit_prefixes);
}