seq: revert Solaris 8 work-around that caused x86 regression
[coreutils/bo.git] / src / seq.c
blob3ae158b08c7acb525cb3c140da2decee7cd314cc
1 /* seq - print sequence of numbers to standard output.
2 Copyright (C) 1994-2008 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 /* FIXME: make this an option. */
50 static char const terminator[] = "\n";
52 static struct option const long_options[] =
54 { "equal-width", no_argument, NULL, 'w'},
55 { "format", required_argument, NULL, 'f'},
56 { "separator", required_argument, NULL, 's'},
57 {GETOPT_HELP_OPTION_DECL},
58 {GETOPT_VERSION_OPTION_DECL},
59 { NULL, 0, NULL, 0}
62 void
63 usage (int status)
65 if (status != EXIT_SUCCESS)
66 fprintf (stderr, _("Try `%s --help' for more information.\n"),
67 program_name);
68 else
70 printf (_("\
71 Usage: %s [OPTION]... LAST\n\
72 or: %s [OPTION]... FIRST LAST\n\
73 or: %s [OPTION]... FIRST INCREMENT LAST\n\
74 "), program_name, program_name, program_name);
75 fputs (_("\
76 Print numbers from FIRST to LAST, in steps of INCREMENT.\n\
77 \n\
78 -f, --format=FORMAT use printf style floating-point FORMAT\n\
79 -s, --separator=STRING use STRING to separate numbers (default: \\n)\n\
80 -w, --equal-width equalize width by padding with leading zeroes\n\
81 "), stdout);
82 fputs (HELP_OPTION_DESCRIPTION, stdout);
83 fputs (VERSION_OPTION_DESCRIPTION, stdout);
84 fputs (_("\
85 \n\
86 If FIRST or INCREMENT is omitted, it defaults to 1. That is, an\n\
87 omitted INCREMENT defaults to 1 even when LAST is smaller than FIRST.\n\
88 FIRST, INCREMENT, and LAST are interpreted as floating point values.\n\
89 INCREMENT is usually positive if FIRST is smaller than LAST, and\n\
90 INCREMENT is usually negative if FIRST is greater than LAST.\n\
91 "), stdout);
92 fputs (_("\
93 FORMAT must be suitable for printing one argument of type `double';\n\
94 it defaults to %.PRECf if FIRST, INCREMENT, and LAST are all fixed point\n\
95 decimal numbers with maximum precision PREC, and to %g otherwise.\n\
96 "), stdout);
97 emit_bug_reporting_address ();
99 exit (status);
102 /* A command-line operand. */
103 struct operand
105 /* Its value, converted to 'long double'. */
106 long double value;
108 /* Its print width, if it were printed out in a form similar to its
109 input form. An input like "-.1" is treated like "-0.1", and an
110 input like "1." is treated like "1", but otherwise widths are
111 left alone. */
112 size_t width;
114 /* Number of digits after the decimal point, or INT_MAX if the
115 number can't easily be expressed as a fixed-point number. */
116 int precision;
118 typedef struct operand operand;
120 /* Description of what a number-generating format will generate. */
121 struct layout
123 /* Number of bytes before and after the number. */
124 size_t prefix_len;
125 size_t suffix_len;
128 /* Read a long double value from the command line.
129 Return if the string is correct else signal error. */
131 static operand
132 scan_arg (const char *arg)
134 operand ret;
136 if (! xstrtold (arg, NULL, &ret.value, c_strtold))
138 error (0, 0, _("invalid floating point argument: %s"), arg);
139 usage (EXIT_FAILURE);
142 /* We don't output spaces or '+' so don't include in width */
143 while (isspace (to_uchar (*arg)) || *arg == '+')
144 arg++;
146 ret.width = strlen (arg);
147 ret.precision = INT_MAX;
149 if (! arg[strcspn (arg, "xX")] && isfinite (ret.value))
151 char const *decimal_point = strchr (arg, '.');
152 if (! decimal_point)
153 ret.precision = 0;
154 else
156 size_t fraction_len = strcspn (decimal_point + 1, "eE");
157 if (fraction_len <= INT_MAX)
158 ret.precision = fraction_len;
159 ret.width += (fraction_len == 0 /* #. -> # */
160 ? -1
161 : (decimal_point == arg /* .# -> 0.# */
162 || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */
164 char const *e = strchr (arg, 'e');
165 if (! e)
166 e = strchr (arg, 'E');
167 if (e)
169 long exponent = strtol (e + 1, NULL, 10);
170 ret.precision += exponent < 0 ? -exponent : 0;
174 return ret;
177 /* Validate the format, FMT. Print a diagnostic and exit
178 if there is not exactly one %-directive. */
180 static void
181 validate_format (char const *fmt)
183 unsigned int n_directives = 0;
184 char const *p;
186 for (p = fmt; *p; p++)
188 if (p[0] == '%' && p[1] != '%' && p[1] != '\0')
190 ++n_directives;
191 ++p;
194 if (n_directives == 0)
196 error (0, 0, _("no %% directive in format string %s"), quote (fmt));
197 usage (EXIT_FAILURE);
199 else if (1 < n_directives)
200 error (EXIT_FAILURE, 0, _("too many %% directives in format string %s"),
201 quote (fmt));
204 /* If FORMAT is a valid printf format for a double argument, return
205 its long double equivalent, possibly allocated from dynamic
206 storage, and store into *LAYOUT a description of the output layout;
207 otherwise, return NULL. */
209 static char const *
210 long_double_format (char const *fmt, struct layout *layout)
212 size_t i;
213 size_t prefix_len = 0;
214 size_t suffix_len = 0;
215 size_t length_modifier_offset;
216 bool has_L;
218 for (i = 0; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
219 if (fmt[i])
220 prefix_len++;
221 else
222 return NULL;
224 i++;
225 i += strspn (fmt + i, "-+#0 '");
226 i += strspn (fmt + i, "0123456789");
227 if (fmt[i] == '.')
229 i++;
230 i += strspn (fmt + i, "0123456789");
233 length_modifier_offset = i;
234 has_L = (fmt[i] == 'L');
235 i += has_L;
236 /* In a valid format string, fmt[i] must be one of these specifiers. */
237 if (fmt[i] == '\0' || ! strchr ("efgaEFGA", fmt[i]))
238 return NULL;
240 for (i++; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
241 if (fmt[i])
242 suffix_len++;
243 else
245 size_t format_size = i + 1;
246 char *ldfmt = xmalloc (format_size + 1);
247 memcpy (ldfmt, fmt, length_modifier_offset);
248 ldfmt[length_modifier_offset] = 'L';
249 strcpy (ldfmt + length_modifier_offset + 1,
250 fmt + length_modifier_offset + has_L);
251 layout->prefix_len = prefix_len;
252 layout->suffix_len = suffix_len;
253 return ldfmt;
256 return NULL;
259 /* Actually print the sequence of numbers in the specified range, with the
260 given or default stepping and format. */
262 static void
263 print_numbers (char const *fmt, struct layout layout,
264 long double first, long double step, long double last)
266 bool out_of_range = (step < 0 ? first < last : last < first);
268 if (! out_of_range)
270 long double x = first;
271 long double i;
273 for (i = 1; ; i++)
275 long double x0 = x;
276 printf (fmt, x);
277 if (out_of_range)
278 break;
279 x = first + i * step;
280 out_of_range = (step < 0 ? x < last : last < x);
282 if (out_of_range)
284 /* If the number just past LAST prints as a value equal
285 to LAST, and prints differently from the previous
286 number, then print the number. This avoids problems
287 with rounding. For example, with the x86 it causes
288 "seq 0 0.000001 0.000003" to print 0.000003 instead
289 of stopping at 0.000002. */
291 bool print_extra_number = false;
292 long double x_val;
293 char *x_str;
294 int x_strlen;
295 setlocale (LC_NUMERIC, "C");
296 x_strlen = asprintf (&x_str, fmt, x);
297 setlocale (LC_NUMERIC, "");
298 if (x_strlen < 0)
299 xalloc_die ();
300 x_str[x_strlen - layout.suffix_len] = '\0';
302 if (xstrtold (x_str + layout.prefix_len, NULL, &x_val, c_strtold)
303 && x_val == last)
305 char *x0_str = NULL;
306 if (asprintf (&x0_str, fmt, x0) < 0)
307 xalloc_die ();
308 print_extra_number = !STREQ (x0_str, x_str);
309 free (x0_str);
312 free (x_str);
313 if (! print_extra_number)
314 break;
317 fputs (separator, stdout);
320 fputs (terminator, stdout);
324 /* Return the default format given FIRST, STEP, and LAST. */
325 static char const *
326 get_default_format (operand first, operand step, operand last)
328 static char format_buf[sizeof "%0.Lf" + 2 * INT_STRLEN_BOUND (int)];
330 int prec = MAX (first.precision, step.precision);
332 if (prec != INT_MAX && last.precision != INT_MAX)
334 if (equal_width)
336 /* increase first_width by any increased precision in step */
337 size_t first_width = first.width + (prec - first.precision);
338 /* adjust last_width to use precision from first/step */
339 size_t last_width = last.width + (prec - last.precision);
340 if (last.precision && prec == 0)
341 last_width--; /* don't include space for '.' */
342 size_t width = MAX (first_width, last_width);
343 if (width <= INT_MAX)
345 int w = width;
346 sprintf (format_buf, "%%0%d.%dLf", w, prec);
347 return format_buf;
350 else
352 sprintf (format_buf, "%%.%dLf", prec);
353 return format_buf;
357 return "%Lg";
361 main (int argc, char **argv)
363 int optc;
364 operand first = { 1, 1, 0 };
365 operand step = { 1, 1, 0 };
366 operand last;
367 struct layout layout = { 0, 0 };
369 /* The printf(3) format used for output. */
370 char const *format_str = NULL;
372 initialize_main (&argc, &argv);
373 set_program_name (argv[0]);
374 setlocale (LC_ALL, "");
375 bindtextdomain (PACKAGE, LOCALEDIR);
376 textdomain (PACKAGE);
378 atexit (close_stdout);
380 equal_width = false;
381 separator = "\n";
383 /* We have to handle negative numbers in the command line but this
384 conflicts with the command line arguments. So explicitly check first
385 whether the next argument looks like a negative number. */
386 while (optind < argc)
388 if (argv[optind][0] == '-'
389 && ((optc = argv[optind][1]) == '.' || ISDIGIT (optc)))
391 /* means negative number */
392 break;
395 optc = getopt_long (argc, argv, "+f:s:w", long_options, NULL);
396 if (optc == -1)
397 break;
399 switch (optc)
401 case 'f':
402 format_str = optarg;
403 break;
405 case 's':
406 separator = optarg;
407 break;
409 case 'w':
410 equal_width = true;
411 break;
413 case_GETOPT_HELP_CHAR;
415 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
417 default:
418 usage (EXIT_FAILURE);
422 if (argc - optind < 1)
424 error (0, 0, _("missing operand"));
425 usage (EXIT_FAILURE);
428 if (3 < argc - optind)
430 error (0, 0, _("extra operand %s"), quote (argv[optind + 3]));
431 usage (EXIT_FAILURE);
434 if (format_str)
436 validate_format (format_str);
437 char const *f = long_double_format (format_str, &layout);
438 if (! f)
440 error (0, 0, _("invalid format string: %s"), quote (format_str));
441 usage (EXIT_FAILURE);
443 format_str = f;
446 last = scan_arg (argv[optind++]);
448 if (optind < argc)
450 first = last;
451 last = scan_arg (argv[optind++]);
453 if (optind < argc)
455 step = last;
456 last = scan_arg (argv[optind++]);
460 if (format_str != NULL && equal_width)
462 error (0, 0, _("\
463 format string may not be specified when printing equal width strings"));
464 usage (EXIT_FAILURE);
467 if (format_str == NULL)
468 format_str = get_default_format (first, step, last);
470 print_numbers (format_str, layout, first.value, step.value, last.value);
472 exit (EXIT_SUCCESS);