aboutsummaryrefslogtreecommitdiff
path: root/src/mlibc/stdio/printf.c
blob: 11516cf7c306881ae891795cba55dc61d6973838 (plain) (blame)
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
#include <stdarg.h>
#include <stdint.h>
#include <mlibc/stdio.h>
#include <mlibc/string.h>
#include <mlibc/stdlib.h>

void __writes(const char *data) {
    for (size_t i = 0; i < strlen(data); i++) writec(data[i]);
}

void printf(const char *fmt, ...) {
    va_list args;
    va_start(args, fmt);

    uint8_t readyToFormat = 0;

    char buff = 0;

    for (; *fmt; fmt++) {
        if (readyToFormat) {
            if (*fmt == '%') {
                writec('%');
                readyToFormat = 0;
                continue;
            }

            buff = *fmt;
            if (buff == 's') {
                const char *str = va_arg(args, const char*);
                __writes(str);
                readyToFormat = 0;
            } else if (buff == 'x') {
                char *p = htoa((uint32_t) va_arg(args, int));
                __writes(p);
                kfree(p);
                readyToFormat = 0;
            } else if (buff == 'd') {
                char *p = itoa(va_arg(args, int));
                __writes(p);
                kfree(p);
                readyToFormat = 0;
            } else if (buff == 'c') {
                writec((char) va_arg(args, int));
                readyToFormat = 0;
            }
        } else {
            if (*fmt == '%')
                readyToFormat = 1;
            else
                writec(*fmt);
        }
    }
}