822bcf1a243795521a26a9a378746af0889ab0f7
[musl] / src / stdlib / wcstol.c
1 #include "stdio_impl.h"
2 #include "intscan.h"
3 #include "shgetc.h"
4
5 /* This read function heavily cheats. It knows:
6  *  (1) len will always be 1
7  *  (2) non-ascii characters don't matter */
8
9 static size_t do_read(FILE *f, unsigned char *buf, size_t len)
10 {
11         size_t i;
12         const wchar_t *wcs = f->cookie;
13
14         if (!wcs[0]) wcs=L"@";
15         for (i=0; i<f->buf_size && wcs[i]; i++)
16                 f->buf[i] = wcs[i] < 128 ? wcs[i] : '@';
17         f->rpos = f->buf;
18         f->rend = f->buf + i;
19         f->cookie = (void *)(wcs+i);
20
21         if (i && len) {
22                 *buf = *f->rpos++;
23                 return 1;
24         }
25         return 0;
26 }
27
28 static unsigned long long wcstox(const wchar_t *s, wchar_t **p, int base, unsigned long long lim)
29 {
30         unsigned char buf[64];
31         FILE f = {0};
32         f.flags = 0;
33         f.rpos = f.rend = 0;
34         f.buf = buf + 4;
35         f.buf_size = sizeof buf - 4;
36         f.lock = -1;
37         f.read = do_read;
38         f.cookie = (void *)s;
39         shlim(&f, 0);
40         unsigned long long y = __intscan(&f, base, 1, lim);
41         if (p) {
42                 size_t cnt = shcnt(&f);
43                 *p = (wchar_t *)s + cnt;
44         }
45         return y;
46 }
47
48 unsigned long long wcstoull(const wchar_t *s, wchar_t **p, int base)
49 {
50         return wcstox(s, p, base, ULLONG_MAX);
51 }
52
53 long long wcstoll(const wchar_t *s, wchar_t **p, int base)
54 {
55         return wcstox(s, p, base, LLONG_MIN);
56 }
57
58 unsigned long wcstoul(const wchar_t *s, wchar_t **p, int base)
59 {
60         return wcstox(s, p, base, ULONG_MAX);
61 }
62
63 long wcstol(const wchar_t *s, wchar_t **p, int base)
64 {
65         return wcstox(s, p, base, 0UL+LONG_MIN);
66 }
67
68 intmax_t wcstoimax(const wchar_t *s, wchar_t **p, int base)
69 {
70         return wcstoll(s, p, base);
71 }
72
73 uintmax_t wcstoumax(const wchar_t *s, wchar_t **p, int base)
74 {
75         return wcstoull(s, p, base);
76 }