-
Notifications
You must be signed in to change notification settings - Fork 0
/
kprintf.c
159 lines (134 loc) · 2.66 KB
/
kprintf.c
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#include "kprintf.h"
#include "stdarg.h"
#include "stdint.h"
#include "vga.h"
#include "com.h"
static void (*outf)(char) = 0;
static void kputs(const char *s)
{
while (*s) {
outf(*s);
s++;
}
}
static void kputx(uint32_t n)
{
uint32_t rn = 0, scale = 0, start = 1;
while (n) {
if (start && (n & 15) == 0) {
scale++;
} else {
start = 0;
}
rn = (rn << 4) + (n & 15);
n >>= 4;
}
if (!rn) {
outf('0');
outf('0');
}
while (rn) {
outf("0123456789ABCDEF"[rn & 15]);
rn >>= 4;
}
while (scale--) {
outf('0');
}
}
static void kputd(uint32_t n)
{
uint32_t rn = 0, scale = 0, start = 1, m;
int32_t nn;
int s = 1;
if (n >> 31 == 1) {
nn = ~n + 1;
s = -1;
} else {
nn = n;
}
while (nn) {
if (start && nn % 10 == 0) {
scale++;
} else {
start = 0;
}
rn = rn * 10 + nn % 10;
nn /= 10;
}
if (!rn) {
outf('0');
return;
}
if (s == -1) {
outf('-');
}
while (rn) {
outf('0' + (rn % 10));
rn /= 10;
}
while (scale--) {
outf('0');
}
}
static void kpute(char s)
{
switch (s) {
case 'b':
outf('\b');
break;
case 'n':
outf('\n');
break;
case 'r':
outf('\r');
break;
case 't':
outf('\t');
break;
}
}
static void kputc(char s)
{
outf(s);
}
void kprintf(enum outdev dev, const char *restrict fmt, ...)
{
va_list ap;
char *s;
outf = dev == OUTDEV_VGA ? vga_putchar : com_write;
va_start(ap, fmt);
for (; *fmt; fmt++) {
if (*fmt == '%') {
fmt++;
switch (*fmt) {
case '%':
kputc('%');
break;
case 'c':
kputc(va_arg(ap, int));
break;
case 's':
s = va_arg(ap, char *);
kputs(s);
break;
case 'd':
kputd(va_arg(ap, uint32_t));
break;
case 'x':
kputx(va_arg(ap, uint32_t));
break;
default:
kputs(":-??");
break;
}
} else {
if (*fmt == '\\') {
fmt++;
kpute(*fmt);
} else {
kputc(*fmt);
}
}
}
va_end(ap);
}