Add unit formatting

This commit is contained in:
apio 2022-11-30 12:42:11 +01:00
parent 552186ad51
commit f1756e6f58
4 changed files with 31 additions and 0 deletions

View File

@ -6,6 +6,7 @@
#include "memory/Heap.h"
#include "memory/MemoryManager.h"
#include "video/TextConsole.h"
#include <Units.h>
Result<void> init()
{
@ -51,6 +52,14 @@ Result<void> init()
TRY(destroy(mem));
char buffer[64];
to_dynamic_unit(MemoryManager::free(), buffer, sizeof(buffer));
Serial::printf("Free memory: %s\n", buffer);
to_dynamic_unit(MemoryManager::used(), buffer, sizeof(buffer));
Serial::printf("Used memory: %s\n", buffer);
to_dynamic_unit(MemoryManager::reserved(), buffer, sizeof(buffer));
Serial::printf("Reserved memory: %s\n", buffer);
while (1)
{
while ((Timer::ticks_ms() - start) < 20) { CPU::wait_for_interrupt(); }

View File

@ -2,6 +2,7 @@ set(FREESTANDING_SOURCES
Format.cpp
NumberParsing.cpp
String.cpp
Units.cpp
)
set(SOURCES

17
luna/Units.cpp Normal file
View File

@ -0,0 +1,17 @@
#include <Format.h>
#include <Units.h>
#include <limits.h>
Result<usize> to_dynamic_unit(usize value, char* buffer, size_t max)
{
if (value < 1024) { return string_format(buffer, max, "%u bytes", value); }
const char* unit_prefixes = "KMGTPE";
for (int i = 40; i >= 0 && value > (0xfffccccccccccccUL >> i); i -= 10)
{
value >>= 10;
unit_prefixes++;
}
return string_format(buffer, max, "%u.%u %ciB", value / 1024, (value % 1024) / 103, *unit_prefixes);
}

4
luna/Units.h Normal file
View File

@ -0,0 +1,4 @@
#pragma once
#include <Result.h>
Result<usize> to_dynamic_unit(usize value, char* buffer, usize max);