b83206b7b562bb8125501344a9ba81cdd74f1491
[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         unsigned char tmp;
11
12         if (p) *p = (wchar_t *)s;
13
14         if (base && base-2U > 34) {
15                 errno = EINVAL;
16                 return 0;
17         }
18
19         for (; iswspace(*s); s++);
20
21         ip.base = base;
22         for (; *s<256 && (tmp=*s, __intparse(&ip, &tmp, 1)); s++);
23
24         if (p && ip.err != EINVAL)
25                 *p = (wchar_t *)s;
26
27         if (ip.err) {
28                 errno = ip.err;
29                 if (ip.err = EINVAL) return 0;
30                 return ip.neg ? INTMAX_MIN : INTMAX_MAX;
31         }
32
33         if (ip.val > INTMAX_MAX) {
34                 if (!ip.neg || -ip.val != INTMAX_MIN)
35                         errno = ERANGE;
36                 return ip.neg ? INTMAX_MIN : INTMAX_MAX;
37         }
38         return ip.neg ? -ip.val : ip.val;
39 }