2022-12-16 17:18:24 +00:00
|
|
|
#include <luna/Alloc.h>
|
2022-12-04 11:42:43 +00:00
|
|
|
#include <luna/Format.h>
|
2022-12-07 10:40:02 +00:00
|
|
|
#include <luna/Result.h>
|
2022-12-16 17:18:24 +00:00
|
|
|
#include <luna/ScopeGuard.h>
|
2022-12-07 11:25:42 +00:00
|
|
|
#include <luna/Units.h>
|
2022-11-30 11:42:11 +00:00
|
|
|
|
2022-12-16 17:32:29 +00:00
|
|
|
usize to_dynamic_unit_cstr(usize value, char* buffer, usize max)
|
2022-11-30 11:42:11 +00:00
|
|
|
{
|
2022-12-17 11:45:26 +00:00
|
|
|
if (value < 1024) { return string_format(buffer, max, "%zu bytes", 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++;
|
|
|
|
}
|
|
|
|
|
2022-12-17 11:45:26 +00:00
|
|
|
return string_format(buffer, max, "%zu.%zu %ciB", value / 1024, (value % 1024) / 103, *unit_prefixes);
|
2022-12-16 17:18:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Result<OwnedStringView> to_dynamic_unit(usize value)
|
|
|
|
{
|
|
|
|
char* buf = TRY(make_array<char>(64));
|
|
|
|
|
2022-12-16 17:32:29 +00:00
|
|
|
to_dynamic_unit_cstr(value, buf, 64);
|
2022-12-16 17:18:24 +00:00
|
|
|
|
2022-12-21 19:22:44 +00:00
|
|
|
return OwnedStringView { buf };
|
2022-11-30 11:42:11 +00:00
|
|
|
}
|