summaryrefslogtreecommitdiff
path: root/src/user/lib/std/stdio.c
blob: 1628a781f6f5f9cacbf511cba15eaeff5e12a1dd (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
120
121
122
123
124
125
126
#include <stdlib.h>
#include <stdio.h>
#include <tce/syscall.h>

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

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


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

void fprint_int(FILE f, int number) {
	if (number == 0) {
		fprint(f, "0");
		return;
	}
	int negative = 0;
	if (number < 0) {
		negative = 1;
		number = 0 - number;
	}
	int order = 0, temp = number, i;
	char numbers[] = "0123456789";
	while (temp > 0) {
		order++;
		temp /= 10;
	}

	char s[32], *r;
	if (negative) {
		s[0] = '-';
		r = s + 1;
	} else {
		r = s;
	}

	for (i = order; i > 0; i--) {
		r[i - 1] = numbers[number % 10];
		number /= 10;
	}
	r[order] = 0;
	fprint(f, s);
}

void fprint_hex(FILE f, unsigned v) {
	char s[11] = {'0', 'x', 0};

	int i;

	char hexdigits[] = "0123456789ABCDEF";

	for (i = 0; i < 8; i++) {
		s[i + 2] = (hexdigits[v >> 28]);
		v = v << 4;
	}
	s[11] = 0;
	fprint(f, s);
}

void vsfprintf(FILE f, char *format, va_list ap) {
	char* start = format;

	while (*format) {
		if (*format == '%') {
			if (start != format) write(f, 0, format - start, start);
			format++;
			if (*format == 'd' || *format == 'i') {
				fprint_int(f, va_arg(ap, int));
			} else if (*format == 'p') {
				fprint_hex(f, va_arg(ap, uint32_t));
			} else if (*format == 's') {
				fprint(f, va_arg(ap, char*));
			}
			format++;
			start = format;
		} else {
			format++;
		}
	}
	if (start != format) write(f, 0, format - start, start);
}

char* freadln(FILE f) {
	int i;

	char *p = (char*)malloc(256);
	char *b = p;

	while (1) {
		int l = read(f, 0, 255, b);
		if (l < 0) {
			free(b);
			return 0;
		}

		for (i = 0; i < l; i++) {
			if (b[i] == '\n') {
				b[i+1] = 0;
				return p;
			}
		}

		int d = b - p + l;

		char* newp = (char*)malloc(d + 256);
		memcpy(newp, p, d);
		free(p);
		p = newp;
		b = p + d;
	}
}