xref: /openbsd-src/usr.bin/seq/seq.c (revision d5abdd01d7a5f24fb6f9b0aab446ef59a9e9067a)
1 /*	$OpenBSD: seq.c,v 1.7 2023/06/12 20:15:06 millert Exp $	*/
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 	{"format",	required_argument,	NULL, 'f'},
59 	{"help",	no_argument,		NULL, 'h'},
60 	{"separator",	required_argument,	NULL, 's'},
61 	{"version",	no_argument,		NULL, 'v'},
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 
76 static __dead void usage(int error);
77 
78 /*
79  * The seq command will print out a numeric sequence from 1, the default,
80  * to a user specified upper limit by 1.  The lower bound and increment
81  * maybe indicated by the user on the command line.  The sequence can
82  * be either whole, the default, or decimal numbers.
83  */
84 int
85 main(int argc, char *argv[])
86 {
87 	int c = 0;
88 	int equalize = 0;
89 	double first = 1.0;
90 	double last = 0.0;
91 	double incr = 0.0;
92 	double prev = 0.0;
93 	double cur, step;
94 	struct lconv *locale;
95 	char *fmt = NULL;
96 	const char *sep = "\n";
97 	const char *term = "\n";
98 	char *cur_print, *last_print, *prev_print;
99 	char pad = ZERO;
100 
101 	if (pledge("stdio", NULL) == -1)
102 		err(1, "pledge");
103 
104 	/* Determine the locale's decimal point. */
105 	locale = localeconv();
106 	if (locale && locale->decimal_point && locale->decimal_point[0] != '\0')
107 		decimal_point = locale->decimal_point;
108 
109 	/*
110 	 * Process options, but handle negative numbers separately
111 	 * least they trip up getopt(3).
112 	 */
113 	while ((optind < argc) && !numeric(argv[optind]) &&
114 	    (c = getopt_long(argc, argv, "+f:s:w", long_opts, NULL)) != -1) {
115 
116 		switch (c) {
117 		case 'f':	/* format (plan9/GNU) */
118 			fmt = optarg;
119 			equalize = 0;
120 			break;
121 		case 's':	/* separator (GNU) */
122 			sep = optarg;
123 			break;
124 		case 'v':	/* version (GNU) */
125 			printf("seq version %s\n", VERSION);
126 			return 0;
127 		case 'w':	/* equal width (plan9/GNU) */
128 			if (fmt == NULL) {
129 				if (equalize++)
130 					pad = SPACE;
131 			}
132 			break;
133 		case 'h':	/* help (GNU) */
134 			usage(0);
135 			break;
136 		default:
137 			usage(1);
138 			break;
139 		}
140 	}
141 
142 	argc -= optind;
143 	argv += optind;
144 	if (argc < 1 || argc > 3)
145 		usage(1);
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 		/*
173 		 * XXX to be bug for bug compatible with Plan 9 add a
174 		 * newline if none found at the end of the format string.
175 		 */
176 	} else
177 		fmt = generate_format(first, incr, last, equalize, pad);
178 
179 	warnx("first: %f, incr: %f", first, incr);
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 		prev = 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
193 	 * they are equal after formatting truncation, but 'cur' and 'prev'
194 	 * are different, it means the exit condition of the loop held true
195 	 * due to a rounding error and we still need to print 'last'.
196 	 */
197 	if (asprintf(&cur_print, fmt, cur) == -1 ||
198 	    asprintf(&last_print, fmt, last) == -1 ||
199 	    asprintf(&prev_print, fmt, prev) == -1)
200 		err(1, "asprintf");
201 	if (strcmp(cur_print, last_print) == 0 &&
202 	    strcmp(cur_print, prev_print) != 0) {
203 		if (cur != first)
204 			fputs(sep, stdout);
205 		fputs(last_print, stdout);
206 	}
207 	free(cur_print);
208 	free(last_print);
209 	free(prev_print);
210 
211 	fputs(term, stdout);
212 
213 	return 0;
214 }
215 
216 /*
217  * numeric - verify that string is numeric
218  */
219 static int
220 numeric(const char *s)
221 {
222 	int seen_decimal_pt, decimal_pt_len;
223 
224 	/* skip any sign */
225 	if (ISSIGN((unsigned char)*s))
226 		s++;
227 
228 	seen_decimal_pt = 0;
229 	decimal_pt_len = strlen(decimal_point);
230 	while (*s) {
231 		if (!isdigit((unsigned char)*s)) {
232 			if (!seen_decimal_pt &&
233 			    strncmp(s, decimal_point, decimal_pt_len) == 0) {
234 				s += decimal_pt_len;
235 				seen_decimal_pt = 1;
236 				continue;
237 			}
238 			if (ISEXP((unsigned char)*s)) {
239 				s++;
240 				if (ISSIGN((unsigned char)*s) ||
241 				    isdigit((unsigned char)*s)) {
242 					s++;
243 					continue;
244 				}
245 			}
246 			break;
247 		}
248 		s++;
249 	}
250 	return *s == '\0';
251 }
252 
253 /*
254  * valid_format - validate user specified format string
255  */
256 static int
257 valid_format(const char *fmt)
258 {
259 	unsigned conversions = 0;
260 
261 	while (*fmt != '\0') {
262 		/* scan for conversions */
263 		if (*fmt != '%') {
264 			fmt++;
265 			continue;
266 		}
267 		fmt++;
268 
269 		/* allow %% but not things like %10% */
270 		if (*fmt == '%') {
271 			fmt++;
272 			continue;
273 		}
274 
275 		/* flags */
276 		while (*fmt != '\0' && strchr("#0- +'", *fmt)) {
277 			fmt++;
278 		}
279 
280 		/* field width */
281 		while (*fmt != '\0' && strchr("0123456789", *fmt)) {
282 			fmt++;
283 		}
284 
285 		/* precision */
286 		if (*fmt == '.') {
287 			fmt++;
288 			while (*fmt != '\0' && strchr("0123456789", *fmt)) {
289 				fmt++;
290 			}
291 		}
292 
293 		/* conversion */
294 		switch (*fmt) {
295 		case 'A':
296 		case 'a':
297 		case 'E':
298 		case 'e':
299 		case 'F':
300 		case 'f':
301 		case 'G':
302 		case 'g':
303 			/* floating point formats are accepted */
304 			conversions++;
305 			break;
306 		default:
307 			/* anything else is not */
308 			return 0;
309 		}
310 	}
311 
312 	/* PR 236347 -- user format strings must have a conversion */
313 	return conversions == 1;
314 }
315 
316 /*
317  * e_atof - convert an ASCII string to a double
318  *	exit if string is not a valid double, or if converted value would
319  *	cause overflow or underflow
320  */
321 static double
322 e_atof(const char *num)
323 {
324 	char *endp;
325 	double dbl;
326 
327 	errno = 0;
328 	dbl = strtod(num, &endp);
329 
330 	if (errno == ERANGE)
331 		/* under or overflow */
332 		err(2, "%s", num);
333 	else if (*endp != '\0')
334 		/* "junk" left in number */
335 		errx(2, "invalid floating point argument: %s", num);
336 
337 	/* zero shall have no sign */
338 	if (dbl == -0.0)
339 		dbl = 0;
340 	return dbl;
341 }
342 
343 /*
344  * decimal_places - count decimal places in a number (string)
345  */
346 static int
347 decimal_places(const char *number)
348 {
349 	int places = 0;
350 	char *dp;
351 
352 	/* look for a decimal point */
353 	if ((dp = strstr(number, decimal_point))) {
354 		dp += strlen(decimal_point);
355 
356 		while (isdigit((unsigned char)*dp++))
357 			places++;
358 	}
359 	return places;
360 }
361 
362 /*
363  * generate_format - create a format string
364  *
365  * XXX to be bug for bug compatible with Plan9 and GNU return "%g"
366  * when "%g" prints as "%e" (this way no width adjustments are made)
367  */
368 static char *
369 generate_format(double first, double incr, double last, int equalize, char pad)
370 {
371 	static char buf[256];
372 	char cc = '\0';
373 	int precision, width1, width2, places;
374 
375 	if (equalize == 0)
376 		return default_format;
377 
378 	/* figure out "last" value printed */
379 	if (first > last)
380 		last = first - incr * floor((first - last) / incr);
381 	else
382 		last = first + incr * floor((last - first) / incr);
383 
384 	snprintf(buf, sizeof(buf), "%g", incr);
385 	if (strchr(buf, 'e'))
386 		cc = 'e';
387 	precision = decimal_places(buf);
388 
389 	width1 = snprintf(buf, sizeof(buf), "%g", first);
390 	if (strchr(buf, 'e'))
391 		cc = 'e';
392 	if ((places = decimal_places(buf)))
393 		width1 -= (places + strlen(decimal_point));
394 
395 	precision = MAXIMUM(places, precision);
396 
397 	width2 = snprintf(buf, sizeof(buf), "%g", last);
398 	if (strchr(buf, 'e'))
399 		cc = 'e';
400 	if ((places = decimal_places(buf)))
401 		width2 -= (places + strlen(decimal_point));
402 
403 	/* XXX if incr is floating point fix the precision */
404 	if (precision) {
405 		snprintf(buf, sizeof(buf), "%%%c%d.%d%c", pad,
406 		    MAXIMUM(width1, width2) + (int)strlen(decimal_point) +
407 		    precision, precision, (cc) ? cc : 'f');
408 	} else {
409 		snprintf(buf, sizeof(buf), "%%%c%d%c", pad,
410 		    MAXIMUM(width1, width2), (cc) ? cc : 'g');
411 	}
412 
413 	return buf;
414 }
415 
416 static __dead void
417 usage(int error)
418 {
419 	fprintf(stderr,
420 	    "usage: %s [-w] [-f format] [-s string] [first [incr]] last\n",
421 	    getprogname());
422 	exit(error);
423 }
424