update for HEAD-2003091401
[reactos.git] / lib / ntdll / stdlib / wcstoul.c
1 /* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
2 #include <limits.h>
3 #include <ctype.h>
4 #include <stdlib.h>
5
6
7 /*
8  * Convert a unicode string to an unsigned long integer.
9  *
10  * Ignores `locale' stuff.  Assumes that the upper and lower case
11  * alphabets and digits are each contiguous.
12  *
13  * @implemented
14  */
15 unsigned long
16 wcstoul(const wchar_t *nptr, wchar_t **endptr, int base)
17 {
18   const wchar_t *s = nptr;
19   unsigned long acc;
20   int c;
21   unsigned long cutoff;
22   int neg = 0, any, cutlim;
23
24   /*
25    * See strtol for comments as to the logic used.
26    */
27   do {
28     c = *s++;
29   } while (iswctype(c, _SPACE));
30   if (c == '-')
31   {
32     neg = 1;
33     c = *s++;
34   }
35   else if (c == L'+')
36     c = *s++;
37   if ((base == 0 || base == 16) &&
38       c == L'0' && (*s == L'x' || *s == L'X'))
39   {
40     c = s[1];
41     s += 2;
42     base = 16;
43   }
44   if (base == 0)
45     base = c == L'0' ? 8 : 10;
46   cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
47   cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
48   for (acc = 0, any = 0;; c = *s++)
49   {
50     if (iswctype(c, _DIGIT))
51       c -= L'0';
52     else if (iswctype(c, _ALPHA))
53       c -= iswctype(c, _UPPER) ? L'A' - 10 : L'a' - 10;
54     else
55       break;
56     if (c >= base)
57       break;
58     if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
59       any = -1;
60     else {
61       any = 1;
62       acc *= base;
63       acc += c;
64     }
65   }
66   if (any < 0)
67   {
68     acc = ULONG_MAX;
69   }
70   else if (neg)
71     acc = -acc;
72   if (endptr != 0)
73     *endptr = any ? (wchar_t *)s - 1 : (wchar_t *)nptr;
74   return acc;
75 }