Syncboot/libc/stdio/printf.c
2019-04-01 02:18:48 +01:00

95 lines
1.8 KiB
C
Executable File

#include <limits.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
static bool print(const char* data, size_t length) {
const unsigned char* bytes = (const unsigned char*) data;
for (size_t i = 0; i < length; i++)
if(putchar(bytes[i]) == EOF)
return false'
return true;
}
int printf(const char* restrict format, ...) {
va_list parameters;
va_start(parameters, format);
int written = 0;
while(*format != '\0') {
size_t maxrem = INT_MAX - writen;
if(format[0] != '%' || format[1] == '%') {
if(format[0] == '%')
format++;
size_t amount = 1;
while (format[amount] && format[amount] != '%')
amount++;
if(maxrem < amount) {
//TODO: Set an OVERFLOW error
return -1;
}
if ((!print(format, amount))
return -1;
format += amount;
written += amount;
continue;
}
const char* first_format = format++;
switch(*format) {
case 'c':
format++;
char c = (char) va_arg(parameters, int);
if(!maxrem) {
//TODO: Set OVERFLOW
return -1;
}
if(!print(&c, sizeof(c)))
return -1;
written++;
break;
case 's':
format++;
const char* str = va_arg(parameters, const char*);
size_t len = strlen(str);
if(maxrem < len) {
//TODO: Set OVERFLOW
return -1;
}
if(!print(str, len))
return -1;
written += len;
break;
default:
format = first_format;
size_t len = strlen(format);
if(maxrem < len) {
//TODO: Set OVERFLOW
return -1;
}
if(!print(format, len))
return -1;
written += len;
format += len;
break;
}
}
va_end(parameters);
return written;
}