1 /* vi: set sw=4 ts=4: */
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 tarball for details.
11 * See SuS3 sort standard at:
12 * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
18 sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
19 sort -c [-bdfinru][-t char][-k keydef][file]
22 /* These are sort types */
23 static const char OPT_STR[] = "ngMucszbrdfimS:T:o:k:t:";
25 FLAG_n = 1, /* Numeric sort */
26 FLAG_g = 2, /* Sort using strtod() */
27 FLAG_M = 4, /* Sort date */
28 /* ucsz apply to root level only, not keys. b at root level implies bb */
29 FLAG_u = 8, /* Unique */
30 FLAG_c = 0x10, /* Check: no output, exit(!ordered) */
31 FLAG_s = 0x20, /* Stable sort, no ascii fallback at end */
32 FLAG_z = 0x40, /* Input is null terminated, not \n */
33 /* These can be applied to search keys, the previous four can't */
34 FLAG_b = 0x80, /* Ignore leading blanks */
35 FLAG_r = 0x100, /* Reverse */
36 FLAG_d = 0x200, /* Ignore !(isalnum()|isspace()) */
37 FLAG_f = 0x400, /* Force uppercase */
38 FLAG_i = 0x800, /* Ignore !isprint() */
39 FLAG_m = 0x1000, /* ignored: merge already sorted files; do not sort */
40 FLAG_S = 0x2000, /* ignored: -S, --buffer-size=SIZE */
41 FLAG_T = 0x4000, /* ignored: -T, --temporary-directory=DIR */
45 FLAG_bb = 0x80000000, /* Ignore trailing blanks */
48 #if ENABLE_FEATURE_SORT_BIG
49 static char key_separator;
51 static struct sort_key {
52 struct sort_key *next_key; /* linked list */
53 unsigned range[4]; /* start word, start char, end word, end char */
57 static char *get_key(char *str, struct sort_key *key, int flags)
59 int start = 0, end = 0, len, i, j;
61 /* Special case whole string, so we don't have to make a copy */
62 if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
63 && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
68 /* Find start of key on first pass, end on second pass */
70 for (j = 0; j < 2; j++) {
73 /* Loop through fields */
76 for (i = 1; i < key->range[2*j] + j; i++) {
78 /* Skip body of key and separator */
80 if (str[end++] == key_separator)
84 /* Skip leading blanks */
85 while (isspace(str[end]))
87 /* Skip body of key */
89 if (isspace(str[end]))
98 /* Strip leading whitespace if necessary */
99 //XXX: skip_whitespace()
101 while (isspace(str[start])) start++;
102 /* Strip trailing whitespace if necessary */
104 while (end > start && isspace(str[end-1])) end--;
105 /* Handle offsets on start and end */
107 end += key->range[3] - 1;
108 if (end > len) end = len;
111 start += key->range[1] - 1;
112 if (start > len) start = len;
115 if (end < start) end = start;
116 str = xstrndup(str+start, end-start);
118 if (flags & FLAG_d) {
119 for (start = end = 0; str[end]; end++)
120 if (isspace(str[end]) || isalnum(str[end]))
121 str[start++] = str[end];
125 if (flags & FLAG_i) {
126 for (start = end = 0; str[end]; end++)
127 if (isprint(str[end]))
128 str[start++] = str[end];
133 for (i = 0; str[i]; i++)
134 str[i] = toupper(str[i]);
139 static struct sort_key *add_key(void)
141 struct sort_key **pkey = &key_list;
143 pkey = &((*pkey)->next_key);
144 return *pkey = xzalloc(sizeof(struct sort_key));
147 #define GET_LINE(fp) \
148 ((option_mask32 & FLAG_z) \
149 ? bb_get_chunk_from_file(fp, NULL) \
150 : xmalloc_getline(fp))
152 #define GET_LINE(fp) xmalloc_getline(fp)
155 /* Iterate through keys list and perform comparisons */
156 static int compare_keys(const void *xarg, const void *yarg)
158 int flags = option_mask32, retval = 0;
161 #if ENABLE_FEATURE_SORT_BIG
162 struct sort_key *key;
164 for (key = key_list; !retval && key; key = key->next_key) {
165 flags = key->flags ? key->flags : option_mask32;
166 /* Chop out and modify key chunks, handling -dfib */
167 x = get_key(*(char **)xarg, key, flags);
168 y = get_key(*(char **)yarg, key, flags);
170 /* This curly bracket serves no purpose but to match the nesting
171 level of the for () loop we're not using */
176 /* Perform actual comparison */
179 bb_error_msg_and_die("unknown sort type");
183 #if ENABLE_LOCALE_SUPPORT
184 retval = strcoll(x, y);
186 retval = strcmp(x, y);
189 #if ENABLE_FEATURE_SORT_BIG
192 double dx = strtod(x, &xx);
193 double dy = strtod(y, &yy);
194 /* not numbers < NaN < -infinity < numbers < +infinity) */
196 retval = (y == yy ? 0 : -1);
199 /* Check for isnan */
201 retval = (dy != dy) ? 0 : -1;
204 /* Check for infinity. Could underflow, but it avoids libm. */
205 else if (1.0 / dx == 0.0) {
207 retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
209 retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
210 } else if (1.0 / dy == 0.0)
211 retval = (dy < 0) ? 1 : -1;
213 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
221 xx = strptime(x, "%b", &thyme);
223 yy = strptime(y, "%b", &thyme);
225 retval = (!yy) ? 0 : -1;
229 retval = (dx == thyme.tm_mon) ? 0 : dx - thyme.tm_mon;
232 /* Full floating point version of -n */
236 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
240 /* Free key copies. */
241 if (x != *(char **)xarg) free(x);
242 if (y != *(char **)yarg) free(y);
243 /* if (retval) break; - done by for () anyway */
245 /* Integer version of -n for tiny systems */
247 retval = atoi(x) - atoi(y);
253 /* Perform fallback sort if necessary */
254 if (!retval && !(option_mask32 & FLAG_s))
255 retval = strcmp(*(char **)xarg, *(char **)yarg);
257 if (flags & FLAG_r) return -retval;
261 #if ENABLE_FEATURE_SORT_BIG
262 static unsigned str2u(char **str)
265 if (!isdigit((*str)[0]))
266 bb_error_msg_and_die("bad field specification");
267 lu = strtoul(*str, str, 10);
268 if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
269 bb_error_msg_and_die("bad field specification");
274 int sort_main(int argc, char **argv);
275 int sort_main(int argc, char **argv)
277 FILE *fp, *outfile = stdout;
278 char *line, **lines = NULL;
279 char *str_ignored, *str_o, *str_t;
280 llist_t *lst_k = NULL;
284 xfunc_error_retval = 2;
286 /* Parse command line options */
287 /* -o and -t can be given at most once */
288 opt_complementary = "?:o--o:t--t:" /* -t, -o: maximum one of each */
289 "k::"; /* -k takes list */
290 getopt32(argc, argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &lst_k, &str_t);
291 #if ENABLE_FEATURE_SORT_BIG
292 if (option_mask32 & FLAG_o) outfile = xfopen(str_o, "w");
293 if (option_mask32 & FLAG_t) {
294 if (!str_t[0] || str_t[1])
295 bb_error_msg_and_die("bad -t parameter");
296 key_separator = str_t[0];
299 lst_k = llist_rev(lst_k);
303 FLAG_n | /* Numeric sort */
304 FLAG_g | /* Sort using strtod() */
305 FLAG_M | /* Sort date */
306 FLAG_b | /* Ignore leading blanks */
307 FLAG_r | /* Reverse */
308 FLAG_d | /* Ignore !(isalnum()|isspace()) */
309 FLAG_f | /* Force uppercase */
310 FLAG_i | /* Ignore !isprint() */
313 struct sort_key *key = add_key();
314 char *str_k = lst_k->data;
317 i = 0; /* i==0 before comma, 1 after (-k3,6) */
320 /* Cannot use bb_strtou - suffix can be a letter */
321 key->range[2*i] = str2u(&str_k);
324 key->range[2*i+1] = str2u(&str_k);
327 if (*str_k == ',' && !i++) {
330 } /* no else needed: fall through to syntax error
331 because comma isn't in OPT_STR */
332 temp2 = strchr(OPT_STR, *str_k);
334 bb_error_msg_and_die("unknown key option");
335 flag = 1 << (temp2 - OPT_STR);
336 if (flag & ~FLAG_allowed_for_k)
337 bb_error_msg_and_die("unknown sort type");
338 /* b after ',' means strip _trailing_ space */
339 if (i && flag == FLAG_b) flag = FLAG_bb;
344 /* leaking lst_k... */
348 /* global b strips leading and trailing spaces */
349 if (option_mask32 & FLAG_b) option_mask32 |= FLAG_bb;
351 /* Open input files and read data */
352 for (i = argv[optind] ? optind : optind-1; argv[i]; i++) {
354 if (i >= optind && NOT_LONE_DASH(argv[i]))
355 fp = xfopen(argv[i], "r");
359 if (!(linecount & 63))
360 lines = xrealloc(lines, sizeof(char *) * (linecount + 64));
361 lines[linecount++] = line;
365 #if ENABLE_FEATURE_SORT_BIG
366 /* if no key, perform alphabetic sort */
368 add_key()->range[0] = 1;
370 if (option_mask32 & FLAG_c) {
371 int j = (option_mask32 & FLAG_u) ? -1 : 0;
372 for (i = 1; i < linecount; i++)
373 if (compare_keys(&lines[i-1], &lines[i]) > j) {
374 fprintf(stderr, "Check line %d\n", i);
380 /* Perform the actual sort */
381 qsort(lines, linecount, sizeof(char *), compare_keys);
383 if (option_mask32 & FLAG_u) {
385 /* coreutils 6.3 drop lines for which only key is the same */
386 /* -- disabling last-resort compare... */
387 option_mask32 |= FLAG_s;
388 for (i = 1; i < linecount; i++) {
389 if (!compare_keys(&lines[flag], &lines[i]))
392 lines[++flag] = lines[i];
394 if (linecount) linecount = flag+1;
397 for (i = 0; i < linecount; i++)
398 fprintf(outfile, "%s\n", lines[i]);
400 fflush_stdout_and_exit(EXIT_SUCCESS);