f6f458bf072cc09cd51fd6892000351d32fea217
[oweals/busybox.git] / coreutils / tr.c
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: xdigit, graph, print
20  */
21 #include "libbb.h"
22
23 #define ASCII 0377
24
25 #define TR_OPT_complement       (1<<0)
26 #define TR_OPT_delete           (1<<1)
27 #define TR_OPT_squeeze_reps     (1<<2)
28
29 static void map(char *pvector,
30                 unsigned char *string1, unsigned int string1_len,
31                 unsigned char *string2, unsigned int string2_len)
32 {
33         char last = '0';
34         unsigned int i, j;
35
36         for (j = 0, i = 0; i < string1_len; i++) {
37                 if (string2_len <= j)
38                         pvector[string1[i]] = last;
39                 else
40                         pvector[string1[i]] = last = string2[j++];
41         }
42 }
43
44 /* supported constructs:
45  *   Ranges,  e.g.,  0-9   ==>  0123456789
46  *   Ranges,  e.g.,  [0-9] ==>  0123456789
47  *   Escapes, e.g.,  \a    ==>  Control-G
48  *   Character classes, e.g. [:upper:] ==> A...Z
49  *   Equiv classess, e.g. [=A=] ==> A   (hmmmmmmm?)
50  */
51 static unsigned int expand(const char *arg, char *buffer)
52 {
53         char *buffer_start = buffer;
54         unsigned i; /* can't be unsigned char: must be able to hold 256 */
55         unsigned char ac;
56
57         while (*arg) {
58                 if (*arg == '\\') {
59                         arg++;
60                         *buffer++ = bb_process_escape_sequence(&arg);
61                         continue;
62                 }
63                 if (arg[1] == '-') { /* "0-9..." */
64                         ac = arg[2];
65                         if (ac == '\0') { /* "0-": copy verbatim */
66                                 *buffer++ = *arg++; /* copy '0' */
67                                 continue; /* next iter will copy '-' and stop */
68                         }
69                         i = *arg;
70                         while (i <= ac) /* ok: i is unsigned _int_ */
71                                 *buffer++ = i++;
72                         arg += 3; /* skip 0-9 */
73                         continue;
74                 }
75                 if (*arg == '[') { /* "[xyz..." */
76                         arg++;
77                         i = *arg++;
78                         /* "[xyz...", i=x, arg points to y */
79                         if (ENABLE_FEATURE_TR_CLASSES && i == ':') {
80 #define CLO ":]\0"
81                                 static const char classes[] ALIGN1 =
82                                         "alpha"CLO "alnum"CLO "digit"CLO
83                                         "lower"CLO "upper"CLO "space"CLO
84                                         "blank"CLO "punct"CLO "cntrl"CLO;
85 #define CLASS_invalid 0 /* we increment the retval */
86 #define CLASS_alpha 1
87 #define CLASS_alnum 2
88 #define CLASS_digit 3
89 #define CLASS_lower 4
90 #define CLASS_upper 5
91 #define CLASS_space 6
92 #define CLASS_blank 7
93 #define CLASS_punct 8
94 #define CLASS_cntrl 9
95 //#define CLASS_xdigit 10
96 //#define CLASS_graph 11
97 //#define CLASS_print 12
98                                 smalluint j;
99                                 { /* not really pretty.. */
100                                         char *tmp = xstrndup(arg, 7); // warning: xdigit would need 8, not 7
101                                         j = index_in_strings(classes, tmp) + 1;
102                                         free(tmp);
103                                 }
104                                 if (j == CLASS_alnum || j == CLASS_digit) {
105                                         for (i = '0'; i <= '9'; i++)
106                                                 *buffer++ = i;
107                                 }
108                                 if (j == CLASS_alpha || j == CLASS_alnum || j == CLASS_upper) {
109                                         for (i = 'A'; i <= 'Z'; i++)
110                                                 *buffer++ = i;
111                                 }
112                                 if (j == CLASS_alpha || j == CLASS_alnum || j == CLASS_lower) {
113                                         for (i = 'a'; i <= 'z'; i++)
114                                                 *buffer++ = i;
115                                 }
116                                 if (j == CLASS_space || j == CLASS_blank) {
117                                         *buffer++ = '\t';
118                                         if (j == CLASS_space) {
119                                                 *buffer++ = '\n';
120                                                 *buffer++ = '\v';
121                                                 *buffer++ = '\f';
122                                                 *buffer++ = '\r';
123                                         }
124                                         *buffer++ = ' ';
125                                 }
126                                 if (j == CLASS_punct || j == CLASS_cntrl) {
127                                         for (i = '\0'; i <= ASCII; i++)
128                                                 if ((j == CLASS_punct && isprint(i) && !isalnum(i) && !isspace(i))
129                                                  || (j == CLASS_cntrl && iscntrl(i)))
130                                                         *buffer++ = i;
131                                 }
132                                 if (j == CLASS_invalid) {
133                                         *buffer++ = '[';
134                                         *buffer++ = ':';
135                                         continue;
136                                 }
137                                 break;
138                         }
139                         /* "[xyz...", i=x, arg points to y */
140                         if (ENABLE_FEATURE_TR_EQUIV && i == '=') { /* [=CHAR=] */
141                                 *buffer++ = *arg; /* copy CHAR */
142                                 arg += 3;       /* skip CHAR=] */
143                                 continue;
144                         }
145                         if (*arg != '-') { /* not [x-...] - copy verbatim */
146                                 *buffer++ = '[';
147                                 arg--; /* points to x */
148                                 continue; /* copy all, including eventual ']' */
149                         }
150                         /* [x-y...] */
151                         arg++;
152                         ac = *arg++;
153                         while (i <= ac)
154                                 *buffer++ = i++;
155                         arg++;  /* skip the assumed ']' */
156                         continue;
157                 }
158                 *buffer++ = *arg++;
159         }
160         return (buffer - buffer_start);
161 }
162
163 static int complement(char *buffer, int buffer_len)
164 {
165         int i, j, ix;
166         char conv[ASCII + 2];
167
168         ix = 0;
169         for (i = '\0'; i <= ASCII; i++) {
170                 for (j = 0; j < buffer_len; j++)
171                         if (buffer[j] == i)
172                                 break;
173                 if (j == buffer_len)
174                         conv[ix++] = i & ASCII;
175         }
176         memcpy(buffer, conv, ix);
177         return ix;
178 }
179
180 int tr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
181 int tr_main(int argc, char **argv)
182 {
183         unsigned char *ptr;
184         int output_length = 0, input_length;
185         int idx = 1;
186         int i;
187         smalluint flags = 0;
188         ssize_t read_chars = 0;
189         size_t in_index = 0, out_index = 0;
190         unsigned last = UCHAR_MAX + 1; /* not equal to any char */
191         unsigned char coded, c; 
192         RESERVE_CONFIG_UBUFFER(output, BUFSIZ);
193         RESERVE_CONFIG_BUFFER(vector, ASCII+1);
194         RESERVE_CONFIG_BUFFER(invec,  ASCII+1);
195         RESERVE_CONFIG_BUFFER(outvec, ASCII+1);
196
197         if (argc > 1 && argv[idx][0] == '-') {
198                 for (ptr = (unsigned char *) &argv[idx][1]; *ptr; ptr++) {
199                         if (*ptr == 'c')
200                                 flags |= TR_OPT_complement;
201                         else if (*ptr == 'd')
202                                 flags |= TR_OPT_delete;
203                         else if (*ptr == 's')
204                                 flags |= TR_OPT_squeeze_reps;
205                         else
206                                 bb_show_usage();
207                 }
208                 idx++;
209         }
210         for (i = 0; i <= ASCII; i++) {
211                 vector[i] = i;
212                 invec[i] = outvec[i] = FALSE;
213         }
214
215 #define tr_buf bb_common_bufsiz1
216         if (argv[idx] != NULL) {
217                 input_length = expand(argv[idx++], tr_buf);
218                 if (flags & TR_OPT_complement)
219                         input_length = complement(tr_buf, input_length);
220                 if (argv[idx]) {
221                         if (argv[idx][0] == '\0')
222                                 bb_error_msg_and_die("STRING2 cannot be empty");
223                         output_length = expand(argv[idx], output);
224                         map(vector, tr_buf, input_length, output, output_length);
225                 }
226                 for (i = 0; i < input_length; i++)
227                         invec[(unsigned char)tr_buf[i]] = TRUE;
228                 for (i = 0; i < output_length; i++)
229                         outvec[output[i]] = TRUE;
230         }
231
232         for (;;) {
233                 /* If we're out of input, flush output and read more input. */
234                 if (in_index == read_chars) {
235                         if (out_index) {
236                                 xwrite(STDOUT_FILENO, (char *)output, out_index);
237                                 out_index = 0;
238                         }
239                         read_chars = safe_read(STDIN_FILENO, tr_buf, BUFSIZ);
240                         if (read_chars <= 0) {
241                                 if (read_chars < 0)
242                                         bb_perror_msg_and_die(bb_msg_read_error);
243                                 exit(EXIT_SUCCESS);
244                         }
245                         in_index = 0;
246                 }
247                 c = tr_buf[in_index++];
248                 coded = vector[c];
249                 if ((flags & TR_OPT_delete) && invec[c])
250                         continue;
251                 if ((flags & TR_OPT_squeeze_reps) && last == coded
252                  && (invec[c] || outvec[coded]))
253                         continue;
254                 output[out_index++] = last = coded;
255         }
256         /* NOTREACHED */
257         return EXIT_SUCCESS;
258 }