1 /* seq - print sequence of numbers to standard output.
2 Copyright (C) 1994-2017 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 <https://www.gnu.org/licenses/>. */
17 /* Written by Ulrich Drepper. */
22 #include <sys/types.h>
31 /* Roll our own isfinite/isnan rather than using <math.h>, so that we don't
32 have to worry about linking -lm just for isfinite. */
34 # define isfinite(x) ((x) * 0 == 0)
37 # define isnan(x) ((x) != (x))
40 /* The official name of this program (e.g., no 'g' prefix). */
41 #define PROGRAM_NAME "seq"
43 #define AUTHORS proper_name ("Ulrich Drepper")
45 /* If true print all number with equal width. */
46 static bool equal_width
;
48 /* The string used to separate two numbers. */
49 static char const *separator
;
51 /* The string output after all numbers have been output.
52 Usually "\n" or "\0". */
53 static char const terminator
[] = "\n";
55 static struct option
const long_options
[] =
57 { "equal-width", no_argument
, NULL
, 'w'},
58 { "format", required_argument
, NULL
, 'f'},
59 { "separator", required_argument
, NULL
, 's'},
60 {GETOPT_HELP_OPTION_DECL
},
61 {GETOPT_VERSION_OPTION_DECL
},
68 if (status
!= EXIT_SUCCESS
)
73 Usage: %s [OPTION]... LAST\n\
74 or: %s [OPTION]... FIRST LAST\n\
75 or: %s [OPTION]... FIRST INCREMENT LAST\n\
76 "), program_name
, program_name
, program_name
);
78 Print numbers from FIRST to LAST, in steps of INCREMENT.\n\
81 emit_mandatory_arg_note ();
84 -f, --format=FORMAT use printf style floating-point FORMAT\n\
85 -s, --separator=STRING use STRING to separate numbers (default: \\n)\n\
86 -w, --equal-width equalize width by padding with leading zeroes\n\
88 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
89 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
92 If FIRST or INCREMENT is omitted, it defaults to 1. That is, an\n\
93 omitted INCREMENT defaults to 1 even when LAST is smaller than FIRST.\n\
94 The sequence of numbers ends when the sum of the current number and\n\
95 INCREMENT would become greater than LAST.\n\
96 FIRST, INCREMENT, and LAST are interpreted as floating point values.\n\
97 INCREMENT is usually positive if FIRST is smaller than LAST, and\n\
98 INCREMENT is usually negative if FIRST is greater than LAST.\n\
99 INCREMENT must not be 0; none of FIRST, INCREMENT and LAST may be NaN.\n\
102 FORMAT must be suitable for printing one argument of type 'double';\n\
103 it defaults to %.PRECf if FIRST, INCREMENT, and LAST are all fixed point\n\
104 decimal numbers with maximum precision PREC, and to %g otherwise.\n\
106 emit_ancillary_info (PROGRAM_NAME
);
111 /* A command-line operand. */
114 /* Its value, converted to 'long double'. */
117 /* Its print width, if it were printed out in a form similar to its
118 input form. An input like "-.1" is treated like "-0.1", and an
119 input like "1." is treated like "1", but otherwise widths are
123 /* Number of digits after the decimal point, or INT_MAX if the
124 number can't easily be expressed as a fixed-point number. */
127 typedef struct operand operand
;
129 /* Description of what a number-generating format will generate. */
132 /* Number of bytes before and after the number. */
137 /* Read a long double value from the command line.
138 Return if the string is correct else signal error. */
141 scan_arg (const char *arg
)
145 if (! xstrtold (arg
, NULL
, &ret
.value
, c_strtold
))
147 error (0, 0, _("invalid floating point argument: %s"), quote (arg
));
148 usage (EXIT_FAILURE
);
151 if (isnan (ret
.value
))
153 error (0, 0, _("invalid %s argument: %s"), quote_n (0, "not-a-number"),
155 usage (EXIT_FAILURE
);
158 /* We don't output spaces or '+' so don't include in width */
159 while (isspace (to_uchar (*arg
)) || *arg
== '+')
162 /* Default to auto width and precision. */
164 ret
.precision
= INT_MAX
;
166 /* Use no precision (and possibly fast generation) for integers. */
167 char const *decimal_point
= strchr (arg
, '.');
168 if (! decimal_point
&& ! strchr (arg
, 'p') /* not a hex float */)
171 /* auto set width and precision for decimal inputs. */
172 if (! arg
[strcspn (arg
, "xX")] && isfinite (ret
.value
))
174 size_t fraction_len
= 0;
175 ret
.width
= strlen (arg
);
179 fraction_len
= strcspn (decimal_point
+ 1, "eE");
180 if (fraction_len
<= INT_MAX
)
181 ret
.precision
= fraction_len
;
182 ret
.width
+= (fraction_len
== 0 /* #. -> # */
184 : (decimal_point
== arg
/* .# -> 0.# */
185 || ! ISDIGIT (decimal_point
[-1]))); /* -.# -> 0.# */
187 char const *e
= strchr (arg
, 'e');
189 e
= strchr (arg
, 'E');
192 long exponent
= strtol (e
+ 1, NULL
, 10);
193 ret
.precision
+= exponent
< 0 ? -exponent
194 : - MIN (ret
.precision
, exponent
);
195 /* Don't account for e.... in the width since this is not output. */
196 ret
.width
-= strlen (arg
) - (e
- arg
);
197 /* Adjust the width as per the exponent. */
202 if (e
== decimal_point
+ 1) /* undo #. -> # above */
207 exponent
= -exponent
;
211 if (decimal_point
&& ret
.precision
== 0 && fraction_len
)
212 ret
.width
--; /* discount space for '.' */
213 exponent
-= MIN (fraction_len
, exponent
);
215 ret
.width
+= exponent
;
222 /* If FORMAT is a valid printf format for a double argument, return
223 its long double equivalent, allocated from dynamic storage, and
224 store into *LAYOUT a description of the output layout; otherwise,
225 report an error and exit. */
228 long_double_format (char const *fmt
, struct layout
*layout
)
231 size_t prefix_len
= 0;
232 size_t suffix_len
= 0;
233 size_t length_modifier_offset
;
236 for (i
= 0; ! (fmt
[i
] == '%' && fmt
[i
+ 1] != '%'); i
+= (fmt
[i
] == '%') + 1)
239 die (EXIT_FAILURE
, 0,
240 _("format %s has no %% directive"), quote (fmt
));
245 i
+= strspn (fmt
+ i
, "-+#0 '");
246 i
+= strspn (fmt
+ i
, "0123456789");
250 i
+= strspn (fmt
+ i
, "0123456789");
253 length_modifier_offset
= i
;
254 has_L
= (fmt
[i
] == 'L');
257 die (EXIT_FAILURE
, 0, _("format %s ends in %%"), quote (fmt
));
258 if (! strchr ("efgaEFGA", fmt
[i
]))
259 die (EXIT_FAILURE
, 0,
260 _("format %s has unknown %%%c directive"), quote (fmt
), fmt
[i
]);
262 for (i
++; ; i
+= (fmt
[i
] == '%') + 1)
263 if (fmt
[i
] == '%' && fmt
[i
+ 1] != '%')
264 die (EXIT_FAILURE
, 0, _("format %s has too many %% directives"),
270 size_t format_size
= i
+ 1;
271 char *ldfmt
= xmalloc (format_size
+ 1);
272 memcpy (ldfmt
, fmt
, length_modifier_offset
);
273 ldfmt
[length_modifier_offset
] = 'L';
274 strcpy (ldfmt
+ length_modifier_offset
+ 1,
275 fmt
+ length_modifier_offset
+ has_L
);
276 layout
->prefix_len
= prefix_len
;
277 layout
->suffix_len
= suffix_len
;
282 static void ATTRIBUTE_NORETURN
285 /* FIXME: consider option to silently ignore errno=EPIPE */
287 die (EXIT_FAILURE
, errno
, _("write error"));
290 /* Actually print the sequence of numbers in the specified range, with the
291 given or default stepping and format. */
294 print_numbers (char const *fmt
, struct layout layout
,
295 long double first
, long double step
, long double last
)
297 bool out_of_range
= (step
< 0 ? first
< last
: last
< first
);
301 long double x
= first
;
307 if (printf (fmt
, x
) < 0)
311 x
= first
+ i
* step
;
312 out_of_range
= (step
< 0 ? x
< last
: last
< x
);
316 /* If the number just past LAST prints as a value equal
317 to LAST, and prints differently from the previous
318 number, then print the number. This avoids problems
319 with rounding. For example, with the x86 it causes
320 "seq 0 0.000001 0.000003" to print 0.000003 instead
321 of stopping at 0.000002. */
323 bool print_extra_number
= false;
327 setlocale (LC_NUMERIC
, "C");
328 x_strlen
= asprintf (&x_str
, fmt
, x
);
329 setlocale (LC_NUMERIC
, "");
332 x_str
[x_strlen
- layout
.suffix_len
] = '\0';
334 if (xstrtold (x_str
+ layout
.prefix_len
, NULL
, &x_val
, c_strtold
)
338 if (asprintf (&x0_str
, fmt
, x0
) < 0)
340 print_extra_number
= !STREQ (x0_str
, x_str
);
345 if (! print_extra_number
)
349 if (fputs (separator
, stdout
) == EOF
)
353 if (fputs (terminator
, stdout
) == EOF
)
358 /* Return the default format given FIRST, STEP, and LAST. */
360 get_default_format (operand first
, operand step
, operand last
)
362 static char format_buf
[sizeof "%0.Lf" + 2 * INT_STRLEN_BOUND (int)];
364 int prec
= MAX (first
.precision
, step
.precision
);
366 if (prec
!= INT_MAX
&& last
.precision
!= INT_MAX
)
370 /* increase first_width by any increased precision in step */
371 size_t first_width
= first
.width
+ (prec
- first
.precision
);
372 /* adjust last_width to use precision from first/step */
373 size_t last_width
= last
.width
+ (prec
- last
.precision
);
374 if (last
.precision
&& prec
== 0)
375 last_width
--; /* don't include space for '.' */
376 if (last
.precision
== 0 && prec
)
377 last_width
++; /* include space for '.' */
378 if (first
.precision
== 0 && prec
)
379 first_width
++; /* include space for '.' */
380 size_t width
= MAX (first_width
, last_width
);
381 if (width
<= INT_MAX
)
384 sprintf (format_buf
, "%%0%d.%dLf", w
, prec
);
390 sprintf (format_buf
, "%%.%dLf", prec
);
398 /* The NUL-terminated string S0 of length S_LEN represents a valid
399 non-negative decimal integer. Adjust the string and length so
400 that the pair describe the next-larger value. */
402 incr (char **s0
, size_t *s_len
)
405 char *endp
= s
+ *s_len
- 1;
418 /* Compare A and B (each a NUL-terminated digit string), with lengths
419 given by A_LEN and B_LEN. Return +1 if A < B, -1 if B < A, else 0. */
421 cmp (char const *a
, size_t a_len
, char const *b
, size_t b_len
)
427 return (strcmp (a
, b
));
430 /* Trim leading 0's from S, but if S is all 0's, leave one.
431 Return a pointer to the trimmed string. */
432 static char const * _GL_ATTRIBUTE_PURE
433 trim_leading_zeros (char const *s
)
439 /* If there were only 0's, back up, to leave one. */
445 /* Print all whole numbers from A to B, inclusive -- to stdout, each
446 followed by a newline. If B < A, return false and print nothing.
447 Otherwise, return true. */
449 seq_fast (char const *a
, char const *b
)
451 bool inf
= STREQ (b
, "inf");
453 /* Skip past any leading 0's. Without this, our naive cmp
454 function would declare 000 to be larger than 99. */
455 a
= trim_leading_zeros (a
);
456 b
= trim_leading_zeros (b
);
458 size_t p_len
= strlen (a
);
459 size_t q_len
= inf
? 0 : strlen (b
);
461 /* Allow for at least 31 digits without realloc.
462 1 more than p_len is needed for the inf case. */
463 size_t inc_size
= MAX (MAX (p_len
+ 1, q_len
), 31);
465 /* Copy input strings (incl NUL) to end of new buffers. */
466 char *p0
= xmalloc (inc_size
+ 1);
467 char *p
= memcpy (p0
+ inc_size
- p_len
, a
, p_len
+ 1);
472 q0
= xmalloc (inc_size
+ 1);
473 q
= memcpy (q0
+ inc_size
- q_len
, b
, q_len
+ 1);
478 bool ok
= inf
|| cmp (p
, p_len
, q
, q_len
) <= 0;
481 /* Reduce number of fwrite calls which is seen to
482 give a speed-up of more than 2x over the unbuffered code
483 when printing the first 10^9 integers. */
484 size_t buf_size
= MAX (BUFSIZ
, (inc_size
+ 1) * 2);
485 char *buf
= xmalloc (buf_size
);
486 char const *buf_end
= buf
+ buf_size
;
490 /* Write first number to buffer. */
491 bufp
= mempcpy (bufp
, p
, p_len
);
493 /* Append separator then number. */
494 while (inf
|| cmp (p
, p_len
, q
, q_len
) < 0)
496 *bufp
++ = *separator
;
499 /* Double up the buffers when needed for the inf case. */
500 if (p_len
== inc_size
)
503 p0
= xrealloc (p0
, inc_size
+ 1);
504 p
= memmove (p0
+ p_len
, p0
, p_len
+ 1);
506 if (buf_size
< (inc_size
+ 1) * 2)
508 size_t buf_offset
= bufp
- buf
;
509 buf_size
= (inc_size
+ 1) * 2;
510 buf
= xrealloc (buf
, buf_size
);
511 buf_end
= buf
+ buf_size
;
512 bufp
= buf
+ buf_offset
;
516 bufp
= mempcpy (bufp
, p
, p_len
);
517 /* If no place for another separator + number then
518 output buffer so far, and reset to start of buffer. */
519 if (buf_end
- (p_len
+ 1) < bufp
)
521 if (fwrite (buf
, bufp
- buf
, 1, stdout
) != 1)
527 /* Write any remaining buffered output, and the terminator. */
528 *bufp
++ = *terminator
;
529 if (fwrite (buf
, bufp
- buf
, 1, stdout
) != 1)
532 IF_LINT (free (buf
));
540 /* Return true if S consists of at least one digit and no non-digits. */
541 static bool _GL_ATTRIBUTE_PURE
542 all_digits_p (char const *s
)
544 size_t n
= strlen (s
);
545 return ISDIGIT (s
[0]) && n
== strspn (s
, "0123456789");
549 main (int argc
, char **argv
)
552 operand first
= { 1, 1, 0 };
553 operand step
= { 1, 1, 0 };
555 struct layout layout
= { 0, 0 };
557 /* The printf(3) format used for output. */
558 char const *format_str
= NULL
;
560 initialize_main (&argc
, &argv
);
561 set_program_name (argv
[0]);
562 setlocale (LC_ALL
, "");
563 bindtextdomain (PACKAGE
, LOCALEDIR
);
564 textdomain (PACKAGE
);
566 atexit (close_stdout
);
571 /* We have to handle negative numbers in the command line but this
572 conflicts with the command line arguments. So explicitly check first
573 whether the next argument looks like a negative number. */
574 while (optind
< argc
)
576 if (argv
[optind
][0] == '-'
577 && ((optc
= argv
[optind
][1]) == '.' || ISDIGIT (optc
)))
579 /* means negative number */
583 optc
= getopt_long (argc
, argv
, "+f:s:w", long_options
, NULL
);
601 case_GETOPT_HELP_CHAR
;
603 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
606 usage (EXIT_FAILURE
);
610 unsigned int n_args
= argc
- optind
;
613 error (0, 0, _("missing operand"));
614 usage (EXIT_FAILURE
);
619 error (0, 0, _("extra operand %s"), quote (argv
[optind
+ 3]));
620 usage (EXIT_FAILURE
);
624 format_str
= long_double_format (format_str
, &layout
);
626 if (format_str
!= NULL
&& equal_width
)
628 error (0, 0, _("format string may not be specified"
629 " when printing equal width strings"));
630 usage (EXIT_FAILURE
);
633 /* If the following hold:
634 - no format string, [FIXME: relax this, eventually]
635 - integer start (or no start)
637 - increment == 1 or not specified [FIXME: relax this, eventually]
638 then use the much more efficient integer-only code. */
639 if (all_digits_p (argv
[optind
])
640 && (n_args
== 1 || all_digits_p (argv
[optind
+ 1]))
641 && (n_args
< 3 || (STREQ ("1", argv
[optind
+ 1])
642 && all_digits_p (argv
[optind
+ 2])))
643 && !equal_width
&& !format_str
&& strlen (separator
) == 1)
645 char const *s1
= n_args
== 1 ? "1" : argv
[optind
];
646 char const *s2
= argv
[optind
+ (n_args
- 1)];
647 if (seq_fast (s1
, s2
))
650 /* Upon any failure, let the more general code deal with it. */
653 last
= scan_arg (argv
[optind
++]);
658 last
= scan_arg (argv
[optind
++]);
665 error (0, 0, _("invalid Zero increment value: %s"),
666 quote (argv
[optind
-1]));
667 usage (EXIT_FAILURE
);
670 last
= scan_arg (argv
[optind
++]);
674 if ((isfinite (first
.value
) && first
.precision
== 0)
675 && step
.precision
== 0 && last
.precision
== 0
676 && 0 <= first
.value
&& step
.value
== 1 && 0 <= last
.value
677 && !equal_width
&& !format_str
&& strlen (separator
) == 1)
681 if (asprintf (&s1
, "%0.Lf", first
.value
) < 0)
683 if (! isfinite (last
.value
))
684 s2
= xstrdup ("inf"); /* Ensure "inf" is used. */
685 else if (asprintf (&s2
, "%0.Lf", last
.value
) < 0)
688 if (*s1
!= '-' && *s2
!= '-' && seq_fast (s1
, s2
))
697 /* Upon any failure, let the more general code deal with it. */
700 if (format_str
== NULL
)
701 format_str
= get_default_format (first
, step
, last
);
703 print_numbers (format_str
, layout
, first
.value
, step
.value
, last
.value
);