summaryrefslogtreecommitdiff
path: root/src/user/lib/libc/std/stdio.c
blob: 359562298b5cc190e4b862fee98702bf27612d2c (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
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
#include <stdlib.h>
#include <stdio.h>
#include <tce/syscall.h>
#include <readline.h>

FILE term = 0;
void print(char *s) { fprint(term, s); }
void printf(char *format,  ...) {
	va_list ap;
	va_start(ap, format);
	vfprintf(term, format, ap);
	va_end(ap);
}
char* readln() { return freadln(term); }

void fprintf(FILE f, char* format, ...) {
	va_list ap;
	va_start(ap, format);
	vfprintf(f, format, ap);
	va_end(ap);
}

// INTERNAL, FOR FORMATTING

static char* format_int(char* buf, int number) {
	if (number == 0) {
		*(buf++) = '0';
		return buf;
	}
	if (number < 0) {
		*(buf++) = '-';
		number = 0 - number;
	}

	int order = 0, temp = number, i;
	char numbers[] = "0123456789";
	while (temp > 0) {
		order++;
		temp /= 10;
	}

	for (i = order; i > 0; i--) {
		buf[i - 1] = numbers[number % 10];
		number /= 10;
	}
	return buf + order;
}

static char* format_hex(char *buf, unsigned v) {
	*(buf++) = '0';
	*(buf++) = 'x';

	int i;
	char hexdigits[] = "0123456789ABCDEF";
	for (i = 0; i < 8; i++) {
		*(buf++) = hexdigits[v >> 28];
		v = v << 4;
	}
	return buf;
}


// FUNCTIONS

void fprint(FILE f, char *s) {
	write(f, 0, strlen(s), s);
}

void fprint_int(FILE f, int number) {
	char s[32];
	char *v = format_int(s, number);
	*v = 0;
	fprint(f, s);
}

void fprint_hex(FILE f, unsigned v) {
	char s[11];
	char *e = format_hex(s, v);
	*e = 0;
	fprint(f, s);
}

void vfprintf(FILE f, char *format, va_list ap) {
	char bb[256];
	int bufl = 256;

	char *buf = bb;
	char *end = buf;

	while (*format) {
		if (*format == '%') {
			// ASSUMPTION : (TODO) WE HAVE ENOUGH SPACE - NOT THE CASE!!!
			format++;
			if (*format == 'd' || *format == 'i') {
				end = format_int(end, va_arg(ap, int));
			} else if (*format == 'p') {
				end = format_hex(end, va_arg(ap, uint32_t));
			} else if (*format == 's') {
				char *s = va_arg(ap, char*);
				strcpy(end, s);
				end += strlen(s);
			}
			format++;
		} else {
			*(end++) = *(format++);
		}
		if (end - buf > bufl - 2) {
			bufl *= 2;
			char *nbuf = (char*)malloc(bufl);
			memcpy(nbuf, buf, end - buf);
			end = nbuf + (end - buf);
			if (buf != bb) free(buf);
			buf = nbuf;
		}
	}
	*end = 0;
	fprint(f, buf);
	if (buf != bb) free(buf);
}