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