1#include "locale_impl.h"
2#include "stdio_impl.h"
3#include <ctype.h>
4#include <limits.h>
5#include <string.h>
6#include <wchar.h>
7
8wint_t ungetwc(wint_t c, FILE* f) {
9    unsigned char mbc[MB_LEN_MAX];
10    int l;
11    locale_t *ploc = &CURRENT_LOCALE, loc = *ploc;
12
13    FLOCK(f);
14
15    if (f->mode <= 0)
16        fwide(f, 1);
17    *ploc = f->locale;
18
19    if (!f->rpos)
20        __toread(f);
21    if (!f->rpos || c == WEOF || (l = wcrtomb((void*)mbc, c, 0)) < 0 ||
22        f->rpos < f->buf - UNGET + l) {
23        FUNLOCK(f);
24        *ploc = loc;
25        return WEOF;
26    }
27
28    if (isascii(c))
29        *--f->rpos = c;
30    else
31        memcpy(f->rpos -= l, mbc, l);
32
33    f->flags &= ~F_EOF;
34
35    FUNLOCK(f);
36    *ploc = loc;
37    return c;
38}
39