cmdedit: small optimizations
[oweals/busybox.git] / coreutils / sort.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * SuS3 compliant sort implementation for busybox
4  *
5  * Copyright (C) 2004 by Rob Landley <rob@landley.net>
6  *
7  * MAINTAINER: Rob Landley <rob@landley.net>
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10  *
11  * See SuS3 sort standard at:
12  * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
13  */
14
15 #include "busybox.h"
16
17 /*
18         sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
19         sort -c [-bdfinru][-t char][-k keydef][file]
20 */
21
22 /* These are sort types */
23 static const char OPT_STR[] = "ngMucszbrdfimS:T:o:k:t:";
24 enum {
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 */
42         FLAG_o  = 0x8000,
43         FLAG_k  = 0x10000,
44         FLAG_t  = 0x20000,
45         FLAG_bb = 0x80000000,   /* Ignore trailing blanks  */
46 };
47
48 #if ENABLE_FEATURE_SORT_BIG
49 static char key_separator;
50
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 */
54         unsigned flags;
55 } *key_list;
56
57 static char *get_key(char *str, struct sort_key *key, int flags)
58 {
59         int start = 0, end = 0, len, i, j;
60
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))
64         ) {
65                 return str;
66         }
67
68         /* Find start of key on first pass, end on second pass */
69         len = strlen(str);
70         for (j = 0; j < 2; j++) {
71                 if (!key->range[2*j])
72                         end = len;
73                 /* Loop through fields */
74                 else {
75                         end = 0;
76                         for (i = 1; i < key->range[2*j] + j; i++) {
77                                 if (key_separator) {
78                                         /* Skip body of key and separator */
79                                         while (str[end]) {
80                                                 if (str[end++] == key_separator)
81                                                         break;
82                                         }
83                                 } else {
84                                         /* Skip leading blanks */
85                                         while (isspace(str[end]))
86                                                 end++;
87                                         /* Skip body of key */
88                                         while (str[end]) {
89                                                 if (isspace(str[end]))
90                                                         break;
91                                                 end++;
92                                         }
93                                 }
94                         }
95                 }
96                 if (!j) start = end;
97         }
98         /* Strip leading whitespace if necessary */
99 //XXX: skip_whitespace()
100         if (flags & FLAG_b)
101                 while (isspace(str[start])) start++;
102         /* Strip trailing whitespace if necessary */
103         if (flags & FLAG_bb)
104                 while (end > start && isspace(str[end-1])) end--;
105         /* Handle offsets on start and end */
106         if (key->range[3]) {
107                 end += key->range[3] - 1;
108                 if (end > len) end = len;
109         }
110         if (key->range[1]) {
111                 start += key->range[1] - 1;
112                 if (start > len) start = len;
113         }
114         /* Make the copy */
115         if (end < start) end = start;
116         str = xstrndup(str+start, end-start);
117         /* Handle -d */
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];
122                 str[start] = '\0';
123         }
124         /* Handle -i */
125         if (flags & FLAG_i) {
126                 for (start = end = 0; str[end]; end++)
127                         if (isprint(str[end]))
128                                 str[start++] = str[end];
129                 str[start] = '\0';
130         }
131         /* Handle -f */
132         if (flags & FLAG_f)
133                 for (i = 0; str[i]; i++)
134                         str[i] = toupper(str[i]);
135
136         return str;
137 }
138
139 static struct sort_key *add_key(void)
140 {
141         struct sort_key **pkey = &key_list;
142         while (*pkey)
143                 pkey = &((*pkey)->next_key);
144         return *pkey = xzalloc(sizeof(struct sort_key));
145 }
146
147 #define GET_LINE(fp) \
148         ((option_mask32 & FLAG_z) \
149         ? bb_get_chunk_from_file(fp, NULL) \
150         : xmalloc_getline(fp))
151 #else
152 #define GET_LINE(fp) xmalloc_getline(fp)
153 #endif
154
155 /* Iterate through keys list and perform comparisons */
156 static int compare_keys(const void *xarg, const void *yarg)
157 {
158         int flags = option_mask32, retval = 0;
159         char *x, *y;
160
161 #if ENABLE_FEATURE_SORT_BIG
162         struct sort_key *key;
163
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);
169 #else
170         /* This curly bracket serves no purpose but to match the nesting
171            level of the for () loop we're not using */
172         {
173                 x = *(char **)xarg;
174                 y = *(char **)yarg;
175 #endif
176                 /* Perform actual comparison */
177                 switch (flags & 7) {
178                 default:
179                         bb_error_msg_and_die("unknown sort type");
180                         break;
181                 /* Ascii sort */
182                 case 0:
183 #if ENABLE_LOCALE_SUPPORT
184                         retval = strcoll(x, y);
185 #else
186                         retval = strcmp(x, y);
187 #endif
188                         break;
189 #if ENABLE_FEATURE_SORT_BIG
190                 case FLAG_g: {
191                         char *xx, *yy;
192                         double dx = strtod(x, &xx);
193                         double dy = strtod(y, &yy);
194                         /* not numbers < NaN < -infinity < numbers < +infinity) */
195                         if (x == xx)
196                                 retval = (y == yy ? 0 : -1);
197                         else if (y == yy)
198                                 retval = 1;
199                         /* Check for isnan */
200                         else if (dx != dx)
201                                 retval = (dy != dy) ? 0 : -1;
202                         else if (dy != dy)
203                                 retval = 1;
204                         /* Check for infinity.  Could underflow, but it avoids libm. */
205                         else if (1.0 / dx == 0.0) {
206                                 if (dx < 0)
207                                         retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
208                                 else
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;
212                         else
213                                 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
214                         break;
215                 }
216                 case FLAG_M: {
217                         struct tm thyme;
218                         int dx;
219                         char *xx, *yy;
220
221                         xx = strptime(x, "%b", &thyme);
222                         dx = thyme.tm_mon;
223                         yy = strptime(y, "%b", &thyme);
224                         if (!xx)
225                                 retval = (!yy) ? 0 : -1;
226                         else if (!yy)
227                                 retval = 1;
228                         else
229                                 retval = (dx == thyme.tm_mon) ? 0 : dx - thyme.tm_mon;
230                         break;
231                 }
232                 /* Full floating point version of -n */
233                 case FLAG_n: {
234                         double dx = atof(x);
235                         double dy = atof(y);
236                         retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
237                         break;
238                 }
239                 } /* switch */
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 */
244 #else
245                 /* Integer version of -n for tiny systems */
246                 case FLAG_n:
247                         retval = atoi(x) - atoi(y);
248                         break;
249                 } /* switch */
250 #endif
251         } /* for */
252
253         /* Perform fallback sort if necessary */
254         if (!retval && !(option_mask32 & FLAG_s))
255                 retval = strcmp(*(char **)xarg, *(char **)yarg);
256
257         if (flags & FLAG_r) return -retval;
258         return retval;
259 }
260
261 #if ENABLE_FEATURE_SORT_BIG
262 static unsigned str2u(char **str)
263 {
264         unsigned long lu;
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");
270         return lu;
271 }
272 #endif
273
274 int sort_main(int argc, char **argv)
275 {
276         FILE *fp, *outfile = stdout;
277         char *line, **lines = NULL;
278         char *str_ignored, *str_o, *str_k, *str_t;
279         int i, flag;
280         int linecount = 0;
281
282         xfunc_error_retval = 2;
283
284         /* Parse command line options */
285         /* -o and -t can be given at most once */
286         opt_complementary = "?:o--o:t--t";
287         getopt32(argc, argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &str_k, &str_t);
288 #if ENABLE_FEATURE_SORT_BIG
289         if (option_mask32 & FLAG_o) outfile = xfopen(str_o, "w");
290         if (option_mask32 & FLAG_t) {
291                 if (!str_t[0] || str_t[1])
292                         bb_error_msg_and_die("bad -t parameter");
293                 key_separator = str_t[0];
294         }
295         /* parse sort key */
296         if (option_mask32 & FLAG_k) {
297                 enum {
298                         FLAG_allowed_for_k =
299                                 FLAG_n | /* Numeric sort */
300                                 FLAG_g | /* Sort using strtod() */
301                                 FLAG_M | /* Sort date */
302                                 FLAG_b | /* Ignore leading blanks */
303                                 FLAG_r | /* Reverse */
304                                 FLAG_d | /* Ignore !(isalnum()|isspace()) */
305                                 FLAG_f | /* Force uppercase */
306                                 FLAG_i | /* Ignore !isprint() */
307                         0
308                 };
309                 struct sort_key *key = add_key();
310                 const char *temp2;
311
312                 i = 0; /* i==0 before comma, 1 after (-k3,6) */
313                 while (*str_k) {
314                         /* Start of range */
315                         /* Cannot use bb_strtou - suffix can be a letter */
316                         key->range[2*i] = str2u(&str_k);
317                         if (*str_k == '.') {
318                                 str_k++;
319                                 key->range[2*i+1] = str2u(&str_k);
320                         }
321                         while (*str_k) {
322                                 if (*str_k == ',' && !i++) {
323                                         str_k++;
324                                         break;
325                                 } /* no else needed: fall through to syntax error
326                                          because comma isn't in OPT_STR */
327                                 temp2 = strchr(OPT_STR, *str_k);
328                                 if (!temp2)
329                                         bb_error_msg_and_die("unknown key option");
330                                 flag = 1 << (temp2 - OPT_STR);
331                                 if (flag & ~FLAG_allowed_for_k)
332                                         bb_error_msg_and_die("unknown sort type");
333                                 /* b after ',' means strip _trailing_ space */
334                                 if (i && flag == FLAG_b) flag = FLAG_bb;
335                                 key->flags |= flag;
336                                 str_k++;
337                         }
338                 }
339         }
340 #endif
341         /* global b strips leading and trailing spaces */
342         if (option_mask32 & FLAG_b) option_mask32 |= FLAG_bb;
343
344         /* Open input files and read data */
345         for (i = argv[optind] ? optind : optind-1; argv[i]; i++) {
346                 fp = stdin;
347                 if (i >= optind && NOT_LONE_DASH(argv[i]))
348                         fp = xfopen(argv[i], "r");
349                 for (;;) {
350                         line = GET_LINE(fp);
351                         if (!line) break;
352                         if (!(linecount & 63))
353                                 lines = xrealloc(lines, sizeof(char *) * (linecount + 64));
354                         lines[linecount++] = line;
355                 }
356                 fclose(fp);
357         }
358 #if ENABLE_FEATURE_SORT_BIG
359         /* if no key, perform alphabetic sort */
360         if (!key_list)
361                 add_key()->range[0] = 1;
362         /* handle -c */
363         if (option_mask32 & FLAG_c) {
364                 int j = (option_mask32 & FLAG_u) ? -1 : 0;
365                 for (i = 1; i < linecount; i++)
366                         if (compare_keys(&lines[i-1], &lines[i]) > j) {
367                                 fprintf(stderr, "Check line %d\n", i);
368                                 return 1;
369                         }
370                 return 0;
371         }
372 #endif
373         /* Perform the actual sort */
374         qsort(lines, linecount, sizeof(char *), compare_keys);
375         /* handle -u */
376         if (option_mask32 & FLAG_u) {
377                 flag = 0;
378                 /* coreutils 6.3 drop lines for which only key is the same */
379                 /* -- disabling last-resort compare... */
380                 option_mask32 |= FLAG_s;
381                 for (i = 1; i < linecount; i++) {
382                         if (!compare_keys(&lines[flag], &lines[i]))
383                                 free(lines[i]);
384                         else
385                                 lines[++flag] = lines[i];
386                 }
387                 if (linecount) linecount = flag+1;
388         }
389         /* Print it */
390         for (i = 0; i < linecount; i++)
391                 fprintf(outfile, "%s\n", lines[i]);
392
393         fflush_stdout_and_exit(EXIT_SUCCESS);
394 }