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