1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29#include "libbb.h"
30
31
32
33#define OPT_e (1 << 0)
34#define OPT_i (1 << 1)
35#define OPT_n (1 << 2)
36#define OPT_o (1 << 3)
37#define OPT_z (1 << 4)
38#define OPT_STR "ei:n:o:z"
39
40
41
42
43
44
45static void shuffle_lines(char **lines, unsigned numlines, unsigned outlines)
46{
47 srand(monotonic_us());
48
49 while (outlines != 0) {
50 char *tmp;
51 unsigned r = rand();
52
53 if (numlines > RAND_MAX)
54 r ^= rand() << 15;
55 r %= numlines;
56
57
58
59
60
61 numlines--;
62 tmp = lines[numlines];
63 lines[numlines] = lines[r];
64 lines[r] = tmp;
65 outlines--;
66 }
67}
68
69int shuf_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
70int shuf_main(int argc, char **argv)
71{
72 unsigned opts;
73 char *opt_i_str, *opt_n_str, *opt_o_str;
74 char **lines;
75 unsigned long long lo = lo;
76 unsigned numlines, outlines;
77 unsigned i;
78 char eol;
79
80 opts = getopt32(argv, "^"
81 OPT_STR
82 "\0" "e--i:i--e",
83 &opt_i_str, &opt_n_str, &opt_o_str
84 );
85
86 argc -= optind;
87 argv += optind;
88
89
90 if (opts & OPT_e) {
91
92 numlines = argc;
93 lines = argv;
94 } else
95 if (opts & OPT_i) {
96
97 unsigned long long hi;
98 char *dash;
99
100 if (argv[0])
101 bb_show_usage();
102
103 dash = strchr(opt_i_str, '-');
104 if (!dash) {
105 bb_error_msg_and_die("bad range '%s'", opt_i_str);
106 }
107 *dash = '\0';
108 lo = xatoull(opt_i_str);
109 hi = xatoull(dash + 1);
110 *dash = '-';
111 if (hi < lo)
112 bb_error_msg_and_die("bad range '%s'", opt_i_str);
113 hi -= lo;
114 if (sizeof(size_t) > sizeof(numlines)) {
115 if (hi >= UINT_MAX)
116 bb_error_msg_and_die("bad range '%s'", opt_i_str);
117 } else {
118 if (hi >= UINT_MAX / sizeof(lines[0]))
119 bb_error_msg_and_die("bad range '%s'", opt_i_str);
120 }
121
122 numlines = hi + 1;
123 lines = xmalloc((size_t)numlines * sizeof(lines[0]));
124 for (i = 0; i < numlines; i++) {
125 lines[i] = (char*)(uintptr_t)i;
126 }
127 } else {
128
129 FILE *fp;
130 const char *fname = "-";
131
132 if (argv[0]) {
133 if (argv[1])
134 bb_show_usage();
135 fname = argv[0];
136 }
137
138 fp = xfopen_stdin(fname);
139 lines = NULL;
140 numlines = 0;
141 for (;;) {
142 char *line = xmalloc_fgetline(fp);
143 if (!line)
144 break;
145 lines = xrealloc_vector(lines, 6, numlines);
146 lines[numlines++] = line;
147 }
148 fclose_if_not_stdin(fp);
149 }
150
151 outlines = numlines;
152 if (opts & OPT_n) {
153 outlines = xatou(opt_n_str);
154 if (outlines > numlines)
155 outlines = numlines;
156 }
157
158 shuffle_lines(lines, numlines, outlines);
159
160 if (opts & OPT_o)
161 xmove_fd(xopen(opt_o_str, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
162
163 eol = '\n';
164 if (opts & OPT_z)
165 eol = '\0';
166
167 for (i = numlines - outlines; i < numlines; i++) {
168 if (opts & OPT_i)
169 printf("%llu%c", lo + (uintptr_t)lines[i], eol);
170 else
171 printf("%s%c", lines[i], eol);
172 }
173
174 fflush_stdout_and_exit(EXIT_SUCCESS);
175}
176