Skip to content

Commit

Permalink
IO::printf(...) implementation on SDK.
Browse files Browse the repository at this point in the history
  • Loading branch information
nthnn committed May 18, 2024
1 parent 90d780c commit b50f39e
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 7 deletions.
18 changes: 18 additions & 0 deletions sdk/librishka/io.h
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,24 @@ class IO final {
*/
static void println();

/**
* @brief Prints formatted output.
*
* This method prints formatted output to the standard output stream. It behaves similar to the printf function
* in C/C++, allowing developers to specify a format string and additional arguments for formatting.
*
* Formatters:
* - `{i}` — Integer number value
* - `{u}` — Unsigned number value
* - `{d}` — Double or floating-point number
* - `{s}` — String value
*
* @param format A string specifying the format of the output.
* @param ... Additional arguments to be formatted according to the format string.
* @return True if the output operation is successful, false otherwise.
*/
static bool printf(string format, ...);

/**
* @brief Check if there is data available to read from the input stream.
*
Expand Down
64 changes: 57 additions & 7 deletions sdk/librishka_io.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

#include "librishka.h"
#include "librishka/func_args.h"
#include "librishka_impl.hpp"

void IO::print(const string text) {
Expand All @@ -28,13 +29,14 @@ void IO::print(
const string bg,
const string style
) {
IO::print(style);
IO::print(fg);
IO::print(bg);
IO::print(text);

IO::print(TERM_STYLE_NORMAL);
IO::print(TERM_FG_HWHITE);
IO::printf(
F("{s}{s}{s}{s}{s}{s}"),
style,
fg, bg,
text,
TERM_STYLE_NORMAL,
TERM_FG_HWHITE
);
}

void IO::println(const string text) {
Expand Down Expand Up @@ -73,6 +75,54 @@ void IO::println() {
IO::print(F("\r\n"));
}

bool IO::printf(string format, ...) {
func_arg_list args;
func_arg_start(args, format);

while(*format) {
if(*format == '{') {
format++;

if(*format == 'i' && *(format + 1) == '}') {
i64 i = func_arg_get(args, i64);
IO::print(i);

format += 2;
}
else if(*format == 'u' && *(format + 1) == '}') {
u64 u = func_arg_get(args, u64);
IO::print(u);

format += 2;
}
else if(*format == 'd' && *(format + 1) == '}') {
double d = func_arg_get(args, double);
IO::print(d);

format += 2;
}
else if(*format == 's' && *(format + 1) == '}') {
string s = func_arg_get(args, char*);
IO::print(s);

format += 2;
}
else {
func_arg_end(args);
return 0;
}
}
else {
rune str[1] = {*format};
IO::print(str);
format++;
}
}

func_arg_end(args);
return 1;
}

rune IO::readch() {
return (rune) rishka_sc_0(RISHKA_SC_IO_READCH);
}
Expand Down

0 comments on commit b50f39e

Please sign in to comment.