xref: /freebsd/usr.bin/seq/seq.c (revision 035dd78d30ba28a3dc15c05ec85ad10127165677)
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 __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
87 main(int argc, char *argv[])
88 {
89 	const char *sep, *term;
90 	struct lconv *locale;
91 	char pad, *fmt, *cur_print, *last_print, *prev_print;
92 	double first, last, incr, prev, cur, step;
93 	int c, errflg, equalize;
94 
95 	pad = ZERO;
96 	fmt = NULL;
97 	first = 1.0;
98 	last = incr = prev = 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 		prev = 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 'prev' are not
198 	 * equal, it means the exit condition of the loop held true due to a
199 	 * rounding error and we still need to print 'last'.
200 	 */
201 	if (asprintf(&cur_print, fmt, cur) < 0) {
202 		err(1, "asprintf");
203 	}
204 	if (asprintf(&last_print, fmt, last) < 0) {
205 		err(1, "asprintf");
206 	}
207 	if (asprintf(&prev_print, fmt, prev) < 0) {
208 		err(1, "asprintf");
209 	}
210 	if (strcmp(cur_print, last_print) == 0 &&
211 	    strcmp(cur_print, prev_print) != 0) {
212 		fputs(last_print, stdout);
213 		fputs(sep, stdout);
214 	}
215 	free(cur_print);
216 	free(last_print);
217 	free(prev_print);
218 
219 	if (term != NULL)
220 		fputs(term, stdout);
221 
222 	return (0);
223 }
224 
225 /*
226  * numeric - verify that string is numeric
227  */
228 static int
229 numeric(const char *s)
230 {
231 	int seen_decimal_pt, decimal_pt_len;
232 
233 	/* skip any sign */
234 	if (ISSIGN((unsigned char)*s))
235 		s++;
236 
237 	seen_decimal_pt = 0;
238 	decimal_pt_len = strlen(decimal_point);
239 	while (*s) {
240 		if (!isdigit((unsigned char)*s)) {
241 			if (!seen_decimal_pt &&
242 			    strncmp(s, decimal_point, decimal_pt_len) == 0) {
243 				s += decimal_pt_len;
244 				seen_decimal_pt = 1;
245 				continue;
246 			}
247 			if (ISEXP((unsigned char)*s)) {
248 				s++;
249 				if (ISSIGN((unsigned char)*s) ||
250 				    isdigit((unsigned char)*s)) {
251 					s++;
252 					continue;
253 				}
254 			}
255 			break;
256 		}
257 		s++;
258 	}
259 	return (*s == '\0');
260 }
261 
262 /*
263  * valid_format - validate user specified format string
264  */
265 static int
266 valid_format(const char *fmt)
267 {
268 	unsigned conversions = 0;
269 
270 	while (*fmt != '\0') {
271 		/* scan for conversions */
272 		if (*fmt != '%') {
273 			fmt++;
274 			continue;
275 		}
276 		fmt++;
277 
278 		/* allow %% but not things like %10% */
279 		if (*fmt == '%') {
280 			fmt++;
281 			continue;
282 		}
283 
284 		/* flags */
285 		while (*fmt != '\0' && strchr("#0- +'", *fmt)) {
286 			fmt++;
287 		}
288 
289 		/* field width */
290 		while (*fmt != '\0' && strchr("0123456789", *fmt)) {
291 			fmt++;
292 		}
293 
294 		/* precision */
295 		if (*fmt == '.') {
296 			fmt++;
297 			while (*fmt != '\0' && strchr("0123456789", *fmt)) {
298 				fmt++;
299 			}
300 		}
301 
302 		/* conversion */
303 		switch (*fmt) {
304 		    case 'A':
305 		    case 'a':
306 		    case 'E':
307 		    case 'e':
308 		    case 'F':
309 		    case 'f':
310 		    case 'G':
311 		    case 'g':
312 			/* floating point formats are accepted */
313 			conversions++;
314 			break;
315 		    default:
316 			/* anything else is not */
317 			return 0;
318 		}
319 	}
320 
321 	/* PR 236347 -- user format strings must have a conversion */
322 	return (conversions == 1);
323 }
324 
325 /*
326  * unescape - handle C escapes in a string
327  */
328 static char *
329 unescape(char *orig)
330 {
331 	char c, *cp, *new = orig;
332 	int i;
333 
334 	for (cp = orig; (*orig = *cp); cp++, orig++) {
335 		if (*cp != '\\')
336 			continue;
337 
338 		switch (*++cp) {
339 		case 'a':	/* alert (bell) */
340 			*orig = '\a';
341 			continue;
342 		case 'b':	/* backspace */
343 			*orig = '\b';
344 			continue;
345 		case 'e':	/* escape */
346 			*orig = '\e';
347 			continue;
348 		case 'f':	/* formfeed */
349 			*orig = '\f';
350 			continue;
351 		case 'n':	/* newline */
352 			*orig = '\n';
353 			continue;
354 		case 'r':	/* carriage return */
355 			*orig = '\r';
356 			continue;
357 		case 't':	/* horizontal tab */
358 			*orig = '\t';
359 			continue;
360 		case 'v':	/* vertical tab */
361 			*orig = '\v';
362 			continue;
363 		case '\\':	/* backslash */
364 			*orig = '\\';
365 			continue;
366 		case '\'':	/* single quote */
367 			*orig = '\'';
368 			continue;
369 		case '\"':	/* double quote */
370 			*orig = '"';
371 			continue;
372 		case '0':
373 		case '1':
374 		case '2':
375 		case '3':	/* octal */
376 		case '4':
377 		case '5':
378 		case '6':
379 		case '7':	/* number */
380 			for (i = 0, c = 0;
381 			     ISODIGIT((unsigned char)*cp) && i < 3;
382 			     i++, cp++) {
383 				c <<= 3;
384 				c |= (*cp - '0');
385 			}
386 			*orig = c;
387 			--cp;
388 			continue;
389 		case 'x':	/* hexadecimal number */
390 			cp++;	/* skip 'x' */
391 			for (i = 0, c = 0;
392 			     isxdigit((unsigned char)*cp) && i < 2;
393 			     i++, cp++) {
394 				c <<= 4;
395 				if (isdigit((unsigned char)*cp))
396 					c |= (*cp - '0');
397 				else
398 					c |= ((toupper((unsigned char)*cp) -
399 					    'A') + 10);
400 			}
401 			*orig = c;
402 			--cp;
403 			continue;
404 		default:
405 			--cp;
406 			break;
407 		}
408 	}
409 
410 	return (new);
411 }
412 
413 /*
414  * e_atof - convert an ASCII string to a double
415  *	exit if string is not a valid double, or if converted value would
416  *	cause overflow or underflow
417  */
418 static double
419 e_atof(const char *num)
420 {
421 	char *endp;
422 	double dbl;
423 
424 	errno = 0;
425 	dbl = strtod(num, &endp);
426 
427 	if (errno == ERANGE)
428 		/* under or overflow */
429 		err(2, "%s", num);
430 	else if (*endp != '\0')
431 		/* "junk" left in number */
432 		errx(2, "invalid floating point argument: %s", num);
433 
434 	/* zero shall have no sign */
435 	if (dbl == -0.0)
436 		dbl = 0;
437 	return (dbl);
438 }
439 
440 /*
441  * decimal_places - count decimal places in a number (string)
442  */
443 static int
444 decimal_places(const char *number)
445 {
446 	int places = 0;
447 	char *dp;
448 
449 	/* look for a decimal point */
450 	if ((dp = strstr(number, decimal_point))) {
451 		dp += strlen(decimal_point);
452 
453 		while (isdigit((unsigned char)*dp++))
454 			places++;
455 	}
456 	return (places);
457 }
458 
459 /*
460  * generate_format - create a format string
461  *
462  * XXX to be bug for bug compatible with Plan9 and GNU return "%g"
463  * when "%g" prints as "%e" (this way no width adjustments are made)
464  */
465 static char *
466 generate_format(double first, double incr, double last, int equalize, char pad)
467 {
468 	static char buf[256];
469 	char cc = '\0';
470 	int precision, width1, width2, places;
471 
472 	if (equalize == 0)
473 		return (default_format);
474 
475 	/* figure out "last" value printed */
476 	if (first > last)
477 		last = first - incr * floor((first - last) / incr);
478 	else
479 		last = first + incr * floor((last - first) / incr);
480 
481 	sprintf(buf, "%g", incr);
482 	if (strchr(buf, 'e'))
483 		cc = 'e';
484 	precision = decimal_places(buf);
485 
486 	width1 = sprintf(buf, "%g", first);
487 	if (strchr(buf, 'e'))
488 		cc = 'e';
489 	if ((places = decimal_places(buf)))
490 		width1 -= (places + strlen(decimal_point));
491 
492 	precision = MAX(places, precision);
493 
494 	width2 = sprintf(buf, "%g", last);
495 	if (strchr(buf, 'e'))
496 		cc = 'e';
497 	if ((places = decimal_places(buf)))
498 		width2 -= (places + strlen(decimal_point));
499 
500 	if (precision) {
501 		sprintf(buf, "%%%c%d.%d%c", pad,
502 		    MAX(width1, width2) + (int) strlen(decimal_point) +
503 		    precision, precision, (cc) ? cc : 'f');
504 	} else {
505 		sprintf(buf, "%%%c%d%c", pad, MAX(width1, width2),
506 		    (cc) ? cc : 'g');
507 	}
508 
509 	return (buf);
510 }
511