sort.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. #include "busybox.h"
  15. static int global_flags;
  16. /*
  17. sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
  18. sort -c [-bdfinru][-t char][-k keydef][file]
  19. */
  20. /* These are sort types */
  21. #define FLAG_n 1 /* Numeric sort */
  22. #define FLAG_g 2 /* Sort using strtod() */
  23. #define FLAG_M 4 /* Sort date */
  24. /* ucsz apply to root level only, not keys. b at root level implies bb */
  25. #define FLAG_u 8 /* Unique */
  26. #define FLAG_c 16 /* Check: no output, exit(!ordered) */
  27. #define FLAG_s 32 /* Stable sort, no ascii fallback at end */
  28. #define FLAG_z 64 /* Input is null terminated, not \n */
  29. /* These can be applied to search keys, the previous four can't */
  30. #define FLAG_b 128 /* Ignore leading blanks */
  31. #define FLAG_r 256 /* Reverse */
  32. #define FLAG_d 512 /* Ignore !(isalnum()|isspace()) */
  33. #define FLAG_f 1024 /* Force uppercase */
  34. #define FLAG_i 2048 /* Ignore !isprint() */
  35. #define FLAG_bb 32768 /* Ignore trailing blanks */
  36. #if ENABLE_FEATURE_SORT_BIG
  37. static char key_separator;
  38. static struct sort_key {
  39. struct sort_key *next_key; /* linked list */
  40. unsigned short range[4]; /* start word, start char, end word, end char */
  41. int flags;
  42. } *key_list;
  43. static char *get_key(char *str, struct sort_key *key, int flags)
  44. {
  45. int start = 0, end = 0, len, i, j;
  46. /* Special case whole string, so we don't have to make a copy */
  47. if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
  48. && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
  49. ) {
  50. return str;
  51. }
  52. /* Find start of key on first pass, end on second pass*/
  53. len = strlen(str);
  54. for (j = 0; j < 2; j++) {
  55. if (!key->range[2*j])
  56. end = len;
  57. /* Loop through fields */
  58. else {
  59. end = 0;
  60. for (i = 1; i < key->range[2*j] + j; i++) {
  61. /* Skip leading blanks or first separator */
  62. if (str[end]) {
  63. if (!key_separator)
  64. while (isspace(str[end])) end++;
  65. }
  66. /* Skip body of key */
  67. for (; str[end]; end++) {
  68. if (key_separator) {
  69. if (str[end] == key_separator)
  70. break;
  71. } else {
  72. if (isspace(str[end]))
  73. break;
  74. }
  75. }
  76. }
  77. }
  78. if (!j) start = end;
  79. }
  80. /* Key with explicit separator starts after separator */
  81. if (key_separator && str[start] == key_separator)
  82. start++;
  83. /* Strip leading whitespace if necessary */
  84. //XXX: skip_whitespace()
  85. if (flags & FLAG_b)
  86. while (isspace(str[start])) start++;
  87. /* Strip trailing whitespace if necessary */
  88. if (flags & FLAG_bb)
  89. while (end > start && isspace(str[end-1])) end--;
  90. /* Handle offsets on start and end */
  91. if (key->range[3]) {
  92. end += key->range[3] - 1;
  93. if (end > len) end = len;
  94. }
  95. if (key->range[1]) {
  96. start += key->range[1] - 1;
  97. if (start > len) start = len;
  98. }
  99. /* Make the copy */
  100. if (end < start) end = start;
  101. str = xstrndup(str+start, end-start);
  102. /* Handle -d */
  103. if (flags & FLAG_d) {
  104. for (start = end = 0; str[end]; end++)
  105. if (isspace(str[end]) || isalnum(str[end]))
  106. str[start++] = str[end];
  107. str[start] = '\0';
  108. }
  109. /* Handle -i */
  110. if (flags & FLAG_i) {
  111. for (start = end = 0; str[end]; end++)
  112. if (isprint(str[end]))
  113. str[start++] = str[end];
  114. str[start] = '\0';
  115. }
  116. /* Handle -f */
  117. if (flags & FLAG_f)
  118. for (i = 0; str[i]; i++)
  119. str[i] = toupper(str[i]);
  120. return str;
  121. }
  122. static struct sort_key *add_key(void)
  123. {
  124. struct sort_key **pkey = &key_list;
  125. while (*pkey)
  126. pkey = &((*pkey)->next_key);
  127. return *pkey = xzalloc(sizeof(struct sort_key));
  128. }
  129. #define GET_LINE(fp) \
  130. ((global_flags & FLAG_z) \
  131. ? bb_get_chunk_from_file(fp, NULL) \
  132. : xmalloc_getline(fp))
  133. #else
  134. #define GET_LINE(fp) xmalloc_getline(fp)
  135. #endif
  136. /* Iterate through keys list and perform comparisons */
  137. static int compare_keys(const void *xarg, const void *yarg)
  138. {
  139. int flags = global_flags, retval = 0;
  140. char *x, *y;
  141. #if ENABLE_FEATURE_SORT_BIG
  142. struct sort_key *key;
  143. for (key = key_list; !retval && key; key = key->next_key) {
  144. flags = key->flags ? key->flags : global_flags;
  145. /* Chop out and modify key chunks, handling -dfib */
  146. x = get_key(*(char **)xarg, key, flags);
  147. y = get_key(*(char **)yarg, key, flags);
  148. #else
  149. /* This curly bracket serves no purpose but to match the nesting
  150. level of the for() loop we're not using */
  151. {
  152. x = *(char **)xarg;
  153. y = *(char **)yarg;
  154. #endif
  155. /* Perform actual comparison */
  156. switch (flags & 7) {
  157. default:
  158. bb_error_msg_and_die("unknown sort type");
  159. break;
  160. /* Ascii sort */
  161. case 0:
  162. retval = strcmp(x, y);
  163. break;
  164. #if ENABLE_FEATURE_SORT_BIG
  165. case FLAG_g: {
  166. char *xx, *yy;
  167. double dx = strtod(x, &xx);
  168. double dy = strtod(y, &yy);
  169. /* not numbers < NaN < -infinity < numbers < +infinity) */
  170. if (x == xx)
  171. retval = (y == yy ? 0 : -1);
  172. else if (y == yy)
  173. retval = 1;
  174. /* Check for isnan */
  175. else if (dx != dx)
  176. retval = (dy != dy) ? 0 : -1;
  177. else if (dy != dy)
  178. retval = 1;
  179. /* Check for infinity. Could underflow, but it avoids libm. */
  180. else if (1.0 / dx == 0.0) {
  181. if (dx < 0)
  182. retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
  183. else
  184. retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
  185. } else if (1.0 / dy == 0.0)
  186. retval = (dy < 0) ? 1 : -1;
  187. else
  188. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  189. break;
  190. }
  191. case FLAG_M: {
  192. struct tm thyme;
  193. int dx;
  194. char *xx, *yy;
  195. xx = strptime(x, "%b", &thyme);
  196. dx = thyme.tm_mon;
  197. yy = strptime(y, "%b", &thyme);
  198. if (!xx)
  199. retval = (!yy) ? 0 : -1;
  200. else if (!yy)
  201. retval = 1;
  202. else
  203. retval = (dx == thyme.tm_mon) ? 0 : dx - thyme.tm_mon;
  204. break;
  205. }
  206. /* Full floating point version of -n */
  207. case FLAG_n: {
  208. double dx = atof(x);
  209. double dy = atof(y);
  210. retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
  211. break;
  212. }
  213. } /* switch */
  214. /* Free key copies. */
  215. if (x != *(char **)xarg) free(x);
  216. if (y != *(char **)yarg) free(y);
  217. /* if (retval) break; - done by for() anyway */
  218. #else
  219. /* Integer version of -n for tiny systems */
  220. case FLAG_n:
  221. retval = atoi(x) - atoi(y);
  222. break;
  223. } /* switch */
  224. #endif
  225. }
  226. /* Perform fallback sort if necessary */
  227. if (!retval && !(global_flags & FLAG_s))
  228. retval = strcmp(*(char **)xarg, *(char **)yarg);
  229. if (flags & FLAG_r) return -retval;
  230. return retval;
  231. }
  232. int sort_main(int argc, char **argv)
  233. {
  234. FILE *fp, *outfile = NULL;
  235. int linecount = 0, i, flag;
  236. char *line, **lines = NULL, *optlist = "ngMucszbrdfimS:T:o:k:t:";
  237. int c;
  238. xfunc_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();
  243. switch (*line) {
  244. #if ENABLE_FEATURE_SORT_BIG
  245. case 'o':
  246. if (outfile) bb_error_msg_and_die("too many -o");
  247. outfile = xfopen(optarg, "w");
  248. break;
  249. case 't':
  250. if (key_separator || optarg[1])
  251. bb_error_msg_and_die("too many -t");
  252. key_separator = *optarg;
  253. break;
  254. /* parse sort key */
  255. case 'k': {
  256. struct sort_key *key = add_key();
  257. char *temp, *temp2;
  258. temp = optarg;
  259. for (i = 0; *temp;) {
  260. /* Start of range */
  261. key->range[2*i] = (unsigned short)strtol(temp, &temp, 10);
  262. if (*temp == '.')
  263. key->range[(2*i)+1] = (unsigned short)strtol(temp+1, &temp, 10);
  264. for (; *temp; temp++) {
  265. if (*temp == ',' && !i++) {
  266. temp++;
  267. break;
  268. } /* no else needed: fall through to syntax error
  269. because comma isn't in optlist */
  270. temp2 = strchr(optlist, *temp);
  271. flag = (1 << (temp2 - optlist));
  272. if (!temp2 || (flag > FLAG_M && flag < FLAG_b))
  273. bb_error_msg_and_die("unknown key option");
  274. /* b after ',' means strip _trailing_ space */
  275. if (i && flag == FLAG_b) flag = FLAG_bb;
  276. key->flags |= flag;
  277. }
  278. }
  279. break;
  280. }
  281. #endif
  282. default:
  283. global_flags |= (1 << (line - optlist));
  284. /* global b strips leading and trailing spaces */
  285. if (global_flags & FLAG_b) global_flags |= FLAG_bb;
  286. break;
  287. }
  288. }
  289. /* Open input files and read data */
  290. for (i = argv[optind] ? optind : optind-1; argv[i]; i++) {
  291. fp = stdin;
  292. if (i >= optind && (argv[i][0] != '-' || argv[i][1]))
  293. fp = xfopen(argv[i], "r");
  294. for (;;) {
  295. line = GET_LINE(fp);
  296. if (!line) break;
  297. if (!(linecount & 63))
  298. lines = xrealloc(lines, sizeof(char *) * (linecount + 64));
  299. lines[linecount++] = line;
  300. }
  301. fclose(fp);
  302. }
  303. #if ENABLE_FEATURE_SORT_BIG
  304. /* if no key, perform alphabetic sort */
  305. if (!key_list)
  306. add_key()->range[0] = 1;
  307. /* handle -c */
  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);
  313. return 1;
  314. }
  315. return 0;
  316. }
  317. #endif
  318. /* Perform the actual sort */
  319. qsort(lines, linecount, sizeof(char *), compare_keys);
  320. /* handle -u */
  321. if (global_flags & FLAG_u) {
  322. for (flag = 0, i = 1; i < linecount; i++) {
  323. if (!compare_keys(&lines[flag], &lines[i]))
  324. free(lines[i]);
  325. else
  326. lines[++flag] = lines[i];
  327. }
  328. if (linecount) linecount = flag+1;
  329. }
  330. /* Print it */
  331. if (!outfile) outfile = stdout;
  332. for (i = 0; i < linecount; i++)
  333. fprintf(outfile, "%s\n", lines[i]);
  334. fflush_stdout_and_exit(EXIT_SUCCESS);
  335. }