update for HEAD-2003091401
[reactos.git] / lib / ntdll / stdlib / strtol.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  * @implemented
9  */
10 long
11 strtol(const char *nptr, char **endptr, int base)
12 {
13   const char *s = nptr;
14   unsigned long acc;
15   int c;
16   unsigned long cutoff;
17   int neg = 0, any, cutlim;
18
19   /*
20    * Skip white space and pick up leading +/- sign if any.
21    * If base is 0, allow 0x for hex and 0 for octal, else
22    * assume decimal; if base is already 16, allow 0x.
23    */
24   do {
25     c = *s++;
26   } while (isspace(c));
27   if (c == '-')
28   {
29     neg = 1;
30     c = *s++;
31   }
32   else if (c == '+')
33     c = *s++;
34   if ((base == 0 || base == 16) &&
35       c == '0' && (*s == 'x' || *s == 'X'))
36   {
37     c = s[1];
38     s += 2;
39     base = 16;
40   }
41   if (base == 0)
42     base = c == '0' ? 8 : 10;
43
44   /*
45    * Compute the cutoff value between legal numbers and illegal
46    * numbers.  That is the largest legal value, divided by the
47    * base.  An input number that is greater than this value, if
48    * followed by a legal input character, is too big.  One that
49    * is equal to this value may be valid or not; the limit
50    * between valid and invalid numbers is then based on the last
51    * digit.  For instance, if the range for longs is
52    * [-2147483648..2147483647] and the input base is 10,
53    * cutoff will be set to 214748364 and cutlim to either
54    * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
55    * a value > 214748364, or equal but the next digit is > 7 (or 8),
56    * the number is too big, and we will return a range error.
57    *
58    * Set any if any `digits' consumed; make it negative to indicate
59    * overflow.
60    */
61   cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
62   cutlim = cutoff % (unsigned long)base;
63   cutoff /= (unsigned long)base;
64   for (acc = 0, any = 0;; c = *s++)
65   {
66     if (isdigit(c))
67       c -= '0';
68     else if (isalpha(c))
69       c -= isupper(c) ? 'A' - 10 : 'a' - 10;
70     else
71       break;
72     if (c >= base)
73       break;
74     if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
75       any = -1;
76     else
77     {
78       any = 1;
79       acc *= base;
80       acc += c;
81     }
82   }
83   if (any < 0)
84   {
85     acc = neg ? LONG_MIN : LONG_MAX;
86   }
87   else if (neg)
88     acc = -acc;
89   if (endptr != 0)
90     *endptr = any ? (char *)s - 1 : (char *)nptr;
91   return acc;
92 }