aboutsummaryrefslogtreecommitdiff
path: root/lib/libk/stdio/vfprintf.c
blob: 807c26af6d06b17faf9a84ff41d03887b4f407bd (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
55
#include <stdio.h>
#include <string.h>

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

int
vfprintf(FILE *__restrict__ stream, const char *__restrict__ format, va_list params)
{
  int written = 0;

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

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

      l = 0;
    }

    else
      ++l;
  }

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

  stream->flush(stream);
  return written;
}