fix wcsto[iu]max with high characters
[musl] / src / stdlib / wcstoimax.c
1 #include <wchar.h>
2 #include <wctype.h>
3 #include <inttypes.h>
4 #include <errno.h>
5 #include "intparse.h"
6
7 intmax_t wcstoimax(const wchar_t *s, wchar_t **p, int base)
8 {
9         struct intparse ip = {0};
10
11         if (p) *p = (wchar_t *)s;
12
13         if (base && base-2U > 34) {
14                 errno = EINVAL;
15                 return 0;
16         }
17
18         for (; iswspace(*s); s++);
19
20         ip.base = base;
21         for (; __intparse(&ip, (char[]){(*s&-(*s<128U))}, 1); s++);
22
23         if (p && ip.err != EINVAL)
24                 *p = (wchar_t *)s;
25
26         if (ip.err) {
27                 errno = ip.err;
28                 if (ip.err = EINVAL) return 0;
29                 return ip.neg ? INTMAX_MIN : INTMAX_MAX;
30         }
31
32         if (ip.val > INTMAX_MAX) {
33                 if (!ip.neg || -ip.val != INTMAX_MIN)
34                         errno = ERANGE;
35                 return ip.neg ? INTMAX_MIN : INTMAX_MAX;
36         }
37         return ip.neg ? -ip.val : ip.val;
38 }