1 /* seq.c - Count from first to last, by increment.
2 *
3 * Copyright 2006 Rob Landley <rob@landley.net>
4 *
5 * http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/seq.html
6
7 USE_SEQ(NEWTOY(seq, "<1>3?f:s:w[!fw]", TOYFLAG_USR|TOYFLAG_BIN))
8
9 config SEQ
10 bool "seq"
11 depends on TOYBOX_FLOAT
12 default y
13 help
14 usage: seq [-w|-f fmt_str] [-s sep_str] [first] [increment] last
15
16 Count from first to last, by increment. Omitted arguments default
17 to 1. Two arguments are used as first and last. Arguments can be
18 negative or floating point.
19
20 -f Use fmt_str as a printf-style floating point format string
21 -s Use sep_str as separator, default is a newline character
22 -w Pad to equal width with leading zeroes
23 */
24
25 #define FOR_seq
26 #include "toys.h"
27
GLOBALS(char * sep;char * fmt;int precision;)28 GLOBALS(
29 char *sep;
30 char *fmt;
31
32 int precision;
33 )
34
35 // Ensure there's one %f escape with correct attributes
36 static void insanitize(char *f)
37 {
38 char *s = next_printf(f, 0);
39
40 if (!s) error_exit("bad -f no %%f");
41 if (-1 == stridx("aAeEfFgG", *s) || (s = next_printf(s, 0))) {
42 // The @ is a byte offset, not utf8 chars. Waiting for somebody to complain.
43 error_exit("bad -f '%s'@%d", f, (int)(s-f+1));
44 }
45 }
46
47 // Parse a numeric argument setting *prec to the precision of this argument.
48 // This reproduces the "1.234e5" precision bug from upstream.
parsef(char * s)49 static double parsef(char *s)
50 {
51 char *dp = strchr(s, '.');
52
53 if (dp++) TT.precision = maxof(TT.precision, strcspn(dp, "eE"));
54
55 return xstrtod(s);
56 }
57
seq_main(void)58 void seq_main(void)
59 {
60 double first = 1, increment = 1, last, dd;
61 int i;
62
63 if (!TT.sep) TT.sep = "\n";
64 switch (toys.optc) {
65 case 3: increment = parsef(toys.optargs[1]);
66 case 2: first = parsef(*toys.optargs);
67 default: last = parsef(toys.optargs[toys.optc-1]);
68 }
69
70 // Prepare format string with appropriate precision. Can't use %g because 1e6
71 if (toys.optflags & FLAG_f) insanitize(TT.fmt);
72 else sprintf(TT.fmt = toybuf, "%%.%df", TT.precision);
73
74 // Pad to largest width
75 if (toys.optflags & FLAG_w) {
76 int len = 0;
77
78 for (i=0; i<3; i++) {
79 dd = (double []){first, increment, last}[i];
80 len = maxof(len, snprintf(0, 0, TT.fmt, dd));
81 }
82 sprintf(TT.fmt = toybuf, "%%0%d.%df", len, TT.precision);
83 }
84
85 // Other implementations output nothing if increment is 0 and first > last,
86 // but loop forever if first < last or even first == last. We output
87 // nothing for all three, if you want endless output use "yes".
88 if (!increment) return;
89
90 i = 0;
91 for (;;) {
92 // Multiply to avoid accumulating rounding errors from increment.
93 dd = first+i*increment;
94 if ((increment<0 && dd<last) || (increment>0 && dd>last)) break;
95 if (i++) printf("%s", TT.sep);
96 printf(TT.fmt, dd);
97 }
98
99 if (i) printf("\n");
100 }
101