tr.c 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini tr implementation for busybox
  4. *
  5. ** Copyright (c) 1987,1997, Prentice Hall All rights reserved.
  6. *
  7. * The name of Prentice Hall may not be used to endorse or promote
  8. * products derived from this software without specific prior
  9. * written permission.
  10. *
  11. * Copyright (c) Michiel Huisjes
  12. *
  13. * This version of tr is adapted from Minix tr and was modified
  14. * by Erik Andersen <andersen@codepoet.org> to be used in busybox.
  15. *
  16. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  17. */
  18. /* http://www.opengroup.org/onlinepubs/009695399/utilities/tr.html
  19. * TODO: graph, print
  20. */
  21. #include "libbb.h"
  22. enum {
  23. ASCII = 256,
  24. /* string buffer needs to be at least as big as the whole "alphabet".
  25. * BUFSIZ == ASCII is ok, but we will realloc in expand
  26. * even for smallest patterns, let's avoid that by using *2:
  27. */
  28. TR_BUFSIZ = (BUFSIZ > ASCII*2) ? BUFSIZ : ASCII*2,
  29. };
  30. static void map(char *pvector,
  31. char *string1, unsigned string1_len,
  32. char *string2, unsigned string2_len)
  33. {
  34. char last = '0';
  35. unsigned i, j;
  36. for (j = 0, i = 0; i < string1_len; i++) {
  37. if (string2_len <= j)
  38. pvector[(unsigned char)(string1[i])] = last;
  39. else
  40. pvector[(unsigned char)(string1[i])] = last = string2[j++];
  41. }
  42. }
  43. /* supported constructs:
  44. * Ranges, e.g., 0-9 ==> 0123456789
  45. * Escapes, e.g., \a ==> Control-G
  46. * Character classes, e.g. [:upper:] ==> A...Z
  47. * Equiv classess, e.g. [=A=] ==> A (hmmmmmmm?)
  48. * not supported:
  49. * \ooo-\ooo - octal ranges
  50. * [x*N] - repeat char x N times
  51. * [x*] - repeat char x until it fills STRING2:
  52. * # echo qwe123 | /usr/bin/tr 123456789 '[d]'
  53. * qwe[d]
  54. * # echo qwe123 | /usr/bin/tr 123456789 '[d*]'
  55. * qweddd
  56. */
  57. static unsigned expand(const char *arg, char **buffer_p)
  58. {
  59. char *buffer = *buffer_p;
  60. unsigned pos = 0;
  61. unsigned size = TR_BUFSIZ;
  62. unsigned i; /* can't be unsigned char: must be able to hold 256 */
  63. unsigned char ac;
  64. while (*arg) {
  65. if (pos + ASCII > size) {
  66. size += ASCII;
  67. *buffer_p = buffer = xrealloc(buffer, size);
  68. }
  69. if (*arg == '\\') {
  70. arg++;
  71. buffer[pos++] = bb_process_escape_sequence(&arg);
  72. continue;
  73. }
  74. if (arg[1] == '-') { /* "0-9..." */
  75. ac = arg[2];
  76. if (ac == '\0') { /* "0-": copy verbatim */
  77. buffer[pos++] = *arg++; /* copy '0' */
  78. continue; /* next iter will copy '-' and stop */
  79. }
  80. i = (unsigned char) *arg;
  81. while (i <= ac) /* ok: i is unsigned _int_ */
  82. buffer[pos++] = i++;
  83. arg += 3; /* skip 0-9 */
  84. continue;
  85. }
  86. if ((ENABLE_FEATURE_TR_CLASSES || ENABLE_FEATURE_TR_EQUIV)
  87. && *arg == '['
  88. ) {
  89. arg++;
  90. i = (unsigned char) *arg++;
  91. /* "[xyz...". i=x, arg points to y */
  92. if (ENABLE_FEATURE_TR_CLASSES && i == ':') { /* [:class:] */
  93. #define CLO ":]\0"
  94. static const char classes[] ALIGN1 =
  95. "alpha"CLO "alnum"CLO "digit"CLO
  96. "lower"CLO "upper"CLO "space"CLO
  97. "blank"CLO "punct"CLO "cntrl"CLO
  98. "xdigit"CLO;
  99. enum {
  100. CLASS_invalid = 0, /* we increment the retval */
  101. CLASS_alpha = 1,
  102. CLASS_alnum = 2,
  103. CLASS_digit = 3,
  104. CLASS_lower = 4,
  105. CLASS_upper = 5,
  106. CLASS_space = 6,
  107. CLASS_blank = 7,
  108. CLASS_punct = 8,
  109. CLASS_cntrl = 9,
  110. CLASS_xdigit = 10,
  111. //CLASS_graph = 11,
  112. //CLASS_print = 12,
  113. };
  114. smalluint j;
  115. char *tmp;
  116. /* xdigit needs 8, not 7 */
  117. i = 7 + (arg[0] == 'x');
  118. tmp = xstrndup(arg, i);
  119. j = index_in_strings(classes, tmp) + 1;
  120. free(tmp);
  121. if (j == CLASS_invalid)
  122. goto skip_bracket;
  123. arg += i;
  124. if (j == CLASS_alnum || j == CLASS_digit || j == CLASS_xdigit) {
  125. for (i = '0'; i <= '9'; i++)
  126. buffer[pos++] = i;
  127. }
  128. if (j == CLASS_alpha || j == CLASS_alnum || j == CLASS_upper) {
  129. for (i = 'A'; i <= 'Z'; i++)
  130. buffer[pos++] = i;
  131. }
  132. if (j == CLASS_alpha || j == CLASS_alnum || j == CLASS_lower) {
  133. for (i = 'a'; i <= 'z'; i++)
  134. buffer[pos++] = i;
  135. }
  136. if (j == CLASS_space || j == CLASS_blank) {
  137. buffer[pos++] = '\t';
  138. if (j == CLASS_space) {
  139. buffer[pos++] = '\n';
  140. buffer[pos++] = '\v';
  141. buffer[pos++] = '\f';
  142. buffer[pos++] = '\r';
  143. }
  144. buffer[pos++] = ' ';
  145. }
  146. if (j == CLASS_punct || j == CLASS_cntrl) {
  147. for (i = '\0'; i < ASCII; i++) {
  148. if ((j == CLASS_punct && isprint(i) && !isalnum(i) && !isspace(i))
  149. || (j == CLASS_cntrl && iscntrl(i))
  150. ) {
  151. buffer[pos++] = i;
  152. }
  153. }
  154. }
  155. if (j == CLASS_xdigit) {
  156. for (i = 'A'; i <= 'F'; i++) {
  157. buffer[pos + 6] = i | 0x20;
  158. buffer[pos++] = i;
  159. }
  160. pos += 6;
  161. }
  162. continue;
  163. }
  164. /* "[xyz...", i=x, arg points to y */
  165. if (ENABLE_FEATURE_TR_EQUIV && i == '=') { /* [=CHAR=] */
  166. buffer[pos++] = *arg; /* copy CHAR */
  167. if (!arg[0] || arg[1] != '=' || arg[2] != ']')
  168. bb_show_usage();
  169. arg += 3; /* skip CHAR=] */
  170. continue;
  171. }
  172. /* The rest of "[xyz..." cases is treated as normal
  173. * string, "[" has no special meaning here:
  174. * tr "[a-z]" "[A-Z]" can be written as tr "a-z" "A-Z",
  175. * also try tr "[a-z]" "_A-Z+" and you'll see that
  176. * [] is not special here.
  177. */
  178. skip_bracket:
  179. arg -= 2; /* points to "[" in "[xyz..." */
  180. }
  181. buffer[pos++] = *arg++;
  182. }
  183. return pos;
  184. }
  185. /* NB: buffer is guaranteed to be at least TR_BUFSIZE
  186. * (which is >= ASCII) big.
  187. */
  188. static int complement(char *buffer, int buffer_len)
  189. {
  190. int len;
  191. char conv[ASCII];
  192. unsigned char ch;
  193. len = 0;
  194. ch = '\0';
  195. while (1) {
  196. if (memchr(buffer, ch, buffer_len) == NULL)
  197. conv[len++] = ch;
  198. if (++ch == '\0')
  199. break;
  200. }
  201. memcpy(buffer, conv, len);
  202. return len;
  203. }
  204. int tr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  205. int tr_main(int argc UNUSED_PARAM, char **argv)
  206. {
  207. int i;
  208. smalluint opts;
  209. ssize_t read_chars;
  210. size_t in_index, out_index;
  211. unsigned last = UCHAR_MAX + 1; /* not equal to any char */
  212. unsigned char coded, c;
  213. char *str1 = xmalloc(TR_BUFSIZ);
  214. char *str2 = xmalloc(TR_BUFSIZ);
  215. int str2_length;
  216. int str1_length;
  217. char *vector = xzalloc(ASCII * 3);
  218. char *invec = vector + ASCII;
  219. char *outvec = vector + ASCII * 2;
  220. #define TR_OPT_complement (3 << 0)
  221. #define TR_OPT_delete (1 << 2)
  222. #define TR_OPT_squeeze_reps (1 << 3)
  223. for (i = 0; i < ASCII; i++) {
  224. vector[i] = i;
  225. /*invec[i] = outvec[i] = FALSE; - done by xzalloc */
  226. }
  227. /* -C/-c difference is that -C complements "characters",
  228. * and -c complements "values" (binary bytes I guess).
  229. * In POSIX locale, these are the same.
  230. */
  231. opt_complementary = "-1";
  232. opts = getopt32(argv, "+Ccds"); /* '+': stop at first non-option */
  233. argv += optind;
  234. str1_length = expand(*argv++, &str1);
  235. str2_length = 0;
  236. if (opts & TR_OPT_complement)
  237. str1_length = complement(str1, str1_length);
  238. if (*argv) {
  239. if (argv[0][0] == '\0')
  240. bb_error_msg_and_die("STRING2 cannot be empty");
  241. str2_length = expand(*argv, &str2);
  242. map(vector, str1, str1_length,
  243. str2, str2_length);
  244. }
  245. for (i = 0; i < str1_length; i++)
  246. invec[(unsigned char)(str1[i])] = TRUE;
  247. for (i = 0; i < str2_length; i++)
  248. outvec[(unsigned char)(str2[i])] = TRUE;
  249. goto start_from;
  250. /* In this loop, str1 space is reused as input buffer,
  251. * str2 - as output one. */
  252. for (;;) {
  253. /* If we're out of input, flush output and read more input. */
  254. if ((ssize_t)in_index == read_chars) {
  255. if (out_index) {
  256. xwrite(STDOUT_FILENO, str2, out_index);
  257. start_from:
  258. out_index = 0;
  259. }
  260. read_chars = safe_read(STDIN_FILENO, str1, TR_BUFSIZ);
  261. if (read_chars <= 0) {
  262. if (read_chars < 0)
  263. bb_perror_msg_and_die(bb_msg_read_error);
  264. break;
  265. }
  266. in_index = 0;
  267. }
  268. c = str1[in_index++];
  269. if ((opts & TR_OPT_delete) && invec[c])
  270. continue;
  271. coded = vector[c];
  272. if ((opts & TR_OPT_squeeze_reps) && last == coded
  273. && (invec[c] || outvec[coded])
  274. ) {
  275. continue;
  276. }
  277. str2[out_index++] = last = coded;
  278. }
  279. return EXIT_SUCCESS;
  280. }