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