86528ef15715be4952bb950ac6941594d3c84783
[musl] / src / stdlib / wcstoumax.c
1 #include <wchar.h>
2 #include <wctype.h>
3 #include <stdlib.h>
4 #include <inttypes.h>
5 #include <errno.h>
6
7 uintmax_t wcstoumax(const wchar_t *s, wchar_t **p, int base)
8 {
9         /* Large enough for largest value in binary */
10         char buf[sizeof(uintmax_t)*8+2];
11         int sign = 0, skipped=0;
12
13         if (!p) p = (wchar_t **)&s;
14
15         if (base && (unsigned)base-2 > 36-2) {
16                 *p = (wchar_t *)s;
17                 errno = EINVAL;
18                 return 0;
19         }
20
21         /* Initial whitespace */
22         for (; iswspace(*s); s++);
23
24         /* Optional sign */
25         if (*s == '-') sign = *s++;
26         else if (*s == '+') s++;
27
28         /* Skip leading zeros but don't allow leading zeros before "0x". */
29         for (; s[0]=='0' && s[1]=='0'; s++) skipped=1;
30         if (skipped && (base==0 || base==16) && (s[1]|32)=='x') {
31                 *p = (wchar_t *)(s+1);
32                 return 0;
33         }
34
35         /* Convert to normal char string so we can use strtoumax */
36         buf[0] = sign;
37         if (wcstombs(buf+!!sign, s, sizeof buf-1) == -1) return 0;
38         buf[sizeof buf-1]=0;
39
40         /* Compute final position */
41         if (p) {
42                 if ((base==0 || base==16) && s[0]=='0' && (s[1]|32)=='x' && iswxdigit(s[2])) s+=2;
43                 for(;*s&&((unsigned)*s-'0'<base||((unsigned)*s|32)-'a'<base-10);s++);
44                 *p = (wchar_t *)s;
45         }
46
47         return strtoumax(buf, 0, base);
48 }