1 /* Shuffle lines of text.
3 Copyright (C) 2006-2024 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 <https://www.gnu.org/licenses/>.
18 Written by Paul Eggert. */
22 #include <sys/types.h>
27 #include "linebuffer.h"
31 #include "read-file.h"
35 /* The official name of this program (e.g., no 'g' prefix). */
36 #define PROGRAM_NAME "shuf"
38 #define AUTHORS proper_name ("Paul Eggert")
40 /* reservoir-sampling introduces CPU overhead for small inputs.
41 So only enable it for inputs >= this limit.
42 This limit was determined using these commands:
43 $ for p in $(seq 7); do src/seq $((10**$p)) > 10p$p.in; done
44 $ for p in $(seq 7); do time shuf-nores -n10 10p$p.in >/dev/null; done
45 $ for p in $(seq 7); do time shuf -n10 10p$p.in >/dev/null; done .*/
46 enum { RESERVOIR_MIN_INPUT
= 8192 * 1024 };
52 if (status
!= EXIT_SUCCESS
)
57 Usage: %s [OPTION]... [FILE]\n\
58 or: %s -e [OPTION]... [ARG]...\n\
59 or: %s -i LO-HI [OPTION]...\n\
61 program_name
, program_name
, program_name
);
63 Write a random permutation of the input lines to standard output.\n\
67 emit_mandatory_arg_note ();
70 -e, --echo treat each ARG as an input line\n\
71 -i, --input-range=LO-HI treat each number LO through HI as an input line\n\
72 -n, --head-count=COUNT output at most COUNT lines\n\
73 -o, --output=FILE write result to FILE instead of standard output\n\
74 --random-source=FILE get random bytes from FILE\n\
75 -r, --repeat output lines can be repeated\n\
78 -z, --zero-terminated line delimiter is NUL, not newline\n\
80 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
81 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
82 emit_ancillary_info (PROGRAM_NAME
);
88 /* For long options that have no equivalent short option, use a
89 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
92 RANDOM_SOURCE_OPTION
= CHAR_MAX
+ 1
95 static struct option
const long_opts
[] =
97 {"echo", no_argument
, nullptr, 'e'},
98 {"input-range", required_argument
, nullptr, 'i'},
99 {"head-count", required_argument
, nullptr, 'n'},
100 {"output", required_argument
, nullptr, 'o'},
101 {"random-source", required_argument
, nullptr, RANDOM_SOURCE_OPTION
},
102 {"repeat", no_argument
, nullptr, 'r'},
103 {"zero-terminated", no_argument
, nullptr, 'z'},
104 {GETOPT_HELP_OPTION_DECL
},
105 {GETOPT_VERSION_OPTION_DECL
},
110 input_from_argv (char **operand
, int n_operands
, char eolbyte
)
113 size_t size
= n_operands
;
116 for (i
= 0; i
< n_operands
; i
++)
117 size
+= strlen (operand
[i
]);
120 for (i
= 0; i
< n_operands
; i
++)
122 char *p1
= stpcpy (p
, operand
[i
]);
128 operand
[n_operands
] = p
;
131 /* Return the start of the next line after LINE, which is guaranteed
132 to end in EOLBYTE. */
135 next_line (char *line
, char eolbyte
)
137 char *p
= rawmemchr (line
, eolbyte
);
141 /* Return the size of the input if possible or OFF_T_MAX if not. */
148 struct stat stat_buf
;
149 if (fstat (STDIN_FILENO
, &stat_buf
) != 0)
151 if (usable_st_size (&stat_buf
))
152 file_size
= stat_buf
.st_size
;
156 off_t input_offset
= lseek (STDIN_FILENO
, 0, SEEK_CUR
);
157 if (input_offset
< 0)
160 file_size
-= input_offset
;
165 /* Read all lines and store up to K permuted lines in *OUT_RSRV.
166 Return the number of lines read, up to a maximum of K. */
169 read_input_reservoir_sampling (FILE *in
, char eolbyte
, idx_t k
,
170 struct randint_source
*s
,
171 struct linebuffer
**out_rsrv
)
174 idx_t n_alloc_lines
= 0;
175 struct linebuffer
*line
= nullptr;
176 struct linebuffer
*rsrv
= nullptr;
178 /* Fill the first K lines, directly into the reservoir. */
179 for (n_lines
= 0; n_lines
< k
; n_lines
++)
181 /* Enlarge reservoir if needed. */
182 if (n_lines
== n_alloc_lines
)
184 idx_t old
= n_alloc_lines
;
185 rsrv
= xpalloc (rsrv
, &n_alloc_lines
, 1, k
, sizeof *rsrv
);
186 memset (&rsrv
[n_lines
], 0, (n_alloc_lines
- old
) * sizeof *rsrv
);
189 line
= readlinebuffer_delim (&rsrv
[n_lines
], in
, eolbyte
);
194 /* last line wasn't null - so there may be more lines to read. */
197 struct linebuffer dummy
;
198 initbuffer (&dummy
); /* space for lines not put in reservoir. */
200 /* Choose the fate of the next line, with decreasing probability (as
201 n_lines increases in size).
203 If the line will be used, store it directly in the reservoir.
204 Otherwise, store it in dummy space.
206 With 'struct linebuffer', storing into existing buffer will reduce
207 re-allocations (will only re-allocate if the new line is longer than
208 the currently allocated space). */
211 randint j
= randint_choose (s
, n_lines
+ 1); /* 0 .. n_lines. */
212 line
= (j
< k
) ? (&rsrv
[j
]) : (&dummy
);
214 while (readlinebuffer_delim (line
, in
, eolbyte
) != nullptr && n_lines
++);
217 error (EXIT_FAILURE
, EOVERFLOW
, _("too many input lines"));
222 /* no more input lines, or an input error. */
224 error (EXIT_FAILURE
, errno
, _("read error"));
227 return MIN (k
, n_lines
);
231 write_permuted_output_reservoir (size_t n_lines
, struct linebuffer
*lines
,
232 size_t const *permutation
)
234 for (size_t i
= 0; i
< n_lines
; i
++)
236 const struct linebuffer
*p
= &lines
[permutation
[i
]];
237 if (fwrite (p
->buffer
, sizeof (char), p
->length
, stdout
) != p
->length
)
244 /* Read data from file IN. Input lines are delimited by EOLBYTE;
245 silently append a trailing EOLBYTE if the file ends in some other
246 byte. Store a pointer to the resulting array of lines into *PLINE.
247 Return the number of lines read. Report an error and exit on
251 read_input (FILE *in
, char eolbyte
, char ***pline
)
260 /* TODO: We should limit the amount of data read here,
261 to less than RESERVOIR_MIN_INPUT. I.e., adjust fread_file() to support
262 taking a byte limit. We'd then need to ensure we handle a line spanning
263 this boundary. With that in place we could set use_reservoir_sampling
264 when used==RESERVOIR_MIN_INPUT, and have read_input_reservoir_sampling()
265 call a wrapper function to populate a linebuffer from the internal pline
266 or if none left, stdin. Doing that would give better performance by
267 avoiding the reservoir CPU overhead when reading < RESERVOIR_MIN_INPUT
268 from a pipe, and allow us to dispense with the input_size() function. */
269 if (!(buf
= fread_file (in
, 0, &used
)))
270 error (EXIT_FAILURE
, errno
, _("read error"));
272 if (used
&& buf
[used
- 1] != eolbyte
)
273 buf
[used
++] = eolbyte
;
278 for (p
= buf
; p
< lim
; p
= next_line (p
, eolbyte
))
281 *pline
= line
= xnmalloc (n_lines
+ 1, sizeof *line
);
284 for (size_t i
= 1; i
<= n_lines
; i
++)
285 line
[i
] = p
= next_line (p
, eolbyte
);
290 /* Output N_LINES lines to stdout from LINE array,
291 chosen by the indices in PERMUTATION.
292 PERMUTATION and LINE must have at least N_LINES elements.
293 Strings in LINE must include the line-terminator character. */
295 write_permuted_lines (size_t n_lines
, char *const *line
,
296 size_t const *permutation
)
298 for (size_t i
= 0; i
< n_lines
; i
++)
300 char *const *p
= line
+ permutation
[i
];
301 size_t len
= p
[1] - p
[0];
302 if (fwrite (p
[0], sizeof *p
[0], len
, stdout
) != len
)
309 /* Output N_LINES of numbers to stdout, from PERMUTATION array.
310 PERMUTATION must have at least N_LINES elements. */
312 write_permuted_numbers (size_t n_lines
, size_t lo_input
,
313 size_t const *permutation
, char eolbyte
)
315 for (size_t i
= 0; i
< n_lines
; i
++)
317 unsigned long int n
= lo_input
+ permutation
[i
];
318 if (printf ("%lu%c", n
, eolbyte
) < 0)
325 /* Output COUNT numbers to stdout, chosen randomly from range
326 LO_INPUT through HI_INPUT. */
328 write_random_numbers (struct randint_source
*s
, size_t count
,
329 size_t lo_input
, size_t hi_input
, char eolbyte
)
331 const randint range
= hi_input
- lo_input
+ 1;
333 for (size_t i
= 0; i
< count
; i
++)
335 unsigned long int j
= lo_input
+ randint_choose (s
, range
);
336 if (printf ("%lu%c", j
, eolbyte
) < 0)
343 /* Output COUNT lines to stdout from LINES array.
344 LINES must have at least N_LINES elements in it.
345 Strings in LINES_ must include the line-terminator character. */
347 write_random_lines (struct randint_source
*s
, size_t count
,
348 char *const *lines
, size_t n_lines
)
350 for (size_t i
= 0; i
< count
; i
++)
352 const randint j
= randint_choose (s
, n_lines
);
353 char *const *p
= lines
+ j
;
354 size_t len
= p
[1] - p
[0];
355 if (fwrite (p
[0], sizeof *p
[0], len
, stdout
) != len
)
363 main (int argc
, char **argv
)
366 bool input_range
= false;
367 size_t lo_input
= SIZE_MAX
;
369 idx_t head_lines
= MIN (IDX_MAX
, SIZE_MAX
);
370 char const *outfile
= nullptr;
371 char *random_source
= nullptr;
373 char **input_lines
= nullptr;
374 bool use_reservoir_sampling
= false;
381 char **line
= nullptr;
382 struct linebuffer
*reservoir
= nullptr;
383 struct randint_source
*randint_source
;
384 size_t *permutation
= nullptr;
387 initialize_main (&argc
, &argv
);
388 set_program_name (argv
[0]);
389 setlocale (LC_ALL
, "");
390 bindtextdomain (PACKAGE
, LOCALEDIR
);
391 textdomain (PACKAGE
);
393 atexit (close_stdout
);
395 while ((optc
= getopt_long (argc
, argv
, "ei:n:o:rz", long_opts
, nullptr))
406 error (EXIT_FAILURE
, 0, _("multiple -i options specified"));
411 strtol_error err
= xstrtoumax (optarg
, &lo_end
, 10, &u
, nullptr);
412 if (err
== LONGINT_OK
)
416 err
= LONGINT_OVERFLOW
;
417 else if (*lo_end
!= '-')
418 err
= LONGINT_INVALID
;
421 err
= xstrtoumax (lo_end
+ 1, nullptr, 10, &u
, "");
422 if (err
== LONGINT_OK
)
426 err
= LONGINT_OVERFLOW
;
431 n_lines
= hi_input
- lo_input
+ 1;
433 if (err
!= LONGINT_OK
|| (lo_input
<= hi_input
) == (n_lines
== 0))
434 error (EXIT_FAILURE
, err
== LONGINT_OVERFLOW
? EOVERFLOW
: 0,
435 "%s: %s", _("invalid input range"), quote (optarg
));
442 strtol_error e
= xstrtoumax (optarg
, nullptr, 10, &argval
, "");
445 head_lines
= MIN (head_lines
, argval
);
446 else if (e
!= LONGINT_OVERFLOW
)
447 error (EXIT_FAILURE
, 0, _("invalid line count: %s"),
453 if (outfile
&& !STREQ (outfile
, optarg
))
454 error (EXIT_FAILURE
, 0, _("multiple output files specified"));
458 case RANDOM_SOURCE_OPTION
:
459 if (random_source
&& !STREQ (random_source
, optarg
))
460 error (EXIT_FAILURE
, 0, _("multiple random sources specified"));
461 random_source
= optarg
;
472 case_GETOPT_HELP_CHAR
;
473 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
475 usage (EXIT_FAILURE
);
478 n_operands
= argc
- optind
;
479 operand
= argv
+ optind
;
481 /* Check invalid usage. */
482 if (echo
&& input_range
)
484 error (0, 0, _("cannot combine -e and -i options"));
485 usage (EXIT_FAILURE
);
487 if (input_range
? 0 < n_operands
: !echo
&& 1 < n_operands
)
489 error (0, 0, _("extra operand %s"), quote (operand
[!input_range
]));
490 usage (EXIT_FAILURE
);
501 input_from_argv (operand
, n_operands
, eolbyte
);
502 n_lines
= n_operands
;
505 else if (input_range
)
507 IF_LINT (n_lines
= hi_input
- lo_input
+ 1); /* Avoid GCC 10 warning. */
512 /* If an input file is specified, re-open it as stdin. */
514 && ! (STREQ (operand
[0], "-")
515 || freopen (operand
[0], "r", stdin
)))
516 error (EXIT_FAILURE
, errno
, "%s", quotef (operand
[0]));
518 fadvise (stdin
, FADVISE_SEQUENTIAL
);
520 if (repeat
|| head_lines
== MIN (IDX_MAX
, SIZE_MAX
)
521 || input_size () <= RESERVOIR_MIN_INPUT
)
523 n_lines
= read_input (stdin
, eolbyte
, &input_lines
);
528 use_reservoir_sampling
= true;
529 n_lines
= SIZE_MAX
; /* unknown number of input lines, for now. */
533 /* The adjusted head line count; can be less than HEAD_LINES if the
534 input is small and if not repeating. */
535 idx_t ahead_lines
= repeat
|| head_lines
< n_lines
? head_lines
: n_lines
;
537 randint_source
= randint_all_new (random_source
,
538 (use_reservoir_sampling
|| repeat
540 : randperm_bound (ahead_lines
, n_lines
)));
541 if (! randint_source
)
542 error (EXIT_FAILURE
, errno
, "%s",
543 quotef (random_source
? random_source
: "getrandom"));
545 if (use_reservoir_sampling
)
547 /* Instead of reading the entire file into 'line',
548 use reservoir-sampling to store just AHEAD_LINES random lines. */
549 n_lines
= read_input_reservoir_sampling (stdin
, eolbyte
, ahead_lines
,
550 randint_source
, &reservoir
);
551 ahead_lines
= n_lines
;
554 /* Close stdin now, rather than earlier, so that randint_all_new
555 doesn't have to worry about opening something other than
557 if (! (head_lines
== 0 || echo
|| input_range
|| fclose (stdin
) == 0))
558 error (EXIT_FAILURE
, errno
, _("read error"));
561 permutation
= randperm_new (randint_source
, ahead_lines
, n_lines
);
563 if (outfile
&& ! freopen (outfile
, "w", stdout
))
564 error (EXIT_FAILURE
, errno
, "%s", quotef (outfile
));
566 /* Generate output according to requested method */
574 error (EXIT_FAILURE
, 0, _("no lines to repeat"));
576 i
= write_random_numbers (randint_source
, ahead_lines
,
577 lo_input
, hi_input
, eolbyte
);
579 i
= write_random_lines (randint_source
, ahead_lines
, line
, n_lines
);
584 if (use_reservoir_sampling
)
585 i
= write_permuted_output_reservoir (n_lines
, reservoir
, permutation
);
586 else if (input_range
)
587 i
= write_permuted_numbers (ahead_lines
, lo_input
,
588 permutation
, eolbyte
);
590 i
= write_permuted_lines (ahead_lines
, line
, permutation
);
596 IF_LINT (randint_all_free (randint_source
)); /* For older valgrind. */
598 main_exit (EXIT_SUCCESS
);