Compare commits

...

2 Commits

Author SHA1 Message Date
f1756e6f58 Add unit formatting 2022-11-30 12:42:11 +01:00
552186ad51 Add string_format and vstring_format 2022-11-30 12:36:21 +01:00
6 changed files with 73 additions and 1 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

View File

@ -467,4 +467,43 @@ Result<usize> cstyle_format(const char* format, callback_t callback, void* arg,
}
return state.count;
}
struct StringFormatInfo
{
char* buffer;
size_t remaining;
};
Result<usize> vstring_format(char* buf, size_t max, const char* format, va_list ap)
{
StringFormatInfo info = {.buffer = buf, .remaining = max - 1};
usize result = TRY(cstyle_format(
format,
[](char c, void* arg) -> Result<void> {
StringFormatInfo* info_arg = (StringFormatInfo*)arg;
if (!info_arg->remaining) return {};
*(info_arg->buffer) = c;
info_arg->buffer++;
info_arg->remaining--;
return {};
},
&info, ap));
*(info.buffer) = 0;
return result;
}
Result<usize> string_format(char* buf, size_t max, const char* format, ...)
{
va_list ap;
va_start(ap, format);
usize result = TRY(vstring_format(buf, max, format, ap));
va_end(ap);
return result;
}

View File

@ -5,4 +5,6 @@
typedef Result<void> (*callback_t)(char, void*);
Result<usize> cstyle_format(const char* format, callback_t callback, void* arg, va_list ap);
Result<usize> cstyle_format(const char* format, callback_t callback, void* arg, va_list ap);
Result<usize> vstring_format(char* buf, size_t max, const char* format, va_list ap);
Result<usize> string_format(char* buf, size_t max, const char* format, ...);

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);