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