xref: /freebsd/usr.bin/seq/seq.c (revision 74ca7bf1d4c7173d5575ba168bc4b5f6d181ff5a)
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 <math.h>
40 #include <locale.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 #define ZERO	'0'
47 #define SPACE	' '
48 
49 #define MAX(a, b)	(((a) < (b))? (b) : (a))
50 #define ISSIGN(c)	((int)(c) == '-' || (int)(c) == '+')
51 #define ISEXP(c)	((int)(c) == 'e' || (int)(c) == 'E')
52 #define ISODIGIT(c)	((int)(c) >= '0' && (int)(c) <= '7')
53 
54 /* Globals */
55 
56 static const char *decimal_point = ".";	/* default */
57 static char default_format[] = { "%g" };	/* default */
58 
59 /* Prototypes */
60 
61 static double e_atof(const char *);
62 
63 static int decimal_places(const char *);
64 static int numeric(const char *);
65 static int valid_format(const char *);
66 
67 static char *generate_format(double, double, double, int, char);
68 static char *unescape(char *);
69 
70 /*
71  * The seq command will print out a numeric sequence from 1, the default,
72  * to a user specified upper limit by 1.  The lower bound and increment
73  * maybe indicated by the user on the command line.  The sequence can
74  * be either whole, the default, or decimal numbers.
75  */
76 int
77 main(int argc, char *argv[])
78 {
79 	const char *sep, *term;
80 	struct lconv *locale;
81 	char pad, *fmt, *cur_print, *last_print;
82 	double first, last, incr, last_shown_value, cur, step;
83 	int c, errflg, equalize;
84 
85 	pad = ZERO;
86 	fmt = NULL;
87 	first = 1.0;
88 	last = incr = last_shown_value = 0.0;
89 	c = errflg = equalize = 0;
90 	sep = "\n";
91 	term = NULL;
92 
93 	/* Determine the locale's decimal point. */
94 	locale = localeconv();
95 	if (locale && locale->decimal_point && locale->decimal_point[0] != '\0')
96 		decimal_point = locale->decimal_point;
97 
98 	/*
99          * Process options, but handle negative numbers separately
100          * least they trip up getopt(3).
101          */
102 	while ((optind < argc) && !numeric(argv[optind]) &&
103 	    (c = getopt(argc, argv, "f:hs:t:w")) != -1) {
104 
105 		switch (c) {
106 		case 'f':	/* format (plan9) */
107 			fmt = optarg;
108 			equalize = 0;
109 			break;
110 		case 's':	/* separator (GNU) */
111 			sep = unescape(optarg);
112 			break;
113 		case 't':	/* terminator (new) */
114 			term = unescape(optarg);
115 			break;
116 		case 'w':	/* equal width (plan9) */
117 			if (!fmt)
118 				if (equalize++)
119 					pad = SPACE;
120 			break;
121 		case 'h':	/* help (GNU) */
122 		default:
123 			errflg++;
124 			break;
125 		}
126 	}
127 
128 	argc -= optind;
129 	argv += optind;
130 	if (argc < 1 || argc > 3)
131 		errflg++;
132 
133 	if (errflg) {
134 		fprintf(stderr,
135 		    "usage: %s [-w] [-f format] [-s string] [-t string] [first [incr]] last\n",
136 		    getprogname());
137 		exit(1);
138 	}
139 
140 	last = e_atof(argv[argc - 1]);
141 
142 	if (argc > 1)
143 		first = e_atof(argv[0]);
144 
145 	if (argc > 2) {
146 		incr = e_atof(argv[1]);
147 		/* Plan 9/GNU don't do zero */
148 		if (incr == 0.0)
149 			errx(1, "zero %screment", (first < last)? "in" : "de");
150 	}
151 
152 	/* default is one for Plan 9/GNU work alike */
153 	if (incr == 0.0)
154 		incr = (first < last) ? 1.0 : -1.0;
155 
156 	if (incr <= 0.0 && first < last)
157 		errx(1, "needs positive increment");
158 
159 	if (incr >= 0.0 && first > last)
160 		errx(1, "needs negative decrement");
161 
162 	if (fmt != NULL) {
163 		if (!valid_format(fmt))
164 			errx(1, "invalid format string: `%s'", fmt);
165 		fmt = unescape(fmt);
166 		if (!valid_format(fmt))
167 			errx(1, "invalid format string");
168 		/*
169 	         * XXX to be bug for bug compatible with Plan 9 add a
170 		 * newline if none found at the end of the format string.
171 		 */
172 	} else
173 		fmt = generate_format(first, incr, last, equalize, pad);
174 
175 	for (step = 1, cur = first; incr > 0 ? cur <= last : cur >= last;
176 	    cur = first + incr * step++) {
177 		printf(fmt, cur);
178 		fputs(sep, stdout);
179 		last_shown_value = cur;
180 	}
181 
182 	/*
183 	 * Did we miss the last value of the range in the loop above?
184 	 *
185 	 * We might have, so check if the printable version of the last
186 	 * computed value ('cur') and desired 'last' value are equal.  If they
187 	 * are equal after formatting truncation, but 'cur' and
188 	 * 'last_shown_value' are not equal, it means the exit condition of the
189 	 * loop held true due to a rounding error and we still need to print
190 	 * 'last'.
191 	 */
192 	asprintf(&cur_print, fmt, cur);
193 	asprintf(&last_print, fmt, last);
194 	if (strcmp(cur_print, last_print) == 0 && cur != last_shown_value) {
195 		fputs(last_print, stdout);
196 		fputs(sep, stdout);
197 	}
198 	free(cur_print);
199 	free(last_print);
200 
201 	if (term != NULL)
202 		fputs(term, stdout);
203 
204 	return (0);
205 }
206 
207 /*
208  * numeric - verify that string is numeric
209  */
210 static int
211 numeric(const char *s)
212 {
213 	int seen_decimal_pt, decimal_pt_len;
214 
215 	/* skip any sign */
216 	if (ISSIGN((unsigned char)*s))
217 		s++;
218 
219 	seen_decimal_pt = 0;
220 	decimal_pt_len = strlen(decimal_point);
221 	while (*s) {
222 		if (!isdigit((unsigned char)*s)) {
223 			if (!seen_decimal_pt &&
224 			    strncmp(s, decimal_point, decimal_pt_len) == 0) {
225 				s += decimal_pt_len;
226 				seen_decimal_pt = 1;
227 				continue;
228 			}
229 			if (ISEXP((unsigned char)*s)) {
230 				s++;
231 				if (ISSIGN((unsigned char)*s) ||
232 				    isdigit((unsigned char)*s)) {
233 					s++;
234 					continue;
235 				}
236 			}
237 			break;
238 		}
239 		s++;
240 	}
241 	return (*s == '\0');
242 }
243 
244 /*
245  * valid_format - validate user specified format string
246  */
247 static int
248 valid_format(const char *fmt)
249 {
250 	unsigned conversions = 0;
251 
252 	while (*fmt != '\0') {
253 		/* scan for conversions */
254 		if (*fmt != '%') {
255 			fmt++;
256 			continue;
257 		}
258 		fmt++;
259 
260 		/* allow %% but not things like %10% */
261 		if (*fmt == '%') {
262 			fmt++;
263 			continue;
264 		}
265 
266 		/* flags */
267 		while (*fmt != '\0' && strchr("#0- +'", *fmt)) {
268 			fmt++;
269 		}
270 
271 		/* field width */
272 		while (*fmt != '\0' && strchr("0123456789", *fmt)) {
273 			fmt++;
274 		}
275 
276 		/* precision */
277 		if (*fmt == '.') {
278 			fmt++;
279 			while (*fmt != '\0' && strchr("0123456789", *fmt)) {
280 				fmt++;
281 			}
282 		}
283 
284 		/* conversion */
285 		switch (*fmt) {
286 		    case 'A':
287 		    case 'a':
288 		    case 'E':
289 		    case 'e':
290 		    case 'F':
291 		    case 'f':
292 		    case 'G':
293 		    case 'g':
294 			/* floating point formats are accepted */
295 			conversions++;
296 			break;
297 		    default:
298 			/* anything else is not */
299 			return 0;
300 		}
301 	}
302 
303 	return (conversions <= 1);
304 }
305 
306 /*
307  * unescape - handle C escapes in a string
308  */
309 static char *
310 unescape(char *orig)
311 {
312 	char c, *cp, *new = orig;
313 	int i;
314 
315 	for (cp = orig; (*orig = *cp); cp++, orig++) {
316 		if (*cp != '\\')
317 			continue;
318 
319 		switch (*++cp) {
320 		case 'a':	/* alert (bell) */
321 			*orig = '\a';
322 			continue;
323 		case 'b':	/* backspace */
324 			*orig = '\b';
325 			continue;
326 		case 'e':	/* escape */
327 			*orig = '\e';
328 			continue;
329 		case 'f':	/* formfeed */
330 			*orig = '\f';
331 			continue;
332 		case 'n':	/* newline */
333 			*orig = '\n';
334 			continue;
335 		case 'r':	/* carriage return */
336 			*orig = '\r';
337 			continue;
338 		case 't':	/* horizontal tab */
339 			*orig = '\t';
340 			continue;
341 		case 'v':	/* vertical tab */
342 			*orig = '\v';
343 			continue;
344 		case '\\':	/* backslash */
345 			*orig = '\\';
346 			continue;
347 		case '\'':	/* single quote */
348 			*orig = '\'';
349 			continue;
350 		case '\"':	/* double quote */
351 			*orig = '"';
352 			continue;
353 		case '0':
354 		case '1':
355 		case '2':
356 		case '3':	/* octal */
357 		case '4':
358 		case '5':
359 		case '6':
360 		case '7':	/* number */
361 			for (i = 0, c = 0;
362 			     ISODIGIT((unsigned char)*cp) && i < 3;
363 			     i++, cp++) {
364 				c <<= 3;
365 				c |= (*cp - '0');
366 			}
367 			*orig = c;
368 			--cp;
369 			continue;
370 		case 'x':	/* hexadecimal number */
371 			cp++;	/* skip 'x' */
372 			for (i = 0, c = 0;
373 			     isxdigit((unsigned char)*cp) && i < 2;
374 			     i++, cp++) {
375 				c <<= 4;
376 				if (isdigit((unsigned char)*cp))
377 					c |= (*cp - '0');
378 				else
379 					c |= ((toupper((unsigned char)*cp) -
380 					    'A') + 10);
381 			}
382 			*orig = c;
383 			--cp;
384 			continue;
385 		default:
386 			--cp;
387 			break;
388 		}
389 	}
390 
391 	return (new);
392 }
393 
394 /*
395  * e_atof - convert an ASCII string to a double
396  *	exit if string is not a valid double, or if converted value would
397  *	cause overflow or underflow
398  */
399 static double
400 e_atof(const char *num)
401 {
402 	char *endp;
403 	double dbl;
404 
405 	errno = 0;
406 	dbl = strtod(num, &endp);
407 
408 	if (errno == ERANGE)
409 		/* under or overflow */
410 		err(2, "%s", num);
411 	else if (*endp != '\0')
412 		/* "junk" left in number */
413 		errx(2, "invalid floating point argument: %s", num);
414 
415 	/* zero shall have no sign */
416 	if (dbl == -0.0)
417 		dbl = 0;
418 	return (dbl);
419 }
420 
421 /*
422  * decimal_places - count decimal places in a number (string)
423  */
424 static int
425 decimal_places(const char *number)
426 {
427 	int places = 0;
428 	char *dp;
429 
430 	/* look for a decimal point */
431 	if ((dp = strstr(number, decimal_point))) {
432 		dp += strlen(decimal_point);
433 
434 		while (isdigit((unsigned char)*dp++))
435 			places++;
436 	}
437 	return (places);
438 }
439 
440 /*
441  * generate_format - create a format string
442  *
443  * XXX to be bug for bug compatible with Plan9 and GNU return "%g"
444  * when "%g" prints as "%e" (this way no width adjustments are made)
445  */
446 static char *
447 generate_format(double first, double incr, double last, int equalize, char pad)
448 {
449 	static char buf[256];
450 	char cc = '\0';
451 	int precision, width1, width2, places;
452 
453 	if (equalize == 0)
454 		return (default_format);
455 
456 	/* figure out "last" value printed */
457 	if (first > last)
458 		last = first - incr * floor((first - last) / incr);
459 	else
460 		last = first + incr * floor((last - first) / incr);
461 
462 	sprintf(buf, "%g", incr);
463 	if (strchr(buf, 'e'))
464 		cc = 'e';
465 	precision = decimal_places(buf);
466 
467 	width1 = sprintf(buf, "%g", first);
468 	if (strchr(buf, 'e'))
469 		cc = 'e';
470 	if ((places = decimal_places(buf)))
471 		width1 -= (places + strlen(decimal_point));
472 
473 	precision = MAX(places, precision);
474 
475 	width2 = sprintf(buf, "%g", last);
476 	if (strchr(buf, 'e'))
477 		cc = 'e';
478 	if ((places = decimal_places(buf)))
479 		width2 -= (places + strlen(decimal_point));
480 
481 	if (precision) {
482 		sprintf(buf, "%%%c%d.%d%c", pad,
483 		    MAX(width1, width2) + (int) strlen(decimal_point) +
484 		    precision, precision, (cc) ? cc : 'f');
485 	} else {
486 		sprintf(buf, "%%%c%d%c", pad, MAX(width1, width2),
487 		    (cc) ? cc : 'g');
488 	}
489 
490 	return (buf);
491 }
492