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
24 static int global_flags;
27 sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
28 sort -c [-bdfinru][-t char][-k keydef][file]
31 /* These are sort types */
32 #define FLAG_n 1 /* Numeric sort */
33 #define FLAG_g 2 /* Sort using strtod() */
34 #define FLAG_M 4 /* Sort date */
35 /* ucsz apply to root level only, not keys. b at root level implies bb */
36 #define FLAG_u 8 /* Unique */
37 #define FLAG_c 16 /* Check: no output, exit(!ordered) */
38 #define FLAG_s 32 /* Stable sort, no ascii fallback at end */
39 #define FLAG_z 64 /* Input is null terminated, not \n */
40 /* These can be applied to search keys, the previous four can't */
41 #define FLAG_b 128 /* Ignore leading blanks */
42 #define FLAG_r 256 /* Reverse */
43 #define FLAG_d 512 /* Ignore !(isalnum()|isspace()) */
44 #define FLAG_f 1024 /* Force uppercase */
45 #define FLAG_i 2048 /* Ignore !isprint() */
46 #define FLAG_bb 32768 /* Ignore trailing blanks */
49 #ifdef CONFIG_FEATURE_SORT_BIG
50 static char key_separator;
52 static struct sort_key
54 struct sort_key *next_key; /* linked list */
55 unsigned short range[4]; /* start word, start char, end word, end char */
59 static char *get_key(char *str, struct sort_key *key, int flags)
61 int start=0,end,len,i,j;
63 /* Special case whole string, so we don't have to make a copy */
64 if(key->range[0]==1 && !key->range[1] && !key->range[2] && !key->range[3]
65 && !(flags&(FLAG_b&FLAG_d&FLAG_f&FLAG_i&FLAG_bb))) return str;
66 /* Find start of key on first pass, end on second pass*/
70 if(!key->range[2*j]) end=len;
71 /* Loop through fields */
74 for(i=1;i<key->range[2*j]+j;i++) {
75 /* Skip leading blanks or first separator */
78 if(str[end]==key_separator) end++;
79 } else if(isspace(str[end]))
80 while(isspace(str[end])) end++;
82 /* Skip body of key */
83 for(;str[end];end++) {
85 if(str[end]==key_separator) break;
86 } else if(isspace(str[end])) break;
92 /* Key with explicit separator starts after separator */
93 if(key_separator && str[start]==key_separator) start++;
94 /* Strip leading whitespace if necessary */
95 if(flags&FLAG_b) while(isspace(str[start])) start++;
96 /* Strip trailing whitespace if necessary */
97 if(flags&FLAG_bb) while(end>start && isspace(str[end-1])) end--;
98 /* Handle offsets on start and end */
100 end+=key->range[3]-1;
104 start+=key->range[1]-1;
105 if(start>len) start=len;
108 if(end<start) end=start;
109 str=bb_xstrndup(str+start,end-start);
112 for(start=end=0;str[end];end++)
113 if(isspace(str[end]) || isalnum(str[end])) str[start++]=str[end];
118 for(start=end=0;str[end];end++)
119 if(isprint(str[end])) str[start++]=str[end];
123 if(flags*FLAG_f) for(i=0;str[i];i++) str[i]=toupper(str[i]);
128 static struct sort_key *add_key(void)
130 struct sort_key **pkey=&key_list;
131 while(*pkey) pkey=&((*pkey)->next_key);
132 return *pkey=xcalloc(1,sizeof(struct sort_key));
135 #define GET_LINE(fp) (global_flags&FLAG_z) ? bb_get_chunk_from_file(fp,NULL) \
136 : bb_get_chomped_line_from_file(fp)
138 #define GET_LINE(fp) bb_get_chomped_line_from_file(fp)
141 /* Iterate through keys list and perform comparisons */
142 static int compare_keys(const void *xarg, const void *yarg)
144 int flags=global_flags,retval=0;
147 #ifdef CONFIG_FEATURE_SORT_BIG
148 struct sort_key *key;
150 for(key=key_list;!retval && key;key=key->next_key) {
151 flags=(key->flags) ? key->flags : global_flags;
152 /* Chop out and modify key chunks, handling -dfib */
153 x=get_key(*(char **)xarg,key,flags);
154 y=get_key(*(char **)yarg,key,flags);
156 /* This curly bracket serves no purpose but to match the nesting
157 level of the for() loop we're not using */
162 /* Perform actual comparison */
165 bb_error_msg_and_die("Unknown sort type.");
171 #ifdef CONFIG_FEATURE_SORT_BIG
175 double dx=strtod(x,&xx), dy=strtod(y,&yy);
176 /* not numbers < NaN < -infinity < numbers < +infinity) */
177 if(x==xx) retval=(y==yy ? 0 : -1);
178 else if(y==yy) retval=1;
179 /* Check for isnan */
180 else if(dx != dx) retval = (dy != dy) ? 0 : -1;
181 else if(dy != dy) retval = 1;
182 /* Check for infinity. Could underflow, but it avoids libm. */
183 else if(1.0/dx == 0.0) {
184 if(dx<0) retval=((1.0/dy == 0.0 && dy<0) ? 0 : -1);
185 else retval=((1.0/dy == 0.0 && dy>0) ? 0 : 1);
186 } else if(1.0/dy == 0.0) retval=dy<0 ? 1 : -1;
187 else retval=dx>dy ? 1 : (dx<dy ? -1 : 0);
196 xx=strptime(x,"%b",&thyme);
198 yy=strptime(y,"%b",&thyme);
199 if(!xx) retval=(!yy ? 0 : -1);
200 else if(!yy) retval=1;
201 else retval=(dx==thyme.tm_mon ? 0 : dx-thyme.tm_mon);
204 /* Full floating point version of -n */
207 double dx=atof(x),dy=atof(y);
208 retval=dx>dy ? 1 : (dx<dy ? -1 : 0);
212 /* Free key copies. */
213 if(x!=*(char **)xarg) free(x);
214 if(y!=*(char **)yarg) free(y);
217 /* Integer version of -n for tiny systems */
219 retval=atoi(x)-atoi(y);
224 /* Perform fallback sort if necessary */
225 if(!retval && !(global_flags&FLAG_s))
226 retval=strcmp(*(char **)xarg, *(char **)yarg);
227 //dprintf(2,"reverse=%d\n",flags&FLAG_r);
228 return ((flags&FLAG_r)?-1:1)*retval;
231 int sort_main(int argc, char **argv)
233 FILE *fp,*outfile=NULL;
234 int linecount=0,i,flag;
235 char *line,**lines=NULL,*optlist="ngMucszbrdfimS:T:o:k:t:";
238 bb_default_error_retval = 2;
239 /* Parse command line options */
240 while((c=getopt(argc,argv,optlist))>0) {
241 line=strchr(optlist,c);
242 if(!line) bb_show_usage();
244 #ifdef CONFIG_FEATURE_SORT_BIG
246 if(outfile) bb_error_msg_and_die("Too many -o.");
247 outfile=bb_xfopen(optarg,"w");
250 if(key_separator || optarg[1])
251 bb_error_msg_and_die("Too many -t.");
252 key_separator=*optarg;
257 struct sort_key *key=add_key();
263 key->range[2*i]=(unsigned short)strtol(temp,&temp,10);
265 key->range[(2*i)+1]=(unsigned short)strtol(temp+1,&temp,10);
267 if(*temp==',' && !i++) {
270 } /* no else needed: fall through to syntax error
271 because comma isn't in optlist */
272 temp2=strchr(optlist,*temp);
273 flag=(1<<(temp2-optlist));
274 if(!temp2 || (flag>FLAG_M && flag<FLAG_b))
275 bb_error_msg_and_die("Unknown key option.");
276 /* b after , means strip _trailing_ space */
277 if(i && flag==FLAG_b) flag=FLAG_bb;
285 global_flags|=(1<<(line-optlist));
286 /* global b strips leading and trailing spaces */
287 if(global_flags&FLAG_b) global_flags|=FLAG_bb;
291 /* Open input files and read data */
292 for(i=argv[optind] ? optind : optind-1;argv[i];i++) {
293 if(i<optind || (*argv[i]=='-' && !argv[i][1])) fp=stdin;
294 else fp=bb_xfopen(argv[i],"r");
299 lines=xrealloc(lines, sizeof(char *)*(linecount+64));
300 lines[linecount++]=line;
304 #ifdef CONFIG_FEATURE_SORT_BIG
305 /* if no key, perform alphabetic sort */
306 if(!key_list) add_key()->range[0]=1;
308 if(global_flags&FLAG_c) {
309 int j=(global_flags&FLAG_u) ? -1 : 0;
310 for(i=1;i<linecount;i++)
311 if(compare_keys(&lines[i-1],&lines[i])>j) {
312 fprintf(stderr,"Check line %d\n",i);
318 /* Perform the actual sort */
319 qsort(lines,linecount,sizeof(char *),compare_keys);
321 if(global_flags&FLAG_u) {
322 for(flag=0,i=1;i<linecount;i++) {
323 if(!compare_keys(&lines[flag],&lines[i])) free(lines[i]);
324 else lines[++flag]=lines[i];
326 if(linecount) linecount=flag+1;
329 if(!outfile) outfile=stdout;
330 for(i=0;i<linecount;i++) fprintf(outfile,"%s\n",lines[i]);
331 bb_fflush_stdout_and_exit(EXIT_SUCCESS);