summaryrefslogtreecommitdiff
path: root/kernel/printf.c
blob: 0b51f8de51aa97a6c13d5ac967732713d32ab013 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "printf.h"
#include "types.h"
#include "portio.h"

void putchar(char c) {
	if(c == '\n') {
		outb(0x3f8, '\r');
	}
	outb(0x3f8, c);
}

int printf(const char* format, ...) {
	int32_t* argp = (int32_t*)&format;
	int num;
	
	while(*format) {
		if(*format != '%') {
			putchar(*format++);
			num++;
			continue;
		}
		format++;
		
		bool is_signed = false;
		bool zero_pad = false;
		int radix = 16;
		int min_len = 0;
		
		if(*format == '0') {
			zero_pad = true;
		}
		
		while(*format >= '0' && *format <= '9') {
			min_len = min_len * 10 + *format++ - '0';
		}
		
		switch(*format++) {
			case '%':
				putchar('%');
				num++;
				break;
			
			case 'c':
				putchar((char)*++argp);
				num++;
				break;
			
			case 's':
				;
				char* str = (char*)*++argp;
				while(*str) {
					putchar(*str++);
					num++;
				}
				break;
			
			case 'd':
				is_signed = true;
			case 'u':
				radix = 10;
			case 'x':
				;
				uint32_t x = (uint32_t)*(++argp);
				if(is_signed && (int32_t)x < 0) {
					x = -x;
					putchar('-');
					min_len--;
				}
				
				char buf[11];
				char* bufp = &buf[sizeof(buf)];
				*--bufp = 0;
				
				do {
					int d = x % radix;
					*--bufp = d < 10 ? '0' + d : 'a' - 10 + d;
					x /= radix;
					min_len--;
				} while(x);
				
				while(min_len > 0) {
					putchar(zero_pad ? '0' : ' ');
					num++;
					min_len--;
				}
				
				while(*bufp) {
					putchar(*bufp++);
					num++;
				}
				break;
		}
	}
	return num;
}