mv: consistently warn about multiply specified source dirs
[coreutils.git] / src / seq.c
blobfbb94a0c0f170ec2bdea2bf55476df50ed8afb67
1 /* seq - print sequence of numbers to standard output.
2 Copyright (C) 1994-2016 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Ulrich Drepper. */
19 #include <config.h>
20 #include <getopt.h>
21 #include <stdio.h>
22 #include <sys/types.h>
24 #include "system.h"
25 #include "c-strtod.h"
26 #include "error.h"
27 #include "quote.h"
28 #include "xstrtod.h"
30 /* Roll our own isfinite rather than using <math.h>, so that we don't
31 have to worry about linking -lm just for isfinite. */
32 #ifndef isfinite
33 # define isfinite(x) ((x) * 0 == 0)
34 #endif
36 /* The official name of this program (e.g., no 'g' prefix). */
37 #define PROGRAM_NAME "seq"
39 #define AUTHORS proper_name ("Ulrich Drepper")
41 /* If true print all number with equal width. */
42 static bool equal_width;
44 /* The string used to separate two numbers. */
45 static char const *separator;
47 /* The string output after all numbers have been output.
48 Usually "\n" or "\0". */
49 static char const terminator[] = "\n";
51 static struct option const long_options[] =
53 { "equal-width", no_argument, NULL, 'w'},
54 { "format", required_argument, NULL, 'f'},
55 { "separator", required_argument, NULL, 's'},
56 {GETOPT_HELP_OPTION_DECL},
57 {GETOPT_VERSION_OPTION_DECL},
58 { NULL, 0, NULL, 0}
61 void
62 usage (int status)
64 if (status != EXIT_SUCCESS)
65 emit_try_help ();
66 else
68 printf (_("\
69 Usage: %s [OPTION]... LAST\n\
70 or: %s [OPTION]... FIRST LAST\n\
71 or: %s [OPTION]... FIRST INCREMENT LAST\n\
72 "), program_name, program_name, program_name);
73 fputs (_("\
74 Print numbers from FIRST to LAST, in steps of INCREMENT.\n\
75 "), stdout);
77 emit_mandatory_arg_note ();
79 fputs (_("\
80 -f, --format=FORMAT use printf style floating-point FORMAT\n\
81 -s, --separator=STRING use STRING to separate numbers (default: \\n)\n\
82 -w, --equal-width equalize width by padding with leading zeroes\n\
83 "), stdout);
84 fputs (HELP_OPTION_DESCRIPTION, stdout);
85 fputs (VERSION_OPTION_DESCRIPTION, stdout);
86 fputs (_("\
87 \n\
88 If FIRST or INCREMENT is omitted, it defaults to 1. That is, an\n\
89 omitted INCREMENT defaults to 1 even when LAST is smaller than FIRST.\n\
90 The sequence of numbers ends when the sum of the current number and\n\
91 INCREMENT would become greater than LAST.\n\
92 FIRST, INCREMENT, and LAST are interpreted as floating point values.\n\
93 INCREMENT is usually positive if FIRST is smaller than LAST, and\n\
94 INCREMENT is usually negative if FIRST is greater than LAST.\n\
95 "), stdout);
96 fputs (_("\
97 FORMAT must be suitable for printing one argument of type 'double';\n\
98 it defaults to %.PRECf if FIRST, INCREMENT, and LAST are all fixed point\n\
99 decimal numbers with maximum precision PREC, and to %g otherwise.\n\
100 "), stdout);
101 emit_ancillary_info (PROGRAM_NAME);
103 exit (status);
106 /* A command-line operand. */
107 struct operand
109 /* Its value, converted to 'long double'. */
110 long double value;
112 /* Its print width, if it were printed out in a form similar to its
113 input form. An input like "-.1" is treated like "-0.1", and an
114 input like "1." is treated like "1", but otherwise widths are
115 left alone. */
116 size_t width;
118 /* Number of digits after the decimal point, or INT_MAX if the
119 number can't easily be expressed as a fixed-point number. */
120 int precision;
122 typedef struct operand operand;
124 /* Description of what a number-generating format will generate. */
125 struct layout
127 /* Number of bytes before and after the number. */
128 size_t prefix_len;
129 size_t suffix_len;
132 /* Read a long double value from the command line.
133 Return if the string is correct else signal error. */
135 static operand
136 scan_arg (const char *arg)
138 operand ret;
140 if (! xstrtold (arg, NULL, &ret.value, c_strtold))
142 error (0, 0, _("invalid floating point argument: %s"), quote (arg));
143 usage (EXIT_FAILURE);
146 /* We don't output spaces or '+' so don't include in width */
147 while (isspace (to_uchar (*arg)) || *arg == '+')
148 arg++;
150 /* Default to auto width and precision. */
151 ret.width = 0;
152 ret.precision = INT_MAX;
154 /* Use no precision (and possibly fast generation) for integers. */
155 char const *decimal_point = strchr (arg, '.');
156 if (! decimal_point && ! strchr (arg, 'p') /* not a hex float */)
157 ret.precision = 0;
159 /* auto set width and precision for decimal inputs. */
160 if (! arg[strcspn (arg, "xX")] && isfinite (ret.value))
162 size_t fraction_len = 0;
163 ret.width = strlen (arg);
165 if (decimal_point)
167 fraction_len = strcspn (decimal_point + 1, "eE");
168 if (fraction_len <= INT_MAX)
169 ret.precision = fraction_len;
170 ret.width += (fraction_len == 0 /* #. -> # */
171 ? -1
172 : (decimal_point == arg /* .# -> 0.# */
173 || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */
175 char const *e = strchr (arg, 'e');
176 if (! e)
177 e = strchr (arg, 'E');
178 if (e)
180 long exponent = strtol (e + 1, NULL, 10);
181 ret.precision += exponent < 0 ? -exponent
182 : - MIN (ret.precision, exponent);
183 /* Don't account for e.... in the width since this is not output. */
184 ret.width -= strlen (arg) - (e - arg);
185 /* Adjust the width as per the exponent. */
186 if (exponent < 0)
188 if (decimal_point)
190 if (e == decimal_point + 1) /* undo #. -> # above */
191 ret.width++;
193 else
194 ret.width++;
195 exponent = -exponent;
197 else
199 if (decimal_point && ret.precision == 0 && fraction_len)
200 ret.width--; /* discount space for '.' */
201 exponent -= MIN (fraction_len, exponent);
203 ret.width += exponent;
207 return ret;
210 /* If FORMAT is a valid printf format for a double argument, return
211 its long double equivalent, allocated from dynamic storage, and
212 store into *LAYOUT a description of the output layout; otherwise,
213 report an error and exit. */
215 static char const *
216 long_double_format (char const *fmt, struct layout *layout)
218 size_t i;
219 size_t prefix_len = 0;
220 size_t suffix_len = 0;
221 size_t length_modifier_offset;
222 bool has_L;
224 for (i = 0; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
226 if (!fmt[i])
227 error (EXIT_FAILURE, 0,
228 _("format %s has no %% directive"), quote (fmt));
229 prefix_len++;
232 i++;
233 i += strspn (fmt + i, "-+#0 '");
234 i += strspn (fmt + i, "0123456789");
235 if (fmt[i] == '.')
237 i++;
238 i += strspn (fmt + i, "0123456789");
241 length_modifier_offset = i;
242 has_L = (fmt[i] == 'L');
243 i += has_L;
244 if (fmt[i] == '\0')
245 error (EXIT_FAILURE, 0, _("format %s ends in %%"), quote (fmt));
246 if (! strchr ("efgaEFGA", fmt[i]))
247 error (EXIT_FAILURE, 0,
248 _("format %s has unknown %%%c directive"), quote (fmt), fmt[i]);
250 for (i++; ; i += (fmt[i] == '%') + 1)
251 if (fmt[i] == '%' && fmt[i + 1] != '%')
252 error (EXIT_FAILURE, 0, _("format %s has too many %% directives"),
253 quote (fmt));
254 else if (fmt[i])
255 suffix_len++;
256 else
258 size_t format_size = i + 1;
259 char *ldfmt = xmalloc (format_size + 1);
260 memcpy (ldfmt, fmt, length_modifier_offset);
261 ldfmt[length_modifier_offset] = 'L';
262 strcpy (ldfmt + length_modifier_offset + 1,
263 fmt + length_modifier_offset + has_L);
264 layout->prefix_len = prefix_len;
265 layout->suffix_len = suffix_len;
266 return ldfmt;
270 /* Actually print the sequence of numbers in the specified range, with the
271 given or default stepping and format. */
273 static void
274 print_numbers (char const *fmt, struct layout layout,
275 long double first, long double step, long double last)
277 bool out_of_range = (step < 0 ? first < last : last < first);
279 if (! out_of_range)
281 long double x = first;
282 long double i;
284 for (i = 1; ; i++)
286 long double x0 = x;
287 printf (fmt, x);
288 if (out_of_range)
289 break;
290 x = first + i * step;
291 out_of_range = (step < 0 ? x < last : last < x);
293 if (out_of_range)
295 /* If the number just past LAST prints as a value equal
296 to LAST, and prints differently from the previous
297 number, then print the number. This avoids problems
298 with rounding. For example, with the x86 it causes
299 "seq 0 0.000001 0.000003" to print 0.000003 instead
300 of stopping at 0.000002. */
302 bool print_extra_number = false;
303 long double x_val;
304 char *x_str;
305 int x_strlen;
306 setlocale (LC_NUMERIC, "C");
307 x_strlen = asprintf (&x_str, fmt, x);
308 setlocale (LC_NUMERIC, "");
309 if (x_strlen < 0)
310 xalloc_die ();
311 x_str[x_strlen - layout.suffix_len] = '\0';
313 if (xstrtold (x_str + layout.prefix_len, NULL, &x_val, c_strtold)
314 && x_val == last)
316 char *x0_str = NULL;
317 if (asprintf (&x0_str, fmt, x0) < 0)
318 xalloc_die ();
319 print_extra_number = !STREQ (x0_str, x_str);
320 free (x0_str);
323 free (x_str);
324 if (! print_extra_number)
325 break;
328 fputs (separator, stdout);
331 fputs (terminator, stdout);
335 /* Return the default format given FIRST, STEP, and LAST. */
336 static char const *
337 get_default_format (operand first, operand step, operand last)
339 static char format_buf[sizeof "%0.Lf" + 2 * INT_STRLEN_BOUND (int)];
341 int prec = MAX (first.precision, step.precision);
343 if (prec != INT_MAX && last.precision != INT_MAX)
345 if (equal_width)
347 /* increase first_width by any increased precision in step */
348 size_t first_width = first.width + (prec - first.precision);
349 /* adjust last_width to use precision from first/step */
350 size_t last_width = last.width + (prec - last.precision);
351 if (last.precision && prec == 0)
352 last_width--; /* don't include space for '.' */
353 if (last.precision == 0 && prec)
354 last_width++; /* include space for '.' */
355 if (first.precision == 0 && prec)
356 first_width++; /* include space for '.' */
357 size_t width = MAX (first_width, last_width);
358 if (width <= INT_MAX)
360 int w = width;
361 sprintf (format_buf, "%%0%d.%dLf", w, prec);
362 return format_buf;
365 else
367 sprintf (format_buf, "%%.%dLf", prec);
368 return format_buf;
372 return "%Lg";
375 /* The NUL-terminated string S0 of length S_LEN represents a valid
376 non-negative decimal integer. Adjust the string and length so
377 that the pair describe the next-larger value. */
378 static void
379 incr (char **s0, size_t *s_len)
381 char *s = *s0;
382 char *endp = s + *s_len - 1;
386 if ((*endp)++ < '9')
387 return;
388 *endp-- = '0';
390 while (endp >= s);
391 *--(*s0) = '1';
392 ++*s_len;
395 /* Compare A and B (each a NUL-terminated digit string), with lengths
396 given by A_LEN and B_LEN. Return +1 if A < B, -1 if B < A, else 0. */
397 static int
398 cmp (char const *a, size_t a_len, char const *b, size_t b_len)
400 if (a_len < b_len)
401 return -1;
402 if (b_len < a_len)
403 return 1;
404 return (strcmp (a, b));
407 /* Trim leading 0's from S, but if S is all 0's, leave one.
408 Return a pointer to the trimmed string. */
409 static char const * _GL_ATTRIBUTE_PURE
410 trim_leading_zeros (char const *s)
412 char const *p = s;
413 while (*s == '0')
414 ++s;
416 /* If there were only 0's, back up, to leave one. */
417 if (!*s && s != p)
418 --s;
419 return s;
422 /* Print all whole numbers from A to B, inclusive -- to stdout, each
423 followed by a newline. If B < A, return false and print nothing.
424 Otherwise, return true. */
425 static bool
426 seq_fast (char const *a, char const *b)
428 bool inf = STREQ (b, "inf");
430 /* Skip past any leading 0's. Without this, our naive cmp
431 function would declare 000 to be larger than 99. */
432 a = trim_leading_zeros (a);
433 b = trim_leading_zeros (b);
435 size_t p_len = strlen (a);
436 size_t q_len = inf ? 0 : strlen (b);
438 /* Allow for at least 31 digits without realloc.
439 1 more than p_len is needed for the inf case. */
440 size_t inc_size = MAX (MAX (p_len + 1, q_len), 31);
442 /* Copy input strings (incl NUL) to end of new buffers. */
443 char *p0 = xmalloc (inc_size + 1);
444 char *p = memcpy (p0 + inc_size - p_len, a, p_len + 1);
445 char *q;
446 char *q0;
447 if (! inf)
449 q0 = xmalloc (inc_size + 1);
450 q = memcpy (q0 + inc_size - q_len, b, q_len + 1);
452 else
453 q = q0 = NULL;
455 bool ok = inf || cmp (p, p_len, q, q_len) <= 0;
456 if (ok)
458 /* Reduce number of fwrite calls which is seen to
459 give a speed-up of more than 2x over the unbuffered code
460 when printing the first 10^9 integers. */
461 size_t buf_size = MAX (BUFSIZ, (inc_size + 1) * 2);
462 char *buf = xmalloc (buf_size);
463 char const *buf_end = buf + buf_size;
465 char *bufp = buf;
467 /* Write first number to buffer. */
468 bufp = mempcpy (bufp, p, p_len);
470 /* Append separator then number. */
471 while (inf || cmp (p, p_len, q, q_len) < 0)
473 *bufp++ = *separator;
474 incr (&p, &p_len);
476 /* Double up the buffers when needed for the inf case. */
477 if (p_len == inc_size)
479 inc_size *= 2;
480 p0 = xrealloc (p0, inc_size + 1);
481 p = memmove (p0 + p_len, p0, p_len + 1);
483 if (buf_size < (inc_size + 1) * 2)
485 size_t buf_offset = bufp - buf;
486 buf_size = (inc_size + 1) * 2;
487 buf = xrealloc (buf, buf_size);
488 buf_end = buf + buf_size;
489 bufp = buf + buf_offset;
493 bufp = mempcpy (bufp, p, p_len);
494 /* If no place for another separator + number then
495 output buffer so far, and reset to start of buffer. */
496 if (buf_end - (p_len + 1) < bufp)
498 fwrite (buf, bufp - buf, 1, stdout);
499 bufp = buf;
503 /* Write any remaining buffered output, and the terminator. */
504 *bufp++ = *terminator;
505 fwrite (buf, bufp - buf, 1, stdout);
507 IF_LINT (free (buf));
510 free (p0);
511 free (q0);
512 return ok;
515 /* Return true if S consists of at least one digit and no non-digits. */
516 static bool _GL_ATTRIBUTE_PURE
517 all_digits_p (char const *s)
519 size_t n = strlen (s);
520 return ISDIGIT (s[0]) && n == strspn (s, "0123456789");
524 main (int argc, char **argv)
526 int optc;
527 operand first = { 1, 1, 0 };
528 operand step = { 1, 1, 0 };
529 operand last;
530 struct layout layout = { 0, 0 };
532 /* The printf(3) format used for output. */
533 char const *format_str = NULL;
535 initialize_main (&argc, &argv);
536 set_program_name (argv[0]);
537 setlocale (LC_ALL, "");
538 bindtextdomain (PACKAGE, LOCALEDIR);
539 textdomain (PACKAGE);
541 atexit (close_stdout);
543 equal_width = false;
544 separator = "\n";
546 /* We have to handle negative numbers in the command line but this
547 conflicts with the command line arguments. So explicitly check first
548 whether the next argument looks like a negative number. */
549 while (optind < argc)
551 if (argv[optind][0] == '-'
552 && ((optc = argv[optind][1]) == '.' || ISDIGIT (optc)))
554 /* means negative number */
555 break;
558 optc = getopt_long (argc, argv, "+f:s:w", long_options, NULL);
559 if (optc == -1)
560 break;
562 switch (optc)
564 case 'f':
565 format_str = optarg;
566 break;
568 case 's':
569 separator = optarg;
570 break;
572 case 'w':
573 equal_width = true;
574 break;
576 case_GETOPT_HELP_CHAR;
578 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
580 default:
581 usage (EXIT_FAILURE);
585 unsigned int n_args = argc - optind;
586 if (n_args < 1)
588 error (0, 0, _("missing operand"));
589 usage (EXIT_FAILURE);
592 if (3 < n_args)
594 error (0, 0, _("extra operand %s"), quote (argv[optind + 3]));
595 usage (EXIT_FAILURE);
598 if (format_str)
599 format_str = long_double_format (format_str, &layout);
601 if (format_str != NULL && equal_width)
603 error (0, 0, _("format string may not be specified"
604 " when printing equal width strings"));
605 usage (EXIT_FAILURE);
608 /* If the following hold:
609 - no format string, [FIXME: relax this, eventually]
610 - integer start (or no start)
611 - integer end
612 - increment == 1 or not specified [FIXME: relax this, eventually]
613 then use the much more efficient integer-only code. */
614 if (all_digits_p (argv[optind])
615 && (n_args == 1 || all_digits_p (argv[optind + 1]))
616 && (n_args < 3 || (STREQ ("1", argv[optind + 1])
617 && all_digits_p (argv[optind + 2])))
618 && !equal_width && !format_str && strlen (separator) == 1)
620 char const *s1 = n_args == 1 ? "1" : argv[optind];
621 char const *s2 = argv[optind + (n_args - 1)];
622 if (seq_fast (s1, s2))
623 return EXIT_SUCCESS;
625 /* Upon any failure, let the more general code deal with it. */
628 last = scan_arg (argv[optind++]);
630 if (optind < argc)
632 first = last;
633 last = scan_arg (argv[optind++]);
635 if (optind < argc)
637 step = last;
638 last = scan_arg (argv[optind++]);
642 if ((isfinite (first.value) && first.precision == 0)
643 && step.precision == 0 && last.precision == 0
644 && 0 <= first.value && step.value == 1 && 0 <= last.value
645 && !equal_width && !format_str && strlen (separator) == 1)
647 char *s1;
648 char *s2;
649 if (asprintf (&s1, "%0.Lf", first.value) < 0)
650 xalloc_die ();
651 if (! isfinite (last.value))
652 s2 = xstrdup ("inf"); /* Ensure "inf" is used. */
653 else if (asprintf (&s2, "%0.Lf", last.value) < 0)
654 xalloc_die ();
656 if (*s1 != '-' && *s2 != '-' && seq_fast (s1, s2))
658 IF_LINT (free (s1));
659 IF_LINT (free (s2));
660 return EXIT_SUCCESS;
663 free (s1);
664 free (s2);
665 /* Upon any failure, let the more general code deal with it. */
668 if (format_str == NULL)
669 format_str = get_default_format (first, step, last);
671 print_numbers (format_str, layout, first.value, step.value, last.value);
673 return EXIT_SUCCESS;