ciabatta/code/stdio.c

81 lines
2.3 KiB
C
Raw Normal View History

2022-06-06 00:16:44 +00:00
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <_os.h>
2022-06-06 04:57:25 +00:00
#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
2022-06-06 00:16:44 +00:00
2022-06-07 02:57:57 +00:00
#include <_os.h>
2022-06-06 00:16:44 +00:00
typedef void(*OutputFunc)(void* ctx, size_t n, const char str[]);
///////////////////////////////////////////////
// Instantiate formatted print functions
///////////////////////////////////////////////
// TODO: instantiate wide char variants of print
#define FMT_FUNC_NAME fmt_print_char
#define FMT_CHAR_TYPE char
#define FMT_STRLEN_S(s, maxsize) strnlen_s(s, maxsize)
#include "printf.h"
typedef struct {
size_t used, capacity;
char* string;
} StrPrintCtx;
FILE *stdout, *stderr, *stdin;
#define CALL_PRINTF(fmt_func, ctx, out, fmt) \
va_list args; \
va_start(args, fmt); \
int result = fmt_func(ctx, out, fmt, args); \
va_end(args)
static void string_write(void *ctx, size_t n, const char *restrict str) {
StrPrintCtx *c = ctx;
memcpy(c->string + c->used, str, n);
c->used += n;
}
int fprintf(FILE *file, const char *restrict fmt, ...) {
2022-06-07 02:57:57 +00:00
CALL_PRINTF(fmt_print_char, file, _file_write, fmt);
2022-06-06 00:16:44 +00:00
return result;
}
int printf(const char *restrict fmt, ...) {
2022-06-07 02:57:57 +00:00
CALL_PRINTF(fmt_print_char, stdout, _file_write, fmt);
2022-06-06 00:16:44 +00:00
return result;
}
int snprintf(char *restrict s, size_t n, const char *restrict fmt, ...) {
StrPrintCtx ctx = { 0, n, s };
CALL_PRINTF(fmt_print_char, &ctx, string_write, fmt);
return result;
}
int sprintf(char *restrict s, const char *restrict fmt, ...) {
StrPrintCtx ctx = { 0, SIZE_MAX, s };
CALL_PRINTF(fmt_print_char, &ctx, string_write, fmt);
return result;
}
int vfprintf(FILE *file, const char *restrict fmt, va_list args) {
2022-06-07 02:57:57 +00:00
return fmt_print_char(file, _file_write, fmt, args);
2022-06-06 00:16:44 +00:00
}
int vprintf(const char *restrict fmt, va_list args) {
2022-06-07 02:57:57 +00:00
return fmt_print_char(stdout, _file_write, fmt, args);
2022-06-06 00:16:44 +00:00
}
int vsnprintf(char *restrict s, size_t n, const char *restrict fmt, va_list args) {
StrPrintCtx ctx = { 0, n, s };
return fmt_print_char(&ctx, string_write, fmt, args);
}
int vsprintf(char *restrict s, const char *restrict fmt, va_list args) {
StrPrintCtx ctx = { 0, SIZE_MAX, s };
return fmt_print_char(&ctx, string_write, fmt, args);
}