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