Luna/libluna/src/Units.cpp

19 lines
459 B
C++
Raw Normal View History

#include <luna/Alloc.h>
2022-12-07 10:40:02 +00:00
#include <luna/Result.h>
#include <luna/ScopeGuard.h>
2022-12-07 11:25:42 +00:00
#include <luna/Units.h>
2022-11-30 11:42:11 +00:00
2023-04-07 08:37:00 +00:00
Result<String> to_dynamic_unit(usize value)
2022-11-30 11:42:11 +00:00
{
2023-04-07 08:37:00 +00:00
if (value < 1024) { return String::format("%zu bytes"_sv, value); }
2022-11-30 11:42:11 +00:00
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++;
}
2023-04-07 08:37:00 +00:00
return String::format("%zu.%zu %ciB"_sv, value / 1024, (value % 1024) / 103, *unit_prefixes);
2023-01-02 12:07:29 +00:00
}