Luna/libluna/src/Units.cpp

19 lines
459 B
C++
Raw Normal View History

#include <luna/Alloc.h>
2022-12-07 11:40:02 +01:00
#include <luna/Result.h>
#include <luna/ScopeGuard.h>
2022-12-07 12:25:42 +01:00
#include <luna/Units.h>
2022-11-30 12:42:11 +01:00
2023-04-07 10:37:00 +02:00
Result<String> to_dynamic_unit(usize value)
2022-11-30 12:42:11 +01:00
{
2023-04-07 10:37:00 +02:00
if (value < 1024) { return String::format("%zu bytes"_sv, value); }
2022-11-30 12:42:11 +01:00
const char* unit_prefixes = "KMGTPE";
2022-11-30 14:41:35 +01:00
while (value > (1024 * 1024))
2022-11-30 12:42:11 +01:00
{
2022-11-30 14:41:35 +01:00
value /= 1024;
2022-11-30 12:42:11 +01:00
unit_prefixes++;
}
2023-04-07 10:37:00 +02:00
return String::format("%zu.%zu %ciB"_sv, value / 1024, (value % 1024) / 103, *unit_prefixes);
2023-01-02 13:07:29 +01:00
}