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