Luna/luna/src/Units.cpp

28 lines
697 B
C++
Raw Normal View History

#include <luna/Alloc.h>
#include <luna/Format.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
usize to_dynamic_unit_cstr(usize value, char* buffer, usize max)
2022-11-30 11:42:11 +00:00
{
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);
}
Result<OwnedStringView> to_dynamic_unit(usize value)
{
char* buf = TRY(make_array<char>(64));
to_dynamic_unit_cstr(value, buf, 64);
return OwnedStringView{buf};
2022-11-30 11:42:11 +00:00
}