Luna/luna/src/Units.cpp
apio 16954695dd
All checks were successful
continuous-integration/drone/push Build is passing
Tell the compiler that string_format is a printf-style function
2022-12-17 12:45:26 +01:00

28 lines
700 B
C++

#include <luna/Alloc.h>
#include <luna/Format.h>
#include <luna/Result.h>
#include <luna/ScopeGuard.h>
#include <luna/Units.h>
usize to_dynamic_unit_cstr(usize value, char* buffer, usize max)
{
if (value < 1024) { return string_format(buffer, max, "%zu bytes", value); }
const char* unit_prefixes = "KMGTPE";
while (value > (1024 * 1024))
{
value /= 1024;
unit_prefixes++;
}
return string_format(buffer, max, "%zu.%zu %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};
}