1 /* $NetBSD: seq.c,v 1.7 2010/05/27 08:40:19 dholland Exp $ */
2 /*-
3 * SPDX-License-Identifier: BSD-2-Clause-NetBSD
4 *
5 * Copyright (c) 2005 The NetBSD Foundation, Inc.
6 * All rights reserved.
7 *
8 * This code is derived from software contributed to The NetBSD Foundation
9 * by Brian Ginsbach.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include <ctype.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <getopt.h>
40 #include <math.h>
41 #include <locale.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46
47 #define ZERO '0'
48 #define SPACE ' '
49
50 #define MAX(a, b) (((a) < (b))? (b) : (a))
51 #define ISSIGN(c) ((int)(c) == '-' || (int)(c) == '+')
52 #define ISEXP(c) ((int)(c) == 'e' || (int)(c) == 'E')
53 #define ISODIGIT(c) ((int)(c) >= '0' && (int)(c) <= '7')
54
55 /* Globals */
56
57 static const char *decimal_point = "."; /* default */
58 static char default_format[] = { "%g" }; /* default */
59
60 static const struct option long_opts[] =
61 {
62 {"format", required_argument, NULL, 'f'},
63 {"separator", required_argument, NULL, 's'},
64 {"terminator", required_argument, NULL, 't'},
65 {"equal-width", no_argument, NULL, 'w'},
66 {NULL, no_argument, NULL, 0}
67 };
68
69 /* Prototypes */
70
71 static double e_atof(const char *);
72
73 static int decimal_places(const char *);
74 static int numeric(const char *);
75 static int valid_format(const char *);
76
77 static char *generate_format(double, double, double, int, char);
78 static char *unescape(char *);
79
80 /*
81 * The seq command will print out a numeric sequence from 1, the default,
82 * to a user specified upper limit by 1. The lower bound and increment
83 * maybe indicated by the user on the command line. The sequence can
84 * be either whole, the default, or decimal numbers.
85 */
86 int
main(int argc,char * argv[])87 main(int argc, char *argv[])
88 {
89 const char *sep, *term;
90 struct lconv *locale;
91 char pad, *fmt, *cur_print, *last_print;
92 double first, last, incr, last_shown_value, cur, step;
93 int c, errflg, equalize;
94
95 pad = ZERO;
96 fmt = NULL;
97 first = 1.0;
98 last = incr = last_shown_value = 0.0;
99 c = errflg = equalize = 0;
100 sep = "\n";
101 term = NULL;
102
103 /* Determine the locale's decimal point. */
104 locale = localeconv();
105 if (locale && locale->decimal_point && locale->decimal_point[0] != '\0')
106 decimal_point = locale->decimal_point;
107
108 /*
109 * Process options, but handle negative numbers separately
110 * least they trip up getopt(3).
111 */
112 while ((optind < argc) && !numeric(argv[optind]) &&
113 (c = getopt_long(argc, argv, "+f:hs:t:w", long_opts, NULL)) != -1) {
114
115 switch (c) {
116 case 'f': /* format (plan9) */
117 fmt = optarg;
118 equalize = 0;
119 break;
120 case 's': /* separator (GNU) */
121 sep = unescape(optarg);
122 break;
123 case 't': /* terminator (new) */
124 term = unescape(optarg);
125 break;
126 case 'w': /* equal width (plan9) */
127 if (!fmt)
128 if (equalize++)
129 pad = SPACE;
130 break;
131 case 'h': /* help (GNU) */
132 default:
133 errflg++;
134 break;
135 }
136 }
137
138 argc -= optind;
139 argv += optind;
140 if (argc < 1 || argc > 3)
141 errflg++;
142
143 if (errflg) {
144 fprintf(stderr,
145 "usage: %s [-w] [-f format] [-s string] [-t string] [first [incr]] last\n",
146 getprogname());
147 exit(1);
148 }
149
150 last = e_atof(argv[argc - 1]);
151
152 if (argc > 1)
153 first = e_atof(argv[0]);
154
155 if (argc > 2) {
156 incr = e_atof(argv[1]);
157 /* Plan 9/GNU don't do zero */
158 if (incr == 0.0)
159 errx(1, "zero %screment", (first < last)? "in" : "de");
160 }
161
162 /* default is one for Plan 9/GNU work alike */
163 if (incr == 0.0)
164 incr = (first < last) ? 1.0 : -1.0;
165
166 if (incr <= 0.0 && first < last)
167 errx(1, "needs positive increment");
168
169 if (incr >= 0.0 && first > last)
170 errx(1, "needs negative decrement");
171
172 if (fmt != NULL) {
173 if (!valid_format(fmt))
174 errx(1, "invalid format string: `%s'", fmt);
175 fmt = unescape(fmt);
176 if (!valid_format(fmt))
177 errx(1, "invalid format string");
178 /*
179 * XXX to be bug for bug compatible with Plan 9 add a
180 * newline if none found at the end of the format string.
181 */
182 } else
183 fmt = generate_format(first, incr, last, equalize, pad);
184
185 for (step = 1, cur = first; incr > 0 ? cur <= last : cur >= last;
186 cur = first + incr * step++) {
187 printf(fmt, cur);
188 fputs(sep, stdout);
189 last_shown_value = cur;
190 }
191
192 /*
193 * Did we miss the last value of the range in the loop above?
194 *
195 * We might have, so check if the printable version of the last
196 * computed value ('cur') and desired 'last' value are equal. If they
197 * are equal after formatting truncation, but 'cur' and
198 * 'last_shown_value' are not equal, it means the exit condition of the
199 * loop held true due to a rounding error and we still need to print
200 * 'last'.
201 */
202 asprintf(&cur_print, fmt, cur);
203 asprintf(&last_print, fmt, last);
204 if (strcmp(cur_print, last_print) == 0 && cur != last_shown_value) {
205 fputs(last_print, stdout);
206 fputs(sep, stdout);
207 }
208 free(cur_print);
209 free(last_print);
210
211 if (term != NULL)
212 fputs(term, stdout);
213
214 return (0);
215 }
216
217 /*
218 * numeric - verify that string is numeric
219 */
220 static int
numeric(const char * s)221 numeric(const char *s)
222 {
223 int seen_decimal_pt, decimal_pt_len;
224
225 /* skip any sign */
226 if (ISSIGN((unsigned char)*s))
227 s++;
228
229 seen_decimal_pt = 0;
230 decimal_pt_len = strlen(decimal_point);
231 while (*s) {
232 if (!isdigit((unsigned char)*s)) {
233 if (!seen_decimal_pt &&
234 strncmp(s, decimal_point, decimal_pt_len) == 0) {
235 s += decimal_pt_len;
236 seen_decimal_pt = 1;
237 continue;
238 }
239 if (ISEXP((unsigned char)*s)) {
240 s++;
241 if (ISSIGN((unsigned char)*s) ||
242 isdigit((unsigned char)*s)) {
243 s++;
244 continue;
245 }
246 }
247 break;
248 }
249 s++;
250 }
251 return (*s == '\0');
252 }
253
254 /*
255 * valid_format - validate user specified format string
256 */
257 static int
valid_format(const char * fmt)258 valid_format(const char *fmt)
259 {
260 unsigned conversions = 0;
261
262 while (*fmt != '\0') {
263 /* scan for conversions */
264 if (*fmt != '%') {
265 fmt++;
266 continue;
267 }
268 fmt++;
269
270 /* allow %% but not things like %10% */
271 if (*fmt == '%') {
272 fmt++;
273 continue;
274 }
275
276 /* flags */
277 while (*fmt != '\0' && strchr("#0- +'", *fmt)) {
278 fmt++;
279 }
280
281 /* field width */
282 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
283 fmt++;
284 }
285
286 /* precision */
287 if (*fmt == '.') {
288 fmt++;
289 while (*fmt != '\0' && strchr("0123456789", *fmt)) {
290 fmt++;
291 }
292 }
293
294 /* conversion */
295 switch (*fmt) {
296 case 'A':
297 case 'a':
298 case 'E':
299 case 'e':
300 case 'F':
301 case 'f':
302 case 'G':
303 case 'g':
304 /* floating point formats are accepted */
305 conversions++;
306 break;
307 default:
308 /* anything else is not */
309 return 0;
310 }
311 }
312
313 return (conversions <= 1);
314 }
315
316 /*
317 * unescape - handle C escapes in a string
318 */
319 static char *
unescape(char * orig)320 unescape(char *orig)
321 {
322 char c, *cp, *new = orig;
323 int i;
324
325 for (cp = orig; (*orig = *cp); cp++, orig++) {
326 if (*cp != '\\')
327 continue;
328
329 switch (*++cp) {
330 case 'a': /* alert (bell) */
331 *orig = '\a';
332 continue;
333 case 'b': /* backspace */
334 *orig = '\b';
335 continue;
336 case 'e': /* escape */
337 *orig = '\e';
338 continue;
339 case 'f': /* formfeed */
340 *orig = '\f';
341 continue;
342 case 'n': /* newline */
343 *orig = '\n';
344 continue;
345 case 'r': /* carriage return */
346 *orig = '\r';
347 continue;
348 case 't': /* horizontal tab */
349 *orig = '\t';
350 continue;
351 case 'v': /* vertical tab */
352 *orig = '\v';
353 continue;
354 case '\\': /* backslash */
355 *orig = '\\';
356 continue;
357 case '\'': /* single quote */
358 *orig = '\'';
359 continue;
360 case '\"': /* double quote */
361 *orig = '"';
362 continue;
363 case '0':
364 case '1':
365 case '2':
366 case '3': /* octal */
367 case '4':
368 case '5':
369 case '6':
370 case '7': /* number */
371 for (i = 0, c = 0;
372 ISODIGIT((unsigned char)*cp) && i < 3;
373 i++, cp++) {
374 c <<= 3;
375 c |= (*cp - '0');
376 }
377 *orig = c;
378 --cp;
379 continue;
380 case 'x': /* hexadecimal number */
381 cp++; /* skip 'x' */
382 for (i = 0, c = 0;
383 isxdigit((unsigned char)*cp) && i < 2;
384 i++, cp++) {
385 c <<= 4;
386 if (isdigit((unsigned char)*cp))
387 c |= (*cp - '0');
388 else
389 c |= ((toupper((unsigned char)*cp) -
390 'A') + 10);
391 }
392 *orig = c;
393 --cp;
394 continue;
395 default:
396 --cp;
397 break;
398 }
399 }
400
401 return (new);
402 }
403
404 /*
405 * e_atof - convert an ASCII string to a double
406 * exit if string is not a valid double, or if converted value would
407 * cause overflow or underflow
408 */
409 static double
e_atof(const char * num)410 e_atof(const char *num)
411 {
412 char *endp;
413 double dbl;
414
415 errno = 0;
416 dbl = strtod(num, &endp);
417
418 if (errno == ERANGE)
419 /* under or overflow */
420 err(2, "%s", num);
421 else if (*endp != '\0')
422 /* "junk" left in number */
423 errx(2, "invalid floating point argument: %s", num);
424
425 /* zero shall have no sign */
426 if (dbl == -0.0)
427 dbl = 0;
428 return (dbl);
429 }
430
431 /*
432 * decimal_places - count decimal places in a number (string)
433 */
434 static int
decimal_places(const char * number)435 decimal_places(const char *number)
436 {
437 int places = 0;
438 char *dp;
439
440 /* look for a decimal point */
441 if ((dp = strstr(number, decimal_point))) {
442 dp += strlen(decimal_point);
443
444 while (isdigit((unsigned char)*dp++))
445 places++;
446 }
447 return (places);
448 }
449
450 /*
451 * generate_format - create a format string
452 *
453 * XXX to be bug for bug compatible with Plan9 and GNU return "%g"
454 * when "%g" prints as "%e" (this way no width adjustments are made)
455 */
456 static char *
generate_format(double first,double incr,double last,int equalize,char pad)457 generate_format(double first, double incr, double last, int equalize, char pad)
458 {
459 static char buf[256];
460 char cc = '\0';
461 int precision, width1, width2, places;
462
463 if (equalize == 0)
464 return (default_format);
465
466 /* figure out "last" value printed */
467 if (first > last)
468 last = first - incr * floor((first - last) / incr);
469 else
470 last = first + incr * floor((last - first) / incr);
471
472 sprintf(buf, "%g", incr);
473 if (strchr(buf, 'e'))
474 cc = 'e';
475 precision = decimal_places(buf);
476
477 width1 = sprintf(buf, "%g", first);
478 if (strchr(buf, 'e'))
479 cc = 'e';
480 if ((places = decimal_places(buf)))
481 width1 -= (places + strlen(decimal_point));
482
483 precision = MAX(places, precision);
484
485 width2 = sprintf(buf, "%g", last);
486 if (strchr(buf, 'e'))
487 cc = 'e';
488 if ((places = decimal_places(buf)))
489 width2 -= (places + strlen(decimal_point));
490
491 if (precision) {
492 sprintf(buf, "%%%c%d.%d%c", pad,
493 MAX(width1, width2) + (int) strlen(decimal_point) +
494 precision, precision, (cc) ? cc : 'f');
495 } else {
496 sprintf(buf, "%%%c%d%c", pad, MAX(width1, width2),
497 (cc) ? cc : 'g');
498 }
499
500 return (buf);
501 }
502