diff --git a/libs/libc/src/printf.cpp b/libs/libc/src/printf.cpp index 16fef188..437a07c7 100644 --- a/libs/libc/src/printf.cpp +++ b/libs/libc/src/printf.cpp @@ -25,7 +25,6 @@ static void __strrev(char* arr, int size) template static char* __unsignedtoa(IntegerType number, char* arr, int base) { int i = 0; - IntegerType r = 0; if (number == 0) { @@ -36,29 +35,60 @@ template static char* __unsignedtoa(IntegerType number, c while (number != 0) { - r = number % base; + IntegerType r = number % (IntegerType)base; arr[i] = (r > 9) ? (r - 10) + 'a' : r + '0'; i++; number /= base; } - __strrev(arr, i - 1); + __strrev(arr, i); arr[i] = '\0'; return arr; } -template -static char* __signedtoa(IntegerType number, char* arr, int base) +template static char* __signedtoa(IntegerType number, char* arr, int base) { + int i = 0, negative = 0; + + if (number == 0) + { + arr[i] = '0'; + arr[i + 1] = '\0'; + return arr; + } + if (number < 0 && base == 10) { - return __unsignedtoa((UnsignedIntegerType)(-number), arr, base); + number *= -1; + negative = 1; } - return __unsignedtoa((UnsignedIntegerType)number, arr, base); + + while (number != 0) + { + IntegerType r = number % base; + arr[i] = (r > 9) ? (r - 10) + 'a' : r + '0'; + i++; + number /= base; + } + + if (negative) + { + arr[i] = '-'; + i++; + } + + __strrev(arr, i); + + arr[i] = '\0'; + + return arr; } +#pragma GCC push_options +#pragma GCC optimize("O0") + template static int internal_printf(const char* format, PutString put_string_callback, ssize_t max, va_list ap) { @@ -150,7 +180,7 @@ static int internal_printf(const char* format, PutString put_string_callback, ss else if (is_long) { char result[25]; - __signedtoa(va_arg(ap, int64_t), result, 10); + __signedtoa(va_arg(ap, int64_t), result, 10); if (buffer_insert_index + strlen(result) > 1024) flush_buffer(); memcpy(buffer + buffer_insert_index, result, strlen(result)); buffer_insert_index += strlen(result); @@ -160,7 +190,7 @@ static int internal_printf(const char* format, PutString put_string_callback, ss else { char result[25]; - __signedtoa(va_arg(ap, int32_t), result, 10); + __signedtoa(va_arg(ap, int32_t), result, 10); if (buffer_insert_index + strlen(result) > 1024) flush_buffer(); memcpy(buffer + buffer_insert_index, result, strlen(result)); buffer_insert_index += strlen(result); @@ -245,6 +275,8 @@ static int internal_printf(const char* format, PutString put_string_callback, ss return written; } +#pragma GCC pop_options + extern "C" { int vprintf(const char* format, va_list ap)