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