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