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
17 /* This is a NOEXEC applet. Be very careful! */
21 sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
22 sort -c [-bdfinru][-t char][-k keydef][file]
25 /* These are sort types */
26 static const char OPT_STR
[] = "ngMucszbrdfimS:T:o:k:t:";
28 FLAG_n
= 1, /* Numeric sort */
29 FLAG_g
= 2, /* Sort using strtod() */
30 FLAG_M
= 4, /* Sort date */
31 /* ucsz apply to root level only, not keys. b at root level implies bb */
32 FLAG_u
= 8, /* Unique */
33 FLAG_c
= 0x10, /* Check: no output, exit(!ordered) */
34 FLAG_s
= 0x20, /* Stable sort, no ascii fallback at end */
35 FLAG_z
= 0x40, /* Input is null terminated, not \n */
36 /* These can be applied to search keys, the previous four can't */
37 FLAG_b
= 0x80, /* Ignore leading blanks */
38 FLAG_r
= 0x100, /* Reverse */
39 FLAG_d
= 0x200, /* Ignore !(isalnum()|isspace()) */
40 FLAG_f
= 0x400, /* Force uppercase */
41 FLAG_i
= 0x800, /* Ignore !isprint() */
42 FLAG_m
= 0x1000, /* ignored: merge already sorted files; do not sort */
43 FLAG_S
= 0x2000, /* ignored: -S, --buffer-size=SIZE */
44 FLAG_T
= 0x4000, /* ignored: -T, --temporary-directory=DIR */
48 FLAG_bb
= 0x80000000, /* Ignore trailing blanks */
51 #if ENABLE_FEATURE_SORT_BIG
52 static char key_separator
;
54 static struct sort_key
{
55 struct sort_key
*next_key
; /* linked list */
56 unsigned range
[4]; /* start word, start char, end word, end char */
60 static char *get_key(char *str
, struct sort_key
*key
, int flags
)
62 int start
= 0, end
= 0, len
, i
, j
;
64 /* Special case whole string, so we don't have to make a copy */
65 if (key
->range
[0] == 1 && !key
->range
[1] && !key
->range
[2] && !key
->range
[3]
66 && !(flags
& (FLAG_b
| FLAG_d
| FLAG_f
| FLAG_i
| FLAG_bb
))
71 /* Find start of key on first pass, end on second pass */
73 for (j
= 0; j
< 2; j
++) {
76 /* Loop through fields */
79 for (i
= 1; i
< key
->range
[2*j
] + j
; i
++) {
81 /* Skip body of key and separator */
83 if (str
[end
++] == key_separator
)
87 /* Skip leading blanks */
88 while (isspace(str
[end
]))
90 /* Skip body of key */
92 if (isspace(str
[end
]))
101 /* Strip leading whitespace if necessary */
102 //XXX: skip_whitespace()
104 while (isspace(str
[start
])) start
++;
105 /* Strip trailing whitespace if necessary */
107 while (end
> start
&& isspace(str
[end
-1])) end
--;
108 /* Handle offsets on start and end */
110 end
+= key
->range
[3] - 1;
111 if (end
> len
) end
= len
;
114 start
+= key
->range
[1] - 1;
115 if (start
> len
) start
= len
;
118 if (end
< start
) end
= start
;
119 str
= xstrndup(str
+start
, end
-start
);
121 if (flags
& FLAG_d
) {
122 for (start
= end
= 0; str
[end
]; end
++)
123 if (isspace(str
[end
]) || isalnum(str
[end
]))
124 str
[start
++] = str
[end
];
128 if (flags
& FLAG_i
) {
129 for (start
= end
= 0; str
[end
]; end
++)
130 if (isprint(str
[end
]))
131 str
[start
++] = str
[end
];
136 for (i
= 0; str
[i
]; i
++)
137 str
[i
] = toupper(str
[i
]);
142 static struct sort_key
*add_key(void)
144 struct sort_key
**pkey
= &key_list
;
146 pkey
= &((*pkey
)->next_key
);
147 return *pkey
= xzalloc(sizeof(struct sort_key
));
150 #define GET_LINE(fp) \
151 ((option_mask32 & FLAG_z) \
152 ? bb_get_chunk_from_file(fp, NULL) \
153 : xmalloc_getline(fp))
155 #define GET_LINE(fp) xmalloc_getline(fp)
158 /* Iterate through keys list and perform comparisons */
159 static int compare_keys(const void *xarg
, const void *yarg
)
161 int flags
= option_mask32
, retval
= 0;
164 #if ENABLE_FEATURE_SORT_BIG
165 struct sort_key
*key
;
167 for (key
= key_list
; !retval
&& key
; key
= key
->next_key
) {
168 flags
= key
->flags
? key
->flags
: option_mask32
;
169 /* Chop out and modify key chunks, handling -dfib */
170 x
= get_key(*(char **)xarg
, key
, flags
);
171 y
= get_key(*(char **)yarg
, key
, flags
);
173 /* This curly bracket serves no purpose but to match the nesting
174 level of the for () loop we're not using */
179 /* Perform actual comparison */
182 bb_error_msg_and_die("unknown sort type");
186 #if ENABLE_LOCALE_SUPPORT
187 retval
= strcoll(x
, y
);
189 retval
= strcmp(x
, y
);
192 #if ENABLE_FEATURE_SORT_BIG
195 double dx
= strtod(x
, &xx
);
196 double dy
= strtod(y
, &yy
);
197 /* not numbers < NaN < -infinity < numbers < +infinity) */
199 retval
= (y
== yy
? 0 : -1);
202 /* Check for isnan */
204 retval
= (dy
!= dy
) ? 0 : -1;
207 /* Check for infinity. Could underflow, but it avoids libm. */
208 else if (1.0 / dx
== 0.0) {
210 retval
= (1.0 / dy
== 0.0 && dy
< 0) ? 0 : -1;
212 retval
= (1.0 / dy
== 0.0 && dy
> 0) ? 0 : 1;
213 } else if (1.0 / dy
== 0.0)
214 retval
= (dy
< 0) ? 1 : -1;
216 retval
= (dx
> dy
) ? 1 : ((dx
< dy
) ? -1 : 0);
224 xx
= strptime(x
, "%b", &thyme
);
226 yy
= strptime(y
, "%b", &thyme
);
228 retval
= (!yy
) ? 0 : -1;
232 retval
= (dx
== thyme
.tm_mon
) ? 0 : dx
- thyme
.tm_mon
;
235 /* Full floating point version of -n */
239 retval
= (dx
> dy
) ? 1 : ((dx
< dy
) ? -1 : 0);
243 /* Free key copies. */
244 if (x
!= *(char **)xarg
) free(x
);
245 if (y
!= *(char **)yarg
) free(y
);
246 /* if (retval) break; - done by for () anyway */
248 /* Integer version of -n for tiny systems */
250 retval
= atoi(x
) - atoi(y
);
256 /* Perform fallback sort if necessary */
257 if (!retval
&& !(option_mask32
& FLAG_s
))
258 retval
= strcmp(*(char **)xarg
, *(char **)yarg
);
260 if (flags
& FLAG_r
) return -retval
;
264 #if ENABLE_FEATURE_SORT_BIG
265 static unsigned str2u(char **str
)
268 if (!isdigit((*str
)[0]))
269 bb_error_msg_and_die("bad field specification");
270 lu
= strtoul(*str
, str
, 10);
271 if ((sizeof(long) > sizeof(int) && lu
> INT_MAX
) || !lu
)
272 bb_error_msg_and_die("bad field specification");
277 int sort_main(int argc
, char **argv
);
278 int sort_main(int argc
, char **argv
)
280 FILE *fp
, *outfile
= stdout
;
281 char *line
, **lines
= NULL
;
282 char *str_ignored
, *str_o
, *str_t
;
283 llist_t
*lst_k
= NULL
;
287 xfunc_error_retval
= 2;
289 /* Parse command line options */
290 /* -o and -t can be given at most once */
291 opt_complementary
= "?:o--o:t--t:" /* -t, -o: maximum one of each */
292 "k::"; /* -k takes list */
293 getopt32(argc
, argv
, OPT_STR
, &str_ignored
, &str_ignored
, &str_o
, &lst_k
, &str_t
);
294 #if ENABLE_FEATURE_SORT_BIG
295 if (option_mask32
& FLAG_o
) outfile
= xfopen(str_o
, "w");
296 if (option_mask32
& FLAG_t
) {
297 if (!str_t
[0] || str_t
[1])
298 bb_error_msg_and_die("bad -t parameter");
299 key_separator
= str_t
[0];
305 FLAG_n
| /* Numeric sort */
306 FLAG_g
| /* Sort using strtod() */
307 FLAG_M
| /* Sort date */
308 FLAG_b
| /* Ignore leading blanks */
309 FLAG_r
| /* Reverse */
310 FLAG_d
| /* Ignore !(isalnum()|isspace()) */
311 FLAG_f
| /* Force uppercase */
312 FLAG_i
| /* Ignore !isprint() */
315 struct sort_key
*key
= add_key();
316 char *str_k
= lst_k
->data
;
319 i
= 0; /* i==0 before comma, 1 after (-k3,6) */
322 /* Cannot use bb_strtou - suffix can be a letter */
323 key
->range
[2*i
] = str2u(&str_k
);
326 key
->range
[2*i
+1] = str2u(&str_k
);
329 if (*str_k
== ',' && !i
++) {
332 } /* no else needed: fall through to syntax error
333 because comma isn't in OPT_STR */
334 temp2
= strchr(OPT_STR
, *str_k
);
336 bb_error_msg_and_die("unknown key option");
337 flag
= 1 << (temp2
- OPT_STR
);
338 if (flag
& ~FLAG_allowed_for_k
)
339 bb_error_msg_and_die("unknown sort type");
340 /* b after ',' means strip _trailing_ space */
341 if (i
&& flag
== FLAG_b
) flag
= FLAG_bb
;
346 /* leaking lst_k... */
350 /* global b strips leading and trailing spaces */
351 if (option_mask32
& FLAG_b
) option_mask32
|= FLAG_bb
;
353 /* Open input files and read data */
354 for (i
= argv
[optind
] ? optind
: optind
-1; argv
[i
]; i
++) {
356 if (i
>= optind
&& NOT_LONE_DASH(argv
[i
]))
357 fp
= xfopen(argv
[i
], "r");
361 if (!(linecount
& 63))
362 lines
= xrealloc(lines
, sizeof(char *) * (linecount
+ 64));
363 lines
[linecount
++] = line
;
367 #if ENABLE_FEATURE_SORT_BIG
368 /* if no key, perform alphabetic sort */
370 add_key()->range
[0] = 1;
372 if (option_mask32
& FLAG_c
) {
373 int j
= (option_mask32
& FLAG_u
) ? -1 : 0;
374 for (i
= 1; i
< linecount
; i
++)
375 if (compare_keys(&lines
[i
-1], &lines
[i
]) > j
) {
376 fprintf(stderr
, "Check line %d\n", i
);
382 /* Perform the actual sort */
383 qsort(lines
, linecount
, sizeof(char *), compare_keys
);
385 if (option_mask32
& FLAG_u
) {
387 /* coreutils 6.3 drop lines for which only key is the same */
388 /* -- disabling last-resort compare... */
389 option_mask32
|= FLAG_s
;
390 for (i
= 1; i
< linecount
; i
++) {
391 if (!compare_keys(&lines
[flag
], &lines
[i
]))
394 lines
[++flag
] = lines
[i
];
396 if (linecount
) linecount
= flag
+1;
399 for (i
= 0; i
< linecount
; i
++)
400 fprintf(outfile
, "%s\n", lines
[i
]);
402 fflush_stdout_and_exit(EXIT_SUCCESS
);