initial check-in, version 0.5.0
[musl] / src / stdio / ungetwc.c
1 #include "stdio_impl.h"
2
3 wint_t ungetwc(wint_t c, FILE *f)
4 {
5         unsigned char mbc[MB_LEN_MAX];
6         int l=1;
7
8         if (c == WEOF) return c;
9
10         /* Try conversion early so we can fail without locking if invalid */
11         if (!isascii(c) && (l = wctomb(mbc, c)) < 0)
12                 return WEOF;
13
14         FLOCK(f);
15
16         f->mode |= f->mode+1;
17
18         /* Fail if unreadable or writing and unable to flush */
19         if ((f->flags & (F_ERR|F_NORD)) || (f->wpos && __oflow(f))) {
20                 FUNLOCK(f);
21                 return EOF;
22         }
23
24         /* Clear write mode */
25         f->wpos = f->wstop = f->wend = 0;
26
27         /* Put the file in read mode */
28         if (!f->rpos) f->rpos = f->rend = f->buf;
29
30         /* If unget buffer is nonempty, fail. */
31         if (f->rpos < f->buf) {
32                 FUNLOCK(f);
33                 return WEOF;
34         }
35
36         /* Put character back into the buffer */
37         if (isascii(c)) *--f->rpos = c;
38         else memcpy(f->rpos -= l, mbc, l);
39
40         /* Clear EOF */
41         f->flags &= ~F_EOF;
42
43         FUNLOCK(f);
44         return c;
45 }