* same with xv6
[mascara-docs.git] / i386 / ucla / src / lab5 / lib / printf.c
blob31f75993fe2c03f7a45ccbb7ae2ece2da420c7dc
1 // Implementation of cprintf console output for user environments,
2 // based on printfmt() and the sys_cputs() system call.
3 //
4 // cprintf is a debugging statement, not a generic output statement.
5 // It is very important that it always go to the console, especially when
6 // debugging file descriptor code!
8 #include <inc/types.h>
9 #include <inc/stdio.h>
10 #include <inc/stdarg.h>
11 #include <inc/lib.h>
14 // Collect up to 256 characters into a buffer
15 // and perform ONE system call to print all of them,
16 // in order to make the lines output to the console atomic
17 // and prevent interrupts from causing context switches
18 // in the middle of a console output line and such.
19 struct printbuf {
20 int idx; // current buffer index
21 int cnt; // total bytes printed so far
22 char buf[256];
26 static void
27 putch(int ch, void *ptr)
29 struct printbuf *b = (struct printbuf *) ptr;
30 b->buf[b->idx++] = ch;
31 if (b->idx == 256-1) {
32 sys_cputs(b->buf, b->idx);
33 b->idx = 0;
35 b->cnt++;
38 int
39 vcprintf(const char *fmt, va_list ap)
41 struct printbuf b;
43 b.idx = 0;
44 b.cnt = 0;
45 vprintfmt(putch, &b, fmt, ap);
46 sys_cputs(b.buf, b.idx);
48 return b.cnt;
51 int
52 cprintf(const char *fmt, ...)
54 va_list ap;
55 int cnt;
57 va_start(ap, fmt);
58 cnt = vcprintf(fmt, ap);
59 va_end(ap);
61 return cnt;