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 */
27 * Convert a string to a long integer.
29 * Ignores `locale' stuff. Assumes that the upper and lower case
30 * alphabets and digits are each contiguous.
32 long strtol(const char *nptr, char **endptr, int base) {
33 register const char *s = nptr;
34 register unsigned long acc;
36 register unsigned long cutoff;
37 register int neg = 0, any, cutlim;
40 * Skip white space and pick up leading +/- sign if any.
41 * If base is 0, allow 0x for hex and 0 for octal, else
42 * assume decimal; if base is already 16, allow 0x.
52 if ((base == 0 || base == 16) &&
53 c == '0' && (*s == 'x' || *s == 'X')) {
59 base = c == '0' ? 8 : 10;
62 * Compute the cutoff value between legal numbers and illegal
63 * numbers. That is the largest legal value, divided by the
64 * base. An input number that is greater than this value, if
65 * followed by a legal input character, is too big. One that
66 * is equal to this value may be valid or not; the limit
67 * between valid and invalid numbers is then based on the last
68 * digit. For instance, if the range for longs is
69 * [-2147483648..2147483647] and the input base is 10,
70 * cutoff will be set to 214748364 and cutlim to either
71 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
72 * a value > 214748364, or equal but the next digit is > 7 (or 8),
73 * the number is too big, and we will return a range error.
75 * Set any if any `digits' consumed; make it negative to indicate
78 cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
79 cutlim = cutoff % (unsigned long)base;
80 cutoff /= (unsigned long)base;
81 for (acc = 0, any = 0;; c = *s++) {
85 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
90 if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
99 acc = neg ? LONG_MIN : LONG_MAX;
103 *endptr = (char *) (any ? s - 1 : nptr);
108 /* Convert a string to an int. */
109 int atoi(const char *nptr) {
110 return (int)strtol(nptr, 0, 10);
113 /* Convert a string to a long int. */
114 long int atol(const char *nptr) {
115 return strtol(nptr, 0, 10);