File: unsort.c

package info (click to toggle)
unsort 1.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, sid, stretch
  • size: 532 kB
  • ctags: 134
  • sloc: ansic: 1,401; sh: 1,042; makefile: 5
file content (345 lines) | stat: -rw-r--r-- 8,941 bytes parent folder | download
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*****************************************************************************

	unsort - reorder files semi-randomly
	Copyright (C) 2007, 2008  Wessel Dankers <wsl@fruit.je>

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*****************************************************************************/

#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/uio.h>

#include "error.h"
#include "filebuf.h"
#include "iovec.h"
#include "shuffle.h"
#include "lsort.h"
#include "merge.h"
#include "msort.h"
#include "unfind.h"
#include "mt19937ar.h"
#include "mt19937ar_init.h"

#ifndef O_LARGEFILE
#define O_LARGEFILE 0
#endif

#ifndef VERSION
#define VERSION "git"
#endif

static const struct option long_options[] = {
	{"help\0               Print this message to stdout", 0, 0, 'h'},
	{"version\0            Print the program version", 0, 0, 'v'},
	{"random\0             Use a random permutation", 0, 0, 'r'},
	{"filenames\0[=<sub>]  Permute as if the input were filenames", 2, 0, 'f'},
	{"separator\0 <sep>    Filename separator for -f", 1, 0, 'S'},
	{"heuristic\0          Use a heuristic permutation (default)", 0, 0, 'p'},
	{"identity\0           Do not change the order of lines", 0, 0, 'n'},
	{"concatenate\0        Concatenate input before shuffling", 0, 0, 'c'},
	{"merge\0              Merge input after shuffling in given order", 0, 0, 'm'},
	{"merge-random\0       Merge input after shuffling (default)", 0, 0, 'M'},
	{"seed\0 <integer>     Seed the permutation", 1, 0, 's'},
	{"zero-terminated\0    Use \\0 line endings", 0, 0, 'z'},
	{"null\0               Use \\0 line endings", 0, 0, '0'},
	{"linefeed\0           Use \\n line endings (default)", 0, 0, 'l'},
	{0, 0, 0, 0}
};

static void usage(FILE *fh, const char *progname) {
	int i;
	fprintf(fh, "Usage: %s [-", progname);
	for(i = 0; long_options[i].name; i++)
		if(long_options[i].val && !long_options[i].has_arg)
			fputc(long_options[i].val, fh);
	fprintf(fh, "] [-s <integer>] [-f [strategy]] [file...]\n");
	for(i = 0; long_options[i].name; i++)
		fprintf(fh, "\t-%c, --%s%s\n",
			long_options[i].val,
			long_options[i].name,
			long_options[i].name + strlen(long_options[i].name) + 1);
}

static void fsck(const uint32_t *tlb, uint32_t count) {
	uint32_t *tmp;
	uint32_t u;

	tmp = xalloc(count * sizeof *tmp);
	memcpy(tmp, tlb, count * sizeof *tmp);
	msort32(tmp, count);

	for(u = 0; u < count; u++)
		if(tmp[u] != u)
			exit_error(ERROR_INTERNAL, "Bad tlb");

	free(tmp);
}

static void get_short_options(const struct option *lo, char *buf) {
	int i;
	*buf++ = ':';
	while(lo->name) {
		i = lo->val;
		if(i) {
			*buf++ = (char)i;
			i = lo->has_arg;
			while(i--)
				*buf++ = ':';
		}
		lo++;
	}
	*buf++ = '\0';
}

