aboutsummaryrefslogtreecommitdiff
path: root/lib/stdio/vfprintf.cpp
blob: aa9256d31be1045481ab84a5d3745150fbc468db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <string.h>

static char buffer[3 * sizeof(int) + 2];

extern "C" int
vfprintf(FILE *restrict stream, const char *restrict format, va_list params)
{
  int written = 0;

  int s = 0;
  int l = 0;
  for (int i = 0; format[i] != '\0'; ++i) {
    if (format[i] == '%') {
      written += stream->puts(&format[s], l);
      s = i + 2;
      ++i;

      switch (format[i]) {
      case 's': {
        const char *arg = va_arg(params, const char *);
        written += stream->puts(arg, -1);
      } break;
      case 'c': {
        const int arg = va_arg(params, int);
        stream->putc(arg);
        ++written;
      } break;
      case 'd': {
        const char *arg = itoa(buffer, va_arg(params, int), 10);
        written += stream->puts(arg, -1);
      } break;
      case 'u': {
        const char *arg = utoa(buffer, va_arg(params, unsigned int), 10);
        written += stream->puts(arg, -1);
      } break;
      case 'x': {
        const char *arg = utoa(buffer, va_arg(params, unsigned int), 16);
        written += stream->puts(arg, -1);
      } break;
      }

      l = 0;
    }

    else
      ++l;
  }

  if (l > 0) { written += stream->puts(&format[s], l); }

  stream->flush();
  return written;
}