42 |
* is_number(s) Return true if s is a string of digits. |
* is_number(s) Return true if s is a string of digits. |
43 |
*/ |
*/ |
44 |
|
|
45 |
|
#include <ctype.h> |
46 |
|
#include <errno.h> |
47 |
|
#include <inttypes.h> |
48 |
|
#include <limits.h> |
49 |
|
#include <stdint.h> |
50 |
#include <stdlib.h> |
#include <stdlib.h> |
51 |
#include "shell.h" |
#include "shell.h" |
52 |
#include "syntax.h" |
#include "syntax.h" |
60 |
char nullstr[1]; /* zero length string */ |
char nullstr[1]; /* zero length string */ |
61 |
const char spcstr[] = " "; |
const char spcstr[] = " "; |
62 |
const char snlfmt[] = "%s\n"; |
const char snlfmt[] = "%s\n"; |
63 |
const char dolatstr[] = { CTLVAR, VSNORMAL|VSQUOTE, '@', '=', '\0' }; |
const char dolatstr[] = { CTLQUOTEMARK, CTLVAR, VSNORMAL, '@', '=', |
64 |
|
CTLQUOTEMARK, '\0' }; |
65 |
const char illnum[] = "Illegal number: %s"; |
const char illnum[] = "Illegal number: %s"; |
66 |
const char homestr[] = "HOME"; |
const char homestr[] = "HOME"; |
67 |
|
|
108 |
return (char *) string; |
return (char *) string; |
109 |
} |
} |
110 |
|
|
111 |
|
void badnum(const char *s) |
112 |
|
{ |
113 |
|
sh_error(illnum, s); |
114 |
|
} |
115 |
|
|
116 |
|
/* |
117 |
|
* Convert a string into an integer of type intmax_t. Alow trailing spaces. |
118 |
|
*/ |
119 |
|
intmax_t atomax(const char *s, int base) |
120 |
|
{ |
121 |
|
char *p; |
122 |
|
intmax_t r; |
123 |
|
|
124 |
|
errno = 0; |
125 |
|
r = strtoimax(s, &p, base); |
126 |
|
|
127 |
|
if (errno != 0) |
128 |
|
badnum(s); |
129 |
|
|
130 |
|
/* |
131 |
|
* Disallow completely blank strings in non-arithmetic (base != 0) |
132 |
|
* contexts. |
133 |
|
*/ |
134 |
|
if (p == s && base) |
135 |
|
badnum(s); |
136 |
|
|
137 |
|
while (isspace((unsigned char)*p)) |
138 |
|
p++; |
139 |
|
|
140 |
|
if (*p) |
141 |
|
badnum(s); |
142 |
|
|
143 |
|
return r; |
144 |
|
} |
145 |
|
|
146 |
|
intmax_t atomax10(const char *s) |
147 |
|
{ |
148 |
|
return atomax(s, 10); |
149 |
|
} |
150 |
|
|
151 |
/* |
/* |
152 |
* Convert a string of digits to an integer, printing an error message on |
* Convert a string of digits to an integer, printing an error message on |
156 |
int |
int |
157 |
number(const char *s) |
number(const char *s) |
158 |
{ |
{ |
159 |
|
intmax_t n = atomax10(s); |
160 |
|
|
161 |
|
if (n < 0 || n > INT_MAX) |
162 |
|
badnum(s); |
163 |
|
|
164 |
if (! is_number(s)) |
return n; |
|
sh_error(illnum, s); |
|
|
return atoi(s); |
|
165 |
} |
} |
166 |
|
|
167 |
|
|