1 /* A small test for strtol. Assumes twos complement */
10 #define outfile stderr
19 static unsigned int Failures = 0;
23 static void IncStr (char* Buf)
24 /* Increment a number represented as a string by one. The string MUST not
25 * start with a '9', we cannot handle overflow in this case.
28 int Len = strlen (Buf);
45 static void CheckStrToL (const char* Str, int Base, long Val, unsigned char Ok)
48 long Res = strtol (Str, &EndPtr, Base);
52 "strtol error in \"%s\":\n"
53 " result = %ld, should be %ld, chars = %d\n",
54 Str, Res, Val, EndPtr - Str);
58 if (errno != ERANGE) {
60 "strtol error in \"%s\":\n"
61 " should not convert, but errno = %d\n",
67 "strtol error in \"%s\":\n"
68 " result = %ld, should be %ld, chars = %d\n",
69 Str, Res, Val, EndPtr - Str);
81 /* Prefixed allowed if base = 0 */
82 CheckStrToL ("\t 0x10G ", 0, 16L, OK);
83 CheckStrToL ("\t 0X10G ", 0, 16L, OK);
84 CheckStrToL (" \t0377\t", 0, 255L, OK);
85 CheckStrToL (" 377", 0, 377L, OK);
87 CheckStrToL ("\t -0x10G ", 0, -16L, OK);
88 CheckStrToL ("\t -0X10G ", 0, -16L, OK);
89 CheckStrToL (" \t-0377\t", 0, -255L, OK);
90 CheckStrToL (" -377", 0, -377L, OK);
92 /* No prefixes if base = 10 */
93 CheckStrToL ("\t 1234 ", 10, 1234L, OK);
94 CheckStrToL ("\t -1234 ", 10, -1234L, OK);
95 CheckStrToL ("\t -0x10G ", 10, 0L, OK);
96 CheckStrToL ("\t -0X10G ", 10, 0L, OK);
97 CheckStrToL (" \t-0377\t", 10, -377L, OK);
98 CheckStrToL (" 0377", 10, 377L, OK);
100 /* 0x prefix is allowed if base = 16 */
101 CheckStrToL ("\t 0x1234 ", 16, 0x1234L, OK);
102 CheckStrToL ("\t -0x1234 ", 16, -0x1234L, OK);
103 CheckStrToL ("\t -010G ", 16, -16L, OK);
104 CheckStrToL ("\t 10G ", 16, 16L, OK);
106 /* Check LONG_MIN and LONG_MAX */
107 sprintf (Buf, "%ld", LONG_MIN);
108 CheckStrToL (Buf, 0, LONG_MIN, OK);
109 sprintf (Buf, "%ld", LONG_MAX);
110 CheckStrToL (Buf, 0, LONG_MAX, OK);
112 /* Check value one smaller */
113 sprintf (Buf+1, "%ld", LONG_MIN);
114 Buf[1] = '0'; /* Overwrite '-' */
122 CheckStrToL (Buf, 0, LONG_MIN, ERROR);
124 /* Check value one larger */
125 sprintf (Buf+1, "%ld", LONG_MAX);
131 CheckStrToL (Buf, 0, LONG_MAX, ERROR);
133 /* Check numbers that are much too large or small */
134 CheckStrToL ("-999999999999999999999999999999999999999999999999999999999", 0, LONG_MIN, ERROR);
135 CheckStrToL ("+999999999999999999999999999999999999999999999999999999999", 0, LONG_MAX, ERROR);
136 CheckStrToL (" 999999999999999999999999999999999999999999999999999999999", 0, LONG_MAX, ERROR);
138 /* Check a few other bases */
139 CheckStrToL ("aBcD", 36, 481261L, OK);
140 CheckStrToL ("zyaB", 35, 0L, ERROR);
141 CheckStrToL ("zyaB", 36, 1677395L, ERROR);
143 fprintf (outfile, "Failures: %u\n", Failures);
144 return (Failures != 0);