Imported Upstream version 2.2.51
[platform/upstream/acl.git] / libmisc / quote.c
1 /*
2   File: quote.c
3
4   Copyright (C) 2003 Andreas Gruenbacher <a.gruenbacher@bestbits.at>
5
6   This program is free software; you can redistribute it and/or modify it under
7   the terms of the GNU Lesser General Public License as published by the
8   Free Software Foundation; either version 2.1 of the License, or (at
9   your option) any later version.
10
11   This program is distributed in the hope that it will be useful, but WITHOUT
12   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
14   License for more details.
15
16   You should have received a copy of the GNU Lesser General Public
17   License along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <ctype.h>
23 #include "misc.h"
24
25 const char *quote(const char *str, const char *quote_chars)
26 {
27         static char *quoted_str;
28         static size_t quoted_str_len;
29         const unsigned char *s;
30         char *q;
31         size_t nonpr;
32
33         if (!str)
34                 return str;
35
36         for (nonpr = 0, s = (unsigned char *)str; *s != '\0'; s++)
37                 if (*s == '\\' || strchr(quote_chars, *s))
38                         nonpr++;
39         if (nonpr == 0)
40                 return str;
41
42         if (high_water_alloc((void **)&quoted_str, &quoted_str_len,
43                              (s - (unsigned char *)str) + nonpr * 3 + 1))
44                 return NULL;
45         for (s = (unsigned char *)str, q = quoted_str; *s != '\0'; s++) {
46                 if (*s == '\\' || strchr(quote_chars, *s)) {
47                         *q++ = '\\';
48                         *q++ = '0' + ((*s >> 6)    );
49                         *q++ = '0' + ((*s >> 3) & 7);
50                         *q++ = '0' + ((*s     ) & 7);
51                 } else
52                         *q++ = *s;
53         }
54         *q++ = '\0';
55
56         return quoted_str;
57 }