int main(int argc, char **argv) {
	int i, fd, option_index;
	char short_options[32];
	struct iovec *iov;
	uint32_t u, numfiles, count, chunk_count, chunk_start;
	uint32_t *tlb, *tmp, *bounce;
	filebuf_t *fb, *ds;
	merge_t *mg, *ms;
	unsigned long ul;

	uint32_t seed = 0;
	bool manual_seed = false;
	bool multi = true;
	shuffle_algo_t shuffle_algo = shuffle_heuristic;
	__attribute__((unused))
	bool shuffle_files = true;
	bool shuffle_unfind = false;
	char *end;
	int sep = '\n';

	get_short_options(long_options, short_options);

	opterr = 0;
	while((i = getopt_long(argc, argv, short_options, long_options, &option_index)) != EOF) {
		switch(i) {
			case 'h':
				puts("unsort - reorder files semi-randomly");
				usage(stdout, *argv);
				exit(ERROR_NONE);
			case 'v':
				printf("unsort %s\ncopyright 2007, 2008 Wessel Dankers <wsl@fruit.je>\n", VERSION);
				exit(ERROR_NONE);
			case 'r':
				shuffle_algo = shuffle_random;
				break;
			case 'p':
				shuffle_algo = shuffle_heuristic;
				break;
			case 'n':
				shuffle_algo = shuffle_none;
				break;
			case 'c':
				multi = false;
				break;
			case 'm':
				multi = true;
				shuffle_files = false;
				break;
			case 'M':
				multi = true;
				shuffle_files = true;
				break;
			case 'f':
				shuffle_unfind = true;
				if(optarg && *optarg) {
					for(u = 0; optarg[u]; u++)
						if(!strchr("1n", optarg[u]))
							exit_error(ERROR_USER, "Invalid value '%s' for -%c", optarg, optopt);
					unfind_strategy = optarg;
				}
				break;
			case 'S':
				if(!optarg || !*optarg)
					exit_error(ERROR_USER, "Missing or invalid value for -%c", optopt);
				if(optarg[1]) {
					if(*optarg != '\\')
						exit_error(ERROR_USER, "Invalid value '%s' for -%c", optarg, optopt);
					ul = strtoul(optarg, &end, 0);
					if(*end || ul > UINT8_MAX)
						exit_error(ERROR_USER, "Invalid value '%s' for -%c", optarg, optopt);
					unfind_sep = (uint8_t)ul;
				} else {
					unfind_sep = *(uint8_t *)optarg;
				}
				break;
			case 's':
				if(optarg && *optarg) {
					errno = 0;
					seed = (uint32_t)strtoul(optarg, &end, 0);
					if(errno)
						exit_perror(ERROR_USER, "Can't parse seed '%s' as an unsigned integer", optarg);
					if(end && *end)
						exit_error(ERROR_USER, "Can't parse seed '%s' as an unsigned integer", optarg);
					manual_seed = true;
				} else {
					seed = UINT32_C(0);
					manual_seed = false;
				}
				break;
			case '0':
			case 'z':
				sep = '\0';
				break;
			case 'l':
				sep = '\n';
				break;
			case '?':
				usage(stderr, *argv);
				exit_error(ERROR_USER, "Unknown option: -%c", optopt);
			case ':':
				usage(stderr, *argv);
				exit_error(ERROR_USER, "Option -%c requires an argument", optopt);
			default:
				usage(stderr, *argv);
				exit_error(ERROR_INTERNAL, "Unknown option: -%c", i);
		}
	}

	if(argc > optind)
		numfiles = (uint32_t)(argc - optind);
	else
		numfiles = 1;

	if(manual_seed) {
		mt_seed(seed);
	} else {
		if(!mt_init_urandom())
			exit_perror(ERROR_SYSTEM, "Can't read from /dev/urandom");
		seed = mt_genrand32();
	}
	shuffle_seed(seed);
	merge_seed(seed);

	ms = xalloc(numfiles * sizeof *ms);
	ds = xalloc(numfiles * sizeof *ds);
	tlb = (uint32_t *)ds;

	if(argc > optind) {
		numfiles = 0;
		for(i = optind; i < argc; i++) {
			fb = ds + numfiles;
			*fb = filebuf_0;
			if(strcmp(argv[i], "-")) {
				fd = open(argv[i], O_RDONLY | O_LARGEFILE);
				if(fd == -1) {
					warn_perror("Can't open %s", argv[i]);
					continue;
				}
				filebuf_init(fb, fd);
				close(fd);
				fb->name = argv[i];
			} else {
				filebuf_init(fb, STDIN_FILENO);
			}
			numfiles++;
		}
	} else {
		numfiles = 1;
		filebuf_init(ds, STDIN_FILENO);
	}

	count = 0;
	for(u = 0; u < numfiles; u++) {
		fb = ds + u;
		mg = ms + u;
		*mg = merge_0;
		if(iovec_parse(fb, sep, NULL, &chunk_count)) {
			if(fb->name)
				warn_error("%s: missing linebreak at end of file – line skipped", fb->name);
			else
				warn_error("missing linebreak at end of input – line skipped");
		}
		mg->start = count;
		mg->count = chunk_count;
		mg->ratio = 1; /* chunk_count */
		count += chunk_count;
	}

	if(!count)
		return 0;

	iov = xalloc(count * sizeof *iov);

	count = 0;
	for(u = 0; u < numfiles; u++) {
		iovec_parse(ds + u, sep, iov + count, &chunk_count);
		count += chunk_count;
	}

	tlb = xalloc(count * sizeof *tlb);

	bounce = xalloc((size_t)count * sizeof *bounce);
	tmp = xalloc((size_t)count * sizeof *tmp);
	shuffle_tmp(tmp);

	if(multi && numfiles > 1) {
		if(shuffle_unfind) {
			merge(ms, numfiles, NULL, tlb, shuffle_algo != shuffle_none);
			for(u = 0; u < numfiles; u++) {
				mg = ms + u;
				chunk_start = mg->start;
				chunk_count = mg->count;
				lsort(iov + chunk_start, chunk_count);
				unfind(iov + chunk_start, chunk_count, tlb + chunk_start, bounce, shuffle_algo);
			}
		} else {
			merge(ms, numfiles, NULL, bounce, shuffle_algo != shuffle_none);
			for(u = 0; u < numfiles; u++) {
				mg = ms + u;
				chunk_start = mg->start;
				chunk_count = mg->count;
				shuffle_algo(bounce + chunk_start, tlb + chunk_start, chunk_count);
			}
		}
	} else {
		if(shuffle_unfind) {
			shuffle_init(tlb, count);
			lsort(iov, count);
			unfind(iov, count, tlb, bounce, shuffle_algo);
		} else {
			shuffle_algo(NULL, tlb, count);
		}
	}
	shuffle_tmp(NULL);
	free(tmp);
	free(bounce);

	if(getenv("UNSORT_FSCK"))
		fsck(tlb, count);

	iovec_shuffle(iov, tlb, count);
	iovec_write(STDOUT_FILENO, iov, count);

	free(ms);
	free(ds);
	free(iov);
	free(tlb);

	return 0;
}