initial check-in, version 0.5.0
[musl] / src / stdio / __overflow.c
1 #include "stdio_impl.h"
2
3 static int overflow(FILE *f, int c)
4 {
5         /* Initialize if we're not already writing */
6         if (!f->wend) {
7                 /* Fail if we're in error state or unwritable. */
8                 if (f->flags & (F_ERR|F_NOWR)) return EOF;
9
10                 /* Set byte orientation -1,0=>-1; 1=>1 */
11                 f->mode |= f->mode-1;
12
13                 /* Clear read buffer (easier than summoning nasal demons) */
14                 f->rpos = f->rend = f->rstop = 0;
15
16                 /* Activate write through the buffer */
17                 f->wpos = f->wbase = f->buf;
18                 f->wend = f->buf + f->buf_size;
19                 f->wstop = (f->lbf < 0) ? f->wend - 1 : 0;
20         }
21
22         /* Buffer can always hold at least 1 byte... */
23         if (c != EOF) {
24                 *f->wpos++ = c;
25                 if (f->wpos <= f->wstop && c != f->lbf) return c;
26         }
27         /* ...since if the next call fails, buffer is empty. */
28         if (f->write(f, f->wbase, f->wpos - f->wbase) < 0) {
29                 f->flags |= F_ERR;
30                 f->wpos = f->wbase = f->wend = f->wstop = 0;
31                 return EOF;
32         }
33
34         /* Buffer is empty so reset position to beginning */
35         f->wpos = f->wbase;
36
37         return c;
38 }
39
40 int __overflow(FILE *f, int c)
41 {
42         return overflow(f, c & 0xff);
43 }
44
45 int __oflow(FILE *f)
46 {
47         overflow(f, EOF);
48         return (f->flags & F_ERR) ? EOF : 0;
49 }
50
51 /* Link flush-on-exit code iff any stdio write functions are linked. */
52 int (*const __fflush_on_exit)(FILE *) = fflush;