*: use better isspace implementation
[oweals/busybox.git] / libbb / process_escape_sequence.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Utility routines.
4  *
5  * Copyright (C) Manuel Novoa III <mjn3@codepoet.org>
6  * and Vladimir Oleynik <dzo@simtreas.ru>
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
9  */
10
11 #include "libbb.h"
12
13 #define WANT_HEX_ESCAPES 1
14
15 /* Usual "this only works for ascii compatible encodings" disclaimer. */
16 #undef _tolower
17 #define _tolower(X) ((X)|((char) 0x20))
18
19 char FAST_FUNC bb_process_escape_sequence(const char **ptr)
20 {
21         /* bash builtin "echo -e '\ec'" interprets \e as ESC,
22          * but coreutils "/bin/echo -e '\ec'" does not.
23          * manpages tend to support coreutils way. */
24         static const char charmap[] ALIGN1 = {
25                 'a',  'b', /*'e',*/ 'f',  'n',  'r',  't',  'v',  '\\', 0,
26                 '\a', '\b', /*27,*/ '\f', '\n', '\r', '\t', '\v', '\\', '\\' };
27
28         const char *p;
29         const char *q;
30         unsigned num_digits;
31         unsigned r;
32         unsigned n;
33         unsigned d;
34         unsigned base;
35
36         num_digits = n = 0;
37         base = 8;
38         q = *ptr;
39
40 #ifdef WANT_HEX_ESCAPES
41         if (*q == 'x') {
42                 ++q;
43                 base = 16;
44                 ++num_digits;
45         }
46 #endif
47
48         /* bash requires leading 0 in octal escapes:
49          * \02 works, \2 does not (prints \ and 2).
50          * We treat \2 as a valid octal escape sequence. */
51         do {
52                 d = (unsigned char)(*q) - '0';
53 #ifdef WANT_HEX_ESCAPES
54                 if (d >= 10) {
55                         d = (unsigned char)(_tolower(*q)) - 'a' + 10;
56                 }
57 #endif
58
59                 if (d >= base) {
60 #ifdef WANT_HEX_ESCAPES
61                         if ((base == 16) && (!--num_digits)) {
62 /*                              return '\\'; */
63                                 --q;
64                         }
65 #endif
66                         break;
67                 }
68
69                 r = n * base + d;
70                 if (r > UCHAR_MAX) {
71                         break;
72                 }
73
74                 n = r;
75                 ++q;
76         } while (++num_digits < 3);
77
78         if (num_digits == 0) {  /* mnemonic escape sequence? */
79                 p = charmap;
80                 do {
81                         if (*p == *q) {
82                                 q++;
83                                 break;
84                         }
85                 } while (*++p);
86                 /* p points to found escape char or NUL,
87                  * advance it and find what it translates to */
88                 p += sizeof(charmap) / 2;
89                 n = *p;
90         }
91
92         *ptr = q;
93
94         return (char) n;
95 }