1 //===-- atox.c - Ascii string parsers for LLVM libc Library -------*- C -*-===//
3 // A lot of this code is ripped gratuitously from glibc and libiberty.
5 //===----------------------------------------------------------------------===//
8 #define isspace(x) ((x) == ' ' || (x) == '\t' || (x) == '\n')
9 #define isdigit(x) ((x) >= '0' && (x) <= '9')
10 #define isupper(x) ((x) >= 'A' && (x) <= 'Z')
11 #define islower(x) ((x) >= 'a' && (x) <= 'z')
12 #define isalpha(x) (isupper(x) || islower(x))
15 #define ULONG_MAX ((unsigned long)(~0L)) /* 0xFFFFFFFF */
19 #define LONG_MAX ((long)(ULONG_MAX >> 1)) /* 0x7FFFFFFF */
23 #define LONG_MIN ((long)(~LONG_MAX)) /* 0x80000000 */
28 * Convert a string to a long integer.
30 * Ignores `locale' stuff. Assumes that the upper and lower case
31 * alphabets and digits are each contiguous.
33 long strtol(const char *nptr, char **endptr, int base) {
34 register const char *s = nptr;
35 register unsigned long acc;
37 register unsigned long cutoff;
38 register int neg = 0, any, cutlim;
41 * Skip white space and pick up leading +/- sign if any.
42 * If base is 0, allow 0x for hex and 0 for octal, else
43 * assume decimal; if base is already 16, allow 0x.
53 if ((base == 0 || base == 16) &&
54 c == '0' && (*s == 'x' || *s == 'X')) {
60 base = c == '0' ? 8 : 10;
63 * Compute the cutoff value between legal numbers and illegal
64 * numbers. That is the largest legal value, divided by the
65 * base. An input number that is greater than this value, if
66 * followed by a legal input character, is too big. One that
67 * is equal to this value may be valid or not; the limit
68 * between valid and invalid numbers is then based on the last
69 * digit. For instance, if the range for longs is
70 * [-2147483648..2147483647] and the input base is 10,
71 * cutoff will be set to 214748364 and cutlim to either
72 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
73 * a value > 214748364, or equal but the next digit is > 7 (or 8),
74 * the number is too big, and we will return a range error.
76 * Set any if any `digits' consumed; make it negative to indicate
79 cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
80 cutlim = cutoff % (unsigned long)base;
81 cutoff /= (unsigned long)base;
82 for (acc = 0, any = 0;; c = *s++) {
86 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
91 if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
100 acc = neg ? LONG_MIN : LONG_MAX;
104 *endptr = (char *) (any ? s - 1 : nptr);
109 /* Convert a string to an int. */
110 int atoi(const char *nptr) {
111 return (int)strtol(nptr, 0, 10);
114 /* Convert a string to a long int. */
115 long int atol(const char *nptr) {
116 return strtol(nptr, 0, 10);