util-linux/lsusb.c: print manufacturer/product strings if available
[busybox-git.git] / coreutils / sort.c
blob2e952f81c12ceb9844bffc40959cbe17f598707b
1 /* vi: set sw=4 ts=4: */
2 /*
3 * SuS3 compliant sort implementation for busybox
5 * Copyright (C) 2004 by Rob Landley <rob@landley.net>
7 * MAINTAINER: Rob Landley <rob@landley.net>
9 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
11 * See SuS3 sort standard at:
12 * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
14 //config:config SORT
15 //config: bool "sort (8.1 kb)"
16 //config: default y
17 //config: help
18 //config: sort is used to sort lines of text in specified files.
19 //config:
20 //config:config FEATURE_SORT_BIG
21 //config: bool "Full SuSv3 compliant sort (support -ktcbdfioghM)"
22 //config: default y
23 //config: depends on SORT
24 //config: help
25 //config: Without this, sort only supports -rusz, and an integer version
26 //config: of -n. Selecting this adds sort keys, floating point support, and
27 //config: more. This adds a little over 3k to a nonstatic build on x86.
28 //config:
29 //config: The SuSv3 sort standard is available at:
30 //config: http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
31 //config:
32 //config:config FEATURE_SORT_OPTIMIZE_MEMORY
33 //config: bool "Use less memory (but might be slower)"
34 //config: default n # defaults to N since we are size-paranoid tribe
35 //config: depends on SORT
36 //config: help
37 //config: Attempt to use less memory (by storing only one copy
38 //config: of duplicated lines, and such). Useful if you work on huge files.
40 //applet:IF_SORT(APPLET_NOEXEC(sort, sort, BB_DIR_USR_BIN, BB_SUID_DROP, sort))
42 //kbuild:lib-$(CONFIG_SORT) += sort.o
44 //usage:#define sort_trivial_usage
45 //usage: "[-nru"
46 //usage: IF_FEATURE_SORT_BIG("ghMcszbdfiokt] [-o FILE] [-k START[.OFS][OPTS][,END[.OFS][OPTS]] [-t CHAR")
47 //usage: "] [FILE]..."
48 //usage:#define sort_full_usage "\n\n"
49 //usage: "Sort lines of text\n"
50 //usage: IF_FEATURE_SORT_BIG(
51 //usage: "\n -o FILE Output to FILE"
52 //usage: "\n -c Check whether input is sorted"
53 //usage: "\n -b Ignore leading blanks"
54 //usage: "\n -f Ignore case"
55 //usage: "\n -i Ignore unprintable characters"
56 //usage: "\n -d Dictionary order (blank or alphanumeric only)"
57 //usage: )
58 //-h, --human-numeric-sort: compare human readable numbers (e.g., 2K 1G)
59 //usage: "\n -n Sort numbers"
60 //usage: IF_FEATURE_SORT_BIG(
61 //usage: "\n -g General numerical sort"
62 //usage: "\n -h Sort human readable numbers (2K 1G)"
63 //usage: "\n -M Sort month"
64 //usage: "\n -V Sort version"
65 //usage: "\n -t CHAR Field separator"
66 //usage: "\n -k N[,M] Sort by Nth field"
67 //usage: )
68 //usage: "\n -r Reverse sort order"
69 //usage: "\n -s Stable (don't sort ties alphabetically)"
70 //usage: "\n -u Suppress duplicate lines"
71 //usage: "\n -z NUL terminated input and output"
72 ///////: "\n -m Ignored for GNU compatibility"
73 ///////: "\n -S BUFSZ Ignored for GNU compatibility"
74 ///////: "\n -T TMPDIR Ignored for GNU compatibility"
75 //usage:
76 //usage:#define sort_example_usage
77 //usage: "$ echo -e \"e\\nf\\nb\\nd\\nc\\na\" | sort\n"
78 //usage: "a\n"
79 //usage: "b\n"
80 //usage: "c\n"
81 //usage: "d\n"
82 //usage: "e\n"
83 //usage: "f\n"
84 //usage: IF_FEATURE_SORT_BIG(
85 //usage: "$ echo -e \"c 3\\nb 2\\nd 2\" | $SORT -k 2,2n -k 1,1r\n"
86 //usage: "d 2\n"
87 //usage: "b 2\n"
88 //usage: "c 3\n"
89 //usage: )
90 //usage: ""
92 #include "libbb.h"
94 /* These are sort types */
95 enum {
96 FLAG_n = 1 << 0, /* Numeric sort */
97 FLAG_g = 1 << 1, /* Sort using strtod() */
98 FLAG_h = 1 << 2, /* Sort using strtod(), plus KMGT suffixes */
99 FLAG_M = 1 << 3, /* Sort date */
100 FLAG_V = 1 << 4, /* Sort version */
101 /* ucsz apply to root level only, not keys. b at root level implies bb */
102 FLAG_u = 1 << 5, /* Unique */
103 FLAG_c = 1 << 6, /* Check: no output, exit(!ordered) */
104 FLAG_s = 1 << 7, /* Stable sort, no ascii fallback at end */
105 FLAG_z = 1 << 8, /* Input and output is NUL terminated, not \n */
106 /* These can be applied to search keys, the previous four can't */
107 FLAG_b = 1 << 9, /* Ignore leading blanks */
108 FLAG_r = 1 << 10, /* Reverse */
109 FLAG_d = 1 << 11, /* Ignore !(isalnum()|isspace()) */
110 FLAG_f = 1 << 12, /* Force uppercase */
111 FLAG_i = 1 << 13, /* Ignore !isprint() */
112 FLAG_m = 1 << 14, /* ignored: merge already sorted files; do not sort */
113 FLAG_S = 1 << 15, /* ignored: -S, --buffer-size=SIZE */
114 FLAG_T = 1 << 16, /* ignored: -T, --temporary-directory=DIR */
115 FLAG_o = 1 << 17,
116 FLAG_k = 1 << 18,
117 FLAG_t = 1 << 19,
118 FLAG_bb = 0x80000000, /* Ignore trailing blanks */
119 FLAG_no_tie_break = 0x40000000,
122 static const char sort_opt_str[] ALIGN1 = "^"
123 "nghMVucszbrdfimS:T:o:k:*t:"
124 "\0" "o--o:t--t"/*-t, -o: at most one of each*/;
126 * OPT_STR must not be string literal, needs to have stable address:
127 * code uses "strchr(OPT_STR,c) - OPT_STR" idiom.
129 #define OPT_STR (sort_opt_str + 1)
131 #if ENABLE_FEATURE_SORT_BIG
132 static char key_separator;
134 static struct sort_key {
135 struct sort_key *next_key; /* linked list */
136 unsigned range[4]; /* start word, start char, end word, end char */
137 unsigned flags;
138 } *key_list;
141 /* This is a NOEXEC applet. Be very careful! */
144 static char *get_key(char *str, struct sort_key *key, int flags)
146 int start = start; /* for compiler */
147 int end;
148 int len, j;
149 unsigned i;
151 /* Special case whole string, so we don't have to make a copy */
152 if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
153 && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
155 return str;
158 /* Find start of key on first pass, end on second pass */
159 len = strlen(str);
160 for (j = 0; j < 2; j++) {
161 if (!key->range[2*j])
162 end = len;
163 /* Loop through fields */
164 else {
165 unsigned char ch = 0;
167 end = 0;
168 for (i = 1; i < key->range[2*j] + j; i++) {
169 if (key_separator) {
170 /* Skip body of key and separator */
171 while ((ch = str[end]) != '\0') {
172 end++;
173 if (ch == key_separator)
174 break;
176 } else {
177 /* Skip leading blanks */
178 while (isspace(str[end]))
179 end++;
180 /* Skip body of key */
181 while (str[end] != '\0') {
182 if (isspace(str[end]))
183 break;
184 end++;
188 /* Remove last delim: "abc:def:" => "abc:def" */
189 if (j && ch) {
190 //if (str[end-1] != key_separator)
191 // bb_error_msg(_and_die("BUG! "
192 // "str[start:%d,end:%d]:'%.*s'",
193 // start, end, (int)(end-start), &str[start]);
194 end--;
197 if (!j) start = end;
199 /* Strip leading whitespace if necessary */
200 if (flags & FLAG_b)
201 /* not using skip_whitespace() for speed */
202 while (isspace(str[start])) start++;
203 /* Strip trailing whitespace if necessary */
204 if (flags & FLAG_bb)
205 while (end > start && isspace(str[end-1])) end--;
206 /* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
207 if (key->range[3]) {
208 end = key->range[3];
209 if (end > len) end = len;
211 /* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
212 if (key->range[1]) {
213 start += key->range[1] - 1;
214 if (start > len) start = len;
216 /* Make the copy */
217 if (end < start)
218 end = start;
219 str = xstrndup(str+start, end-start);
220 /* Handle -d */
221 if (flags & FLAG_d) {
222 for (start = end = 0; str[end]; end++)
223 if (isspace(str[end]) || isalnum(str[end]))
224 str[start++] = str[end];
225 str[start] = '\0';
227 /* Handle -i */
228 if (flags & FLAG_i) {
229 for (start = end = 0; str[end]; end++)
230 if (isprint_asciionly(str[end]))
231 str[start++] = str[end];
232 str[start] = '\0';
234 /* Handle -f */
235 if (flags & FLAG_f)
236 for (i = 0; str[i]; i++)
237 str[i] = toupper(str[i]);
239 return str;
242 static struct sort_key *add_key(void)
244 struct sort_key **pkey = &key_list;
245 while (*pkey)
246 pkey = &((*pkey)->next_key);
247 return *pkey = xzalloc(sizeof(struct sort_key));
250 #define GET_LINE(fp) \
251 ((option_mask32 & FLAG_z) \
252 ? bb_get_chunk_from_file(fp, NULL) \
253 : xmalloc_fgetline(fp))
254 #else
255 #define GET_LINE(fp) xmalloc_fgetline(fp)
256 #endif
258 #if ENABLE_FEATURE_SORT_BIG
259 static int scale_suffix(const char *tail)
261 static const char suffix[] ALIGN1 = "kmgtpezy";
262 const char *s;
263 int n;
265 if (!tail[0])
266 return -1;
267 s = strchr(suffix, tail[0] | 0x20);
268 if (!s)
269 return -1;
270 n = s - suffix;
271 if (n != 0 && tail[0] >= 'a')
272 return -1; /* mg... not accepted, only MG... */
273 return n;
275 #endif
277 /* Iterate through keys list and perform comparisons */
278 static int compare_keys(const void *xarg, const void *yarg)
280 int flags = option_mask32, retval = 0;
281 char *x, *y;
283 #if ENABLE_FEATURE_SORT_BIG
284 struct sort_key *key;
286 for (key = key_list; !retval && key; key = key->next_key) {
287 flags = key->flags ? key->flags : option_mask32;
288 /* Chop out and modify key chunks, handling -dfib */
289 x = get_key(*(char **)xarg, key, flags);
290 y = get_key(*(char **)yarg, key, flags);
291 #else
292 /* This curly bracket serves no purpose but to match the nesting
293 * level of the for () loop we're not using */
295 x = *(char **)xarg;
296 y = *(char **)yarg;
297 #endif
298 /* Perform actual comparison */
299 switch (flags & (FLAG_n | FLAG_g | FLAG_h | FLAG_M | FLAG_V)) {
300 default:
301 bb_simple_error_msg_and_die("unknown sort type");
302 break;
303 #if defined(HAVE_STRVERSCMP) && HAVE_STRVERSCMP == 1
304 case FLAG_V:
305 retval = strverscmp(x, y);
306 break;
307 #endif
308 /* Ascii sort */
309 case 0:
310 #if ENABLE_LOCALE_SUPPORT
311 retval = strcoll(x, y);
312 #else
313 retval = strcmp(x, y);
314 #endif
315 break;
316 #if ENABLE_FEATURE_SORT_BIG
317 case FLAG_g:
318 case FLAG_h: {
319 char *xx, *yy;
320 //TODO: needs setlocale(LC_NUMERIC, "C")?
321 double dx = strtod(x, &xx);
322 double dy = strtod(y, &yy);
323 /* not numbers < NaN < -infinity < numbers < +infinity) */
324 if (x == xx)
325 retval = (y == yy ? 0 : -1);
326 else if (y == yy)
327 retval = 1;
328 /* Check for isnan */
329 else if (dx != dx)
330 retval = (dy != dy) ? 0 : -1;
331 else if (dy != dy)
332 retval = 1;
333 else {
334 if (flags & FLAG_h) {
335 int xs = scale_suffix(xx);
336 int ys = scale_suffix(yy);
337 if (xs != ys) {
338 retval = xs - ys;
339 break;
342 /* Check for infinity. Could underflow, but it avoids libm. */
343 if (1.0 / dx == 0.0) {
344 if (dx < 0)
345 retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
346 else
347 retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
348 } else if (1.0 / dy == 0.0)
349 retval = (dy < 0) ? 1 : -1;
350 else
351 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
353 break;
355 case FLAG_M: {
356 struct tm thyme;
357 int dx;
358 char *xx, *yy;
360 xx = strptime(skip_whitespace(x), "%b", &thyme);
361 dx = thyme.tm_mon;
362 yy = strptime(skip_whitespace(y), "%b", &thyme);
363 if (!xx)
364 retval = (!yy) ? 0 : -1;
365 else if (!yy)
366 retval = 1;
367 else
368 retval = dx - thyme.tm_mon;
369 break;
371 /* Full floating point version of -n */
372 case FLAG_n: {
373 double dx = atof(x);
374 double dy = atof(y);
375 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
376 break;
378 } /* switch */
379 /* Free key copies. */
380 if (x != *(char **)xarg) free(x);
381 if (y != *(char **)yarg) free(y);
382 /* if (retval) break; - done by for () anyway */
383 #else
384 /* Integer version of -n for tiny systems */
385 case FLAG_n:
386 retval = atoi(x) - atoi(y);
387 break;
388 } /* switch */
389 #endif
390 } /* for */
392 if (retval == 0) {
393 /* So far lines are "the same" */
395 if (option_mask32 & FLAG_s) {
396 /* "Stable sort": later line is "greater than",
397 * IOW: do not allow qsort() to swap equal lines.
399 uint32_t *p32;
400 uint32_t x32, y32;
401 char *line;
402 unsigned len;
404 line = *(char**)xarg;
405 len = (strlen(line) + 4) & (~3u);
406 p32 = (void*)(line + len);
407 x32 = *p32;
408 line = *(char**)yarg;
409 len = (strlen(line) + 4) & (~3u);
410 p32 = (void*)(line + len);
411 y32 = *p32;
413 /* If x > y, 1, else -1 */
414 retval = (x32 > y32) * 2 - 1;
415 /* Here, -r has no effect! */
416 return retval;
418 if (!(option_mask32 & FLAG_no_tie_break)) {
419 /* fallback sort */
420 flags = option_mask32;
421 retval = strcmp(*(char **)xarg, *(char **)yarg);
425 if (flags & FLAG_r)
426 return -retval;
428 return retval;
431 #if ENABLE_FEATURE_SORT_BIG
432 static unsigned str2u(char **str)
434 unsigned long lu;
435 if (!isdigit((*str)[0]))
436 bb_simple_error_msg_and_die("bad field specification");
437 lu = strtoul(*str, str, 10);
438 if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
439 bb_simple_error_msg_and_die("bad field specification");
440 return lu;
442 #endif
444 int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
445 int sort_main(int argc UNUSED_PARAM, char **argv)
447 char **lines;
448 char *str_ignored, *str_o, *str_t;
449 llist_t *lst_k = NULL;
450 int i;
451 int linecount;
452 unsigned opts;
453 #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
454 bool can_drop_dups;
455 size_t prev_len = 0;
456 char *prev_line = (char*) "";
457 /* Postpone optimizing if the input is small, < 16k lines:
458 * even just free()ing duplicate lines takes time.
460 size_t count_to_optimize_dups = 0x3fff;
461 #endif
463 xfunc_error_retval = 2;
465 /* Parse command line options */
466 opts = getopt32(argv,
467 sort_opt_str,
468 &str_ignored, &str_ignored, &str_o, &lst_k, &str_t
470 #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
471 /* Can drop dups only if -u but no "complicating" options,
472 * IOW: if we do a full line compares. Safe options:
473 * -o FILE Output to FILE
474 * -z Lines are terminated by NUL, not newline
475 * -r Reverse sort order
476 * -s Stable (don't sort ties alphabetically)
477 * Not sure about these:
478 * -b Ignore leading blanks
479 * -f Ignore case
480 * -i Ignore unprintable characters
481 * -d Dictionary order (blank or alphanumeric only)
482 * -n Sort numbers
483 * -g General numerical sort
484 * -M Sort month
486 can_drop_dups = ((opts & ~(FLAG_o|FLAG_z|FLAG_r|FLAG_s)) == FLAG_u);
487 /* Stable sort needs every line to be uniquely allocated,
488 * disable optimization to reuse strings:
490 if (opts & FLAG_s)
491 count_to_optimize_dups = (size_t)-1L;
492 #endif
493 /* global b strips leading and trailing spaces */
494 if (opts & FLAG_b)
495 option_mask32 |= FLAG_bb;
496 #if ENABLE_FEATURE_SORT_BIG
497 if (opts & FLAG_t) {
498 if (!str_t[0] || str_t[1])
499 bb_simple_error_msg_and_die("bad -t parameter");
500 key_separator = str_t[0];
502 /* note: below this point we use option_mask32, not opts,
503 * since that reduces register pressure and makes code smaller */
505 /* Parse sort key */
506 while (lst_k) {
507 enum {
508 FLAG_allowed_for_k =
509 FLAG_n | /* Numeric sort */
510 FLAG_g | /* Sort using strtod() */
511 FLAG_h | /* Sort using strtod(), plus KMGT suffixes */
512 FLAG_M | /* Sort date */
513 FLAG_b | /* Ignore leading blanks */
514 FLAG_r | /* Reverse */
515 FLAG_d | /* Ignore !(isalnum()|isspace()) */
516 FLAG_f | /* Force uppercase */
517 FLAG_i | /* Ignore !isprint() */
520 struct sort_key *key = add_key();
521 char *str_k = llist_pop(&lst_k);
523 i = 0; /* i==0 before comma, 1 after (-k3,6) */
524 while (*str_k) {
525 /* Start of range */
526 /* Cannot use bb_strtou - suffix can be a letter */
527 key->range[2*i] = str2u(&str_k);
528 if (*str_k == '.') {
529 str_k++;
530 key->range[2*i+1] = str2u(&str_k);
532 while (*str_k) {
533 int flag;
534 const char *idx;
536 if (*str_k == ',' && !i++) {
537 str_k++;
538 break;
539 } /* no else needed: fall through to syntax error
540 because comma isn't in OPT_STR */
541 idx = strchr(OPT_STR, *str_k);
542 if (!idx)
543 bb_simple_error_msg_and_die("unknown key option");
544 flag = 1 << (idx - OPT_STR);
545 if (flag & ~FLAG_allowed_for_k)
546 bb_simple_error_msg_and_die("unknown sort type");
547 /* b after ',' means strip _trailing_ space */
548 if (i && flag == FLAG_b)
549 flag = FLAG_bb;
550 key->flags |= flag;
551 str_k++;
555 #endif
557 /* Open input files and read data */
558 argv += optind;
559 if (!*argv)
560 *--argv = (char*)"-";
561 linecount = 0;
562 lines = NULL;
563 do {
564 /* coreutils 6.9 compat: abort on first open error,
565 * do not continue to next file: */
566 FILE *fp = xfopen_stdin(*argv);
567 for (;;) {
568 char *line = GET_LINE(fp);
569 if (!line)
570 break;
572 #if ENABLE_FEATURE_SORT_OPTIMIZE_MEMORY
573 if (count_to_optimize_dups != 0)
574 count_to_optimize_dups--;
575 if (count_to_optimize_dups == 0) {
576 size_t len;
577 char *new_line;
579 /* On kernel/linux/arch/ *.[ch] files,
580 * this reduces memory usage by 6%.
581 * yes | head -99999999 | sort
582 * goes down from 1900Mb to 380 Mb.
584 len = strlen(line);
585 if (len <= prev_len) {
586 new_line = prev_line + (prev_len - len);
587 if (strcmp(line, new_line) == 0) {
588 /* it's a tail of the prev line */
589 if (can_drop_dups && prev_len == len) {
590 /* it's identical to prev line */
591 free(line);
592 continue;
594 free(line);
595 line = new_line;
596 /* continue using longer prev_line
597 * for future tail tests.
599 goto skip;
602 prev_len = len;
603 prev_line = line;
604 skip: ;
606 #else
607 //TODO: lighter version which only drops total dups if can_drop_dups == true
608 #endif
609 lines = xrealloc_vector(lines, 6, linecount);
610 lines[linecount++] = line;
612 fclose_if_not_stdin(fp);
613 } while (*++argv);
615 #if ENABLE_FEATURE_SORT_BIG
616 /* If no key, perform alphabetic sort */
617 if (!key_list)
618 add_key()->range[0] = 1;
619 /* Handle -c */
620 if (option_mask32 & FLAG_c) {
621 int j = (option_mask32 & FLAG_u) ? -1 : 0;
622 for (i = 1; i < linecount; i++) {
623 if (compare_keys(&lines[i-1], &lines[i]) > j) {
624 fprintf(stderr, "Check line %u\n", i);
625 return EXIT_FAILURE;
628 return EXIT_SUCCESS;
630 #endif
632 /* For stable sort, store original line position beyond terminating NUL */
633 if (option_mask32 & FLAG_s) {
634 for (i = 0; i < linecount; i++) {
635 uint32_t *p32;
636 char *line;
637 unsigned len;
639 line = lines[i];
640 len = (strlen(line) + 4) & (~3u);
641 lines[i] = line = xrealloc(line, len + 4);
642 p32 = (void*)(line + len);
643 *p32 = i;
645 /*option_mask32 |= FLAG_no_tie_break;*/
646 /* ^^^redundant: if FLAG_s, compare_keys() does no tie break */
649 /* Perform the actual sort */
650 qsort(lines, linecount, sizeof(lines[0]), compare_keys);
652 /* Handle -u */
653 if (option_mask32 & FLAG_u) {
654 int j = 0;
655 /* coreutils 6.3 drop lines for which only key is the same:
656 * - disabling last-resort compare, or else compare_keys()
657 * will be the same only for completely identical lines
658 * - disabling -s (same reasons)
660 option_mask32 = (option_mask32 | FLAG_no_tie_break) & (~FLAG_s);
661 for (i = 1; i < linecount; i++) {
662 if (compare_keys(&lines[j], &lines[i]) == 0)
663 free(lines[i]);
664 else
665 lines[++j] = lines[i];
667 if (linecount)
668 linecount = j+1;
671 /* Print it */
672 #if ENABLE_FEATURE_SORT_BIG
673 /* Open output file _after_ we read all input ones */
674 if (option_mask32 & FLAG_o)
675 xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
676 #endif
678 int ch = (option_mask32 & FLAG_z) ? '\0' : '\n';
679 for (i = 0; i < linecount; i++)
680 printf("%s%c", lines[i], ch);
683 fflush_stdout_and_exit_SUCCESS();