TODO: add an item for a chmod optimization
[platform/upstream/coreutils.git] / src / seq.c
1 /* seq - print sequence of numbers to standard output.
2    Copyright (C) 1994-2008 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>.  */
16
17 /* Written by Ulrich Drepper.  */
18
19 #include <config.h>
20 #include <getopt.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <math.h>
24 #include <float.h>
25
26 #include "system.h"
27 #include "c-strtod.h"
28 #include "error.h"
29 #include "quote.h"
30 #include "xstrtod.h"
31
32 /* Roll our own isfinite rather than using <math.h>, so that we don't
33    have to worry about linking -lm just for isfinite.  */
34 #ifndef isfinite
35 # define isfinite(x) ((x) * 0 == 0)
36 #endif
37
38 /* The official name of this program (e.g., no `g' prefix).  */
39 #define PROGRAM_NAME "seq"
40
41 #define AUTHORS proper_name ("Ulrich Drepper")
42
43 /* If true print all number with equal width.  */
44 static bool equal_width;
45
46 /* The string used to separate two numbers.  */
47 static char const *separator;
48
49 /* The string output after all numbers have been output.
50    Usually "\n" or "\0".  */
51 /* FIXME: make this an option.  */
52 static char const terminator[] = "\n";
53
54 static struct option const long_options[] =
55 {
56   { "equal-width", no_argument, NULL, 'w'},
57   { "format", required_argument, NULL, 'f'},
58   { "separator", required_argument, NULL, 's'},
59   {GETOPT_HELP_OPTION_DECL},
60   {GETOPT_VERSION_OPTION_DECL},
61   { NULL, 0, NULL, 0}
62 };
63
64 void
65 usage (int status)
66 {
67   if (status != EXIT_SUCCESS)
68     fprintf (stderr, _("Try `%s --help' for more information.\n"),
69              program_name);
70   else
71     {
72       printf (_("\
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);
77       fputs (_("\
78 Print numbers from FIRST to LAST, in steps of INCREMENT.\n\
79 \n\
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 FIRST, INCREMENT, and LAST are interpreted as floating point values.\n\
91 INCREMENT is usually positive if FIRST is smaller than LAST, and\n\
92 INCREMENT is usually negative if FIRST is greater than LAST.\n\
93 "), stdout);
94       fputs (_("\
95 FORMAT must be suitable for printing one argument of type `double';\n\
96 it defaults to %.PRECf if FIRST, INCREMENT, and LAST are all fixed point\n\
97 decimal numbers with maximum precision PREC, and to %g otherwise.\n\
98 "), stdout);
99       emit_bug_reporting_address ();
100     }
101   exit (status);
102 }
103
104 /* A command-line operand.  */
105 struct operand
106 {
107   /* Its value, converted to 'long double'.  */
108   long double value;
109
110   /* Its print width, if it were printed out in a form similar to its
111      input form.  An input like "-.1" is treated like "-0.1", and an
112      input like "1." is treated like "1", but otherwise widths are
113      left alone.  */
114   size_t width;
115
116   /* Number of digits after the decimal point, or INT_MAX if the
117      number can't easily be expressed as a fixed-point number.  */
118   int precision;
119 };
120 typedef struct operand operand;
121
122 /* Description of what a number-generating format will generate.  */
123 struct layout
124 {
125   /* Number of bytes before and after the number.  */
126   size_t prefix_len;
127   size_t suffix_len;
128 };
129
130 /* Read a long double value from the command line.
131    Return if the string is correct else signal error.  */
132
133 static operand
134 scan_arg (const char *arg)
135 {
136   operand ret;
137
138   if (! xstrtold (arg, NULL, &ret.value, c_strtold))
139     {
140       error (0, 0, _("invalid floating point argument: %s"), arg);
141       usage (EXIT_FAILURE);
142     }
143
144   /* We don't output spaces or '+' so don't include in width */
145   while (isspace (to_uchar (*arg)) || *arg == '+')
146     arg++;
147
148   ret.width = strlen (arg);
149   ret.precision = INT_MAX;
150
151   if (! arg[strcspn (arg, "xX")] && isfinite (ret.value))
152     {
153       char const *decimal_point = strchr (arg, '.');
154       if (! decimal_point)
155         ret.precision = 0;
156       else
157         {
158           size_t fraction_len = strcspn (decimal_point + 1, "eE");
159           if (fraction_len <= INT_MAX)
160             ret.precision = fraction_len;
161           ret.width += (fraction_len == 0                      /* #.  -> #   */
162                         ? -1
163                         : (decimal_point == arg                /* .#  -> 0.# */
164                            || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */
165         }
166       char const *e = strchr (arg, 'e');
167       if (! e)
168         e = strchr (arg, 'E');
169       if (e)
170         {
171           long exponent = strtol (e + 1, NULL, 10);
172           ret.precision += exponent < 0 ? -exponent : 0;
173         }
174     }
175
176   return ret;
177 }
178
179 /* Validate the format, FMT.  Print a diagnostic and exit
180    if there is not exactly one %-directive.  */
181
182 static void
183 validate_format (char const *fmt)
184 {
185   unsigned int n_directives = 0;
186   char const *p;
187
188   for (p = fmt; *p; p++)
189     {
190       if (p[0] == '%' && p[1] != '%' && p[1] != '\0')
191         {
192           ++n_directives;
193           ++p;
194         }
195     }
196   if (n_directives == 0)
197     {
198       error (0, 0, _("no %% directive in format string %s"), quote (fmt));
199       usage (EXIT_FAILURE);
200     }
201   else if (1 < n_directives)
202     error (EXIT_FAILURE, 0, _("too many %% directives in format string %s"),
203            quote (fmt));
204 }
205
206 /* If FORMAT is a valid printf format for a double argument, return
207    its long double equivalent, possibly allocated from dynamic
208    storage, and store into *LAYOUT a description of the output layout;
209    otherwise, return NULL.  */
210
211 static char const *
212 long_double_format (char const *fmt, struct layout *layout)
213 {
214   size_t i;
215   size_t prefix_len = 0;
216   size_t suffix_len = 0;
217   size_t length_modifier_offset;
218   bool has_L;
219
220   for (i = 0; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
221     if (fmt[i])
222       prefix_len++;
223     else
224       return NULL;
225
226   i++;
227   i += strspn (fmt + i, "-+#0 '");
228   i += strspn (fmt + i, "0123456789");
229   if (fmt[i] == '.')
230     {
231       i++;
232       i += strspn (fmt + i, "0123456789");
233     }
234
235   length_modifier_offset = i;
236   has_L = (fmt[i] == 'L');
237   i += has_L;
238   /* In a valid format string, fmt[i] must be one of these specifiers.  */
239   if (fmt[i] == '\0' || ! strchr ("efgaEFGA", fmt[i]))
240     return NULL;
241
242   for (i++; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1)
243     if (fmt[i])
244       suffix_len++;
245     else
246       {
247         size_t format_size = i + 1;
248         char *ldfmt = xmalloc (format_size + 1);
249         memcpy (ldfmt, fmt, length_modifier_offset);
250         ldfmt[length_modifier_offset] = 'L';
251         strcpy (ldfmt + length_modifier_offset + 1,
252                 fmt + length_modifier_offset + has_L);
253         layout->prefix_len = prefix_len;
254         layout->suffix_len = suffix_len;
255         return ldfmt;
256       }
257
258   return NULL;
259 }
260
261 /* Return the absolute relative difference from x to y.  */
262 static double
263 abs_rel_diff (double x, double y)
264 {
265   double s = (y == 0.0 ? 1 : y);
266   return fabs ((y - x) / s);
267 }
268
269 /* Actually print the sequence of numbers in the specified range, with the
270    given or default stepping and format.  */
271
272 static void
273 print_numbers (char const *fmt, struct layout layout,
274                long double first, long double step, long double last)
275 {
276   bool out_of_range = (step < 0 ? first < last : last < first);
277
278   if (! out_of_range)
279     {
280       long double x = first;
281       long double i;
282
283       for (i = 1; ; i++)
284         {
285           long double x0 = x;
286           printf (fmt, x);
287           if (out_of_range)
288             break;
289           x = first + i * step;
290           out_of_range = (step < 0 ? x < last : last < x);
291
292           if (out_of_range)
293             {
294               /* If the number just past LAST prints as a value equal
295                  to LAST, and prints differently from the previous
296                  number, then print the number.  This avoids problems
297                  with rounding.  For example, with the x86 it causes
298                  "seq 0 0.000001 0.000003" to print 0.000003 instead
299                  of stopping at 0.000002.  */
300
301               bool print_extra_number = false;
302               long double x_val;
303               char *x_str;
304               int x_strlen = asprintf (&x_str, fmt, x);
305               if (x_strlen < 0)
306                 xalloc_die ();
307               x_str[x_strlen - layout.suffix_len] = '\0';
308
309               if (xstrtold (x_str + layout.prefix_len, NULL, &x_val, c_strtold)
310                   && abs_rel_diff (x_val, last) < DBL_EPSILON)
311                 {
312                   char *x0_str = NULL;
313                   if (asprintf (&x0_str, fmt, x0) < 0)
314                     xalloc_die ();
315                   print_extra_number = !STREQ (x0_str, x_str);
316                   free (x0_str);
317                 }
318
319               free (x_str);
320               if (! print_extra_number)
321                 break;
322             }
323
324           fputs (separator, stdout);
325         }
326
327       fputs (terminator, stdout);
328     }
329 }
330
331 /* Return the default format given FIRST, STEP, and LAST.  */
332 static char const *
333 get_default_format (operand first, operand step, operand last)
334 {
335   static char format_buf[sizeof "%0.Lf" + 2 * INT_STRLEN_BOUND (int)];
336
337   int prec = MAX (first.precision, step.precision);
338
339   if (prec != INT_MAX && last.precision != INT_MAX)
340     {
341       if (equal_width)
342         {
343           /* increase first_width by any increased precision in step */
344           size_t first_width = first.width + (prec - first.precision);
345           /* adjust last_width to use precision from first/step */
346           size_t last_width = last.width + (prec - last.precision);
347           if (last.precision && prec == 0)
348             last_width--;  /* don't include space for '.' */
349           size_t width = MAX (first_width, last_width);
350           if (width <= INT_MAX)
351             {
352               int w = width;
353               sprintf (format_buf, "%%0%d.%dLf", w, prec);
354               return format_buf;
355             }
356         }
357       else
358         {
359           sprintf (format_buf, "%%.%dLf", prec);
360           return format_buf;
361         }
362     }
363
364   return "%Lg";
365 }
366
367 int
368 main (int argc, char **argv)
369 {
370   int optc;
371   operand first = { 1, 1, 0 };
372   operand step = { 1, 1, 0 };
373   operand last;
374   struct layout layout = { 0, 0 };
375
376   /* The printf(3) format used for output.  */
377   char const *format_str = NULL;
378
379   initialize_main (&argc, &argv);
380   set_program_name (argv[0]);
381   setlocale (LC_ALL, "");
382   bindtextdomain (PACKAGE, LOCALEDIR);
383   textdomain (PACKAGE);
384
385   atexit (close_stdout);
386
387   equal_width = false;
388   separator = "\n";
389
390   /* We have to handle negative numbers in the command line but this
391      conflicts with the command line arguments.  So explicitly check first
392      whether the next argument looks like a negative number.  */
393   while (optind < argc)
394     {
395       if (argv[optind][0] == '-'
396           && ((optc = argv[optind][1]) == '.' || ISDIGIT (optc)))
397         {
398           /* means negative number */
399           break;
400         }
401
402       optc = getopt_long (argc, argv, "+f:s:w", long_options, NULL);
403       if (optc == -1)
404         break;
405
406       switch (optc)
407         {
408         case 'f':
409           format_str = optarg;
410           break;
411
412         case 's':
413           separator = optarg;
414           break;
415
416         case 'w':
417           equal_width = true;
418           break;
419
420         case_GETOPT_HELP_CHAR;
421
422         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
423
424         default:
425           usage (EXIT_FAILURE);
426         }
427     }
428
429   if (argc - optind < 1)
430     {
431       error (0, 0, _("missing operand"));
432       usage (EXIT_FAILURE);
433     }
434
435   if (3 < argc - optind)
436     {
437       error (0, 0, _("extra operand %s"), quote (argv[optind + 3]));
438       usage (EXIT_FAILURE);
439     }
440
441   if (format_str)
442     {
443       validate_format (format_str);
444       char const *f = long_double_format (format_str, &layout);
445       if (! f)
446         {
447           error (0, 0, _("invalid format string: %s"), quote (format_str));
448           usage (EXIT_FAILURE);
449         }
450       format_str = f;
451     }
452
453   last = scan_arg (argv[optind++]);
454
455   if (optind < argc)
456     {
457       first = last;
458       last = scan_arg (argv[optind++]);
459
460       if (optind < argc)
461         {
462           step = last;
463           last = scan_arg (argv[optind++]);
464         }
465     }
466
467   if (format_str != NULL && equal_width)
468     {
469       error (0, 0, _("\
470 format string may not be specified when printing equal width strings"));
471       usage (EXIT_FAILURE);
472     }
473
474   if (format_str == NULL)
475     format_str = get_default_format (first, step, last);
476
477   print_numbers (format_str, layout, first.value, step.value, last.value);
478
479   exit (EXIT_SUCCESS);
480 }