maint: cleanup up various uses of __attribute__
[coreutils.git] / src / shuf.c
blob71ac3e60c9868d84f7963ef6f25bb6eb3627e2eb
1 /* Shuffle lines of text.
3 Copyright (C) 2006-2013 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 Written by Paul Eggert. */
20 #include <config.h>
22 #include <sys/types.h>
23 #include "system.h"
25 #include "error.h"
26 #include "fadvise.h"
27 #include "getopt.h"
28 #include "quote.h"
29 #include "quotearg.h"
30 #include "randint.h"
31 #include "randperm.h"
32 #include "read-file.h"
33 #include "stdio--.h"
34 #include "xstrtol.h"
36 /* The official name of this program (e.g., no 'g' prefix). */
37 #define PROGRAM_NAME "shuf"
39 #define AUTHORS proper_name ("Paul Eggert")
41 void
42 usage (int status)
44 if (status != EXIT_SUCCESS)
45 emit_try_help ();
46 else
48 printf (_("\
49 Usage: %s [OPTION]... [FILE]\n\
50 or: %s -e [OPTION]... [ARG]...\n\
51 or: %s -i LO-HI [OPTION]...\n\
52 "),
53 program_name, program_name, program_name);
54 fputs (_("\
55 Write a random permutation of the input lines to standard output.\n\
56 "), stdout);
58 emit_mandatory_arg_note ();
60 fputs (_("\
61 -e, --echo treat each ARG as an input line\n\
62 -i, --input-range=LO-HI treat each number LO through HI as an input line\n\
63 -n, --head-count=COUNT output at most COUNT lines\n\
64 -o, --output=FILE write result to FILE instead of standard output\n\
65 --random-source=FILE get random bytes from FILE\n\
66 -z, --zero-terminated end lines with 0 byte, not newline\n\
67 "), stdout);
68 fputs (HELP_OPTION_DESCRIPTION, stdout);
69 fputs (VERSION_OPTION_DESCRIPTION, stdout);
70 fputs (_("\
71 \n\
72 With no FILE, or when FILE is -, read standard input.\n\
73 "), stdout);
74 emit_ancillary_info ();
77 exit (status);
80 /* For long options that have no equivalent short option, use a
81 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
82 enum
84 RANDOM_SOURCE_OPTION = CHAR_MAX + 1
87 static struct option const long_opts[] =
89 {"echo", no_argument, NULL, 'e'},
90 {"input-range", required_argument, NULL, 'i'},
91 {"head-count", required_argument, NULL, 'n'},
92 {"output", required_argument, NULL, 'o'},
93 {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},
94 {"zero-terminated", no_argument, NULL, 'z'},
95 {GETOPT_HELP_OPTION_DECL},
96 {GETOPT_VERSION_OPTION_DECL},
97 {0, 0, 0, 0},
100 static bool
101 input_numbers_option_used (size_t lo_input, size_t hi_input)
103 return ! (lo_input == SIZE_MAX && hi_input == 0);
106 static void
107 input_from_argv (char **operand, int n_operands, char eolbyte)
109 char *p;
110 size_t size = n_operands;
111 int i;
113 for (i = 0; i < n_operands; i++)
114 size += strlen (operand[i]);
115 p = xmalloc (size);
117 for (i = 0; i < n_operands; i++)
119 char *p1 = stpcpy (p, operand[i]);
120 operand[i] = p;
121 p = p1;
122 *p++ = eolbyte;
125 operand[n_operands] = p;
128 /* Return the start of the next line after LINE. The current line
129 ends in EOLBYTE, and is guaranteed to end before LINE + N. */
131 static char *
132 next_line (char *line, char eolbyte, size_t n)
134 char *p = memchr (line, eolbyte, n);
135 return p + 1;
138 /* Read data from file IN. Input lines are delimited by EOLBYTE;
139 silently append a trailing EOLBYTE if the file ends in some other
140 byte. Store a pointer to the resulting array of lines into *PLINE.
141 Return the number of lines read. Report an error and exit on
142 failure. */
144 static size_t
145 read_input (FILE *in, char eolbyte, char ***pline)
147 char *p;
148 char *buf = NULL;
149 size_t used;
150 char *lim;
151 char **line;
152 size_t i;
153 size_t n_lines;
155 if (!(buf = fread_file (in, &used)))
156 error (EXIT_FAILURE, errno, _("read error"));
158 if (used && buf[used - 1] != eolbyte)
159 buf[used++] = eolbyte;
161 lim = buf + used;
163 n_lines = 0;
164 for (p = buf; p < lim; p = next_line (p, eolbyte, lim - p))
165 n_lines++;
167 *pline = line = xnmalloc (n_lines + 1, sizeof *line);
169 line[0] = p = buf;
170 for (i = 1; i <= n_lines; i++)
171 line[i] = p = next_line (p, eolbyte, lim - p);
173 return n_lines;
176 static int
177 write_permuted_output (size_t n_lines, char * const *line, size_t lo_input,
178 size_t const *permutation, char eolbyte)
180 size_t i;
182 if (line)
183 for (i = 0; i < n_lines; i++)
185 char * const *p = line + permutation[i];
186 size_t len = p[1] - p[0];
187 if (fwrite (p[0], sizeof *p[0], len, stdout) != len)
188 return -1;
190 else
191 for (i = 0; i < n_lines; i++)
193 unsigned long int n = lo_input + permutation[i];
194 if (printf ("%lu%c", n, eolbyte) < 0)
195 return -1;
198 return 0;
202 main (int argc, char **argv)
204 bool echo = false;
205 size_t lo_input = SIZE_MAX;
206 size_t hi_input = 0;
207 size_t head_lines = SIZE_MAX;
208 char const *outfile = NULL;
209 char *random_source = NULL;
210 char eolbyte = '\n';
211 char **input_lines = NULL;
213 int optc;
214 int n_operands;
215 char **operand;
216 size_t n_lines;
217 char **line;
218 struct randint_source *randint_source;
219 size_t *permutation;
221 initialize_main (&argc, &argv);
222 set_program_name (argv[0]);
223 setlocale (LC_ALL, "");
224 bindtextdomain (PACKAGE, LOCALEDIR);
225 textdomain (PACKAGE);
227 atexit (close_stdout);
229 while ((optc = getopt_long (argc, argv, "ei:n:o:z", long_opts, NULL)) != -1)
230 switch (optc)
232 case 'e':
233 echo = true;
234 break;
236 case 'i':
238 unsigned long int argval = 0;
239 char *p = strchr (optarg, '-');
240 char const *hi_optarg = optarg;
241 bool invalid = !p;
243 if (input_numbers_option_used (lo_input, hi_input))
244 error (EXIT_FAILURE, 0, _("multiple -i options specified"));
246 if (p)
248 *p = '\0';
249 invalid = ((xstrtoul (optarg, NULL, 10, &argval, NULL)
250 != LONGINT_OK)
251 || SIZE_MAX < argval);
252 *p = '-';
253 lo_input = argval;
254 hi_optarg = p + 1;
257 invalid |= ((xstrtoul (hi_optarg, NULL, 10, &argval, NULL)
258 != LONGINT_OK)
259 || SIZE_MAX < argval);
260 hi_input = argval;
261 n_lines = hi_input - lo_input + 1;
262 invalid |= ((lo_input <= hi_input) == (n_lines == 0));
263 if (invalid)
264 error (EXIT_FAILURE, 0, _("invalid input range %s"),
265 quote (optarg));
267 break;
269 case 'n':
271 unsigned long int argval;
272 strtol_error e = xstrtoul (optarg, NULL, 10, &argval, NULL);
274 if (e == LONGINT_OK)
275 head_lines = MIN (head_lines, argval);
276 else if (e != LONGINT_OVERFLOW)
277 error (EXIT_FAILURE, 0, _("invalid line count %s"),
278 quote (optarg));
280 break;
282 case 'o':
283 if (outfile && !STREQ (outfile, optarg))
284 error (EXIT_FAILURE, 0, _("multiple output files specified"));
285 outfile = optarg;
286 break;
288 case RANDOM_SOURCE_OPTION:
289 if (random_source && !STREQ (random_source, optarg))
290 error (EXIT_FAILURE, 0, _("multiple random sources specified"));
291 random_source = optarg;
292 break;
294 case 'z':
295 eolbyte = '\0';
296 break;
298 case_GETOPT_HELP_CHAR;
299 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
300 default:
301 usage (EXIT_FAILURE);
304 n_operands = argc - optind;
305 operand = argv + optind;
307 if (echo)
309 if (input_numbers_option_used (lo_input, hi_input))
310 error (EXIT_FAILURE, 0, _("cannot combine -e and -i options"));
311 input_from_argv (operand, n_operands, eolbyte);
312 n_lines = n_operands;
313 line = operand;
315 else if (input_numbers_option_used (lo_input, hi_input))
317 if (n_operands)
319 error (0, 0, _("extra operand %s"), quote (operand[0]));
320 usage (EXIT_FAILURE);
322 n_lines = hi_input - lo_input + 1;
323 line = NULL;
325 else
327 switch (n_operands)
329 case 0:
330 break;
332 case 1:
333 if (! (STREQ (operand[0], "-") || freopen (operand[0], "r", stdin)))
334 error (EXIT_FAILURE, errno, "%s", operand[0]);
335 break;
337 default:
338 error (0, 0, _("extra operand %s"), quote (operand[1]));
339 usage (EXIT_FAILURE);
342 fadvise (stdin, FADVISE_SEQUENTIAL);
344 n_lines = read_input (stdin, eolbyte, &input_lines);
345 line = input_lines;
348 head_lines = MIN (head_lines, n_lines);
350 randint_source = randint_all_new (random_source,
351 randperm_bound (head_lines, n_lines));
352 if (! randint_source)
353 error (EXIT_FAILURE, errno, "%s", quotearg_colon (random_source));
355 /* Close stdin now, rather than earlier, so that randint_all_new
356 doesn't have to worry about opening something other than
357 stdin. */
358 if (! (echo || input_numbers_option_used (lo_input, hi_input))
359 && (fclose (stdin) != 0))
360 error (EXIT_FAILURE, errno, _("read error"));
362 permutation = randperm_new (randint_source, head_lines, n_lines);
364 if (outfile && ! freopen (outfile, "w", stdout))
365 error (EXIT_FAILURE, errno, "%s", quotearg_colon (outfile));
366 if (write_permuted_output (head_lines, line, lo_input, permutation, eolbyte)
367 != 0)
368 error (EXIT_FAILURE, errno, _("write error"));
370 #ifdef lint
371 free (permutation);
372 randint_all_free (randint_source);
373 if (input_lines)
375 free (input_lines[0]);
376 free (input_lines);
378 #endif
380 return EXIT_SUCCESS;