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