gcc config
[prop.git] / lib-src / strings / charesc.cc
blobf1fb7a558e577961e99b8b81047929c9f9264173
1 //////////////////////////////////////////////////////////////////////////////
2 // NOTICE:
3 //
4 // ADLib, Prop and their related set of tools and documentation are in the
5 // public domain. The author(s) of this software reserve no copyrights on
6 // the source code and any code generated using the tools. You are encouraged
7 // to use ADLib and Prop to develop software, in both academic and commercial
8 // settings, and are free to incorporate any part of ADLib and Prop into
9 // your programs.
11 // Although you are under no obligation to do so, we strongly recommend that
12 // you give away all software developed using our tools.
14 // We also ask that credit be given to us when ADLib and/or Prop are used in
15 // your programs, and that this notice be preserved intact in all the source
16 // code.
18 // This software is still under development and we welcome any suggestions
19 // and help from the users.
21 // Allen Leung
22 // 1994
23 //////////////////////////////////////////////////////////////////////////////
25 #include <ctype.h>
26 #include <AD/strings/charesc.h>
28 char * quote_string (char * buf, const char * s)
29 { while (*s)
30 { char c;
31 s = parse_char(s,c);
32 buf = print_char(buf,c);
34 *buf = '\0';
35 return buf;
38 const char * parse_char(const char * s, char& c)
39 { if (*s == '\\') {
40 s++;
41 switch (*s) {
42 case '0': case '1':
43 { char ch; int count;
44 for (ch = 0, count = 0; *s >= '0' && *s <= '7' && count < 3; s++, count++)
45 ch = ch * 8 + *s - '0';
46 c = ch; return s;
48 case 'n': c = '\n'; break;
49 case 't': c = '\t'; break;
50 case 'x':
51 case 'X':
52 { int digit1;
53 int digit2;
54 s++;
55 if (isdigit(*s)) digit1 = *s - '0';
56 else if (*s >= 'a' && *s <= 'f') digit1 = *s - 'a' + 10;
57 else if (*s >= 'A' && *s <= 'F') digit1 = *s - 'A' + 10;
58 else digit1 = 0;
59 s++;
60 if (isdigit(*s)) digit2 = *s - '0';
61 else if (*s >= 'a' && *s <= 'f') digit2 = *s - 'a' + 10;
62 else if (*s >= 'A' && *s <= 'F') digit2 = *s - 'A' + 10;
63 else digit2 = 0;
64 c = digit1 * 16 + digit2;
65 return s+1;
66 } break;
67 default: c = *s;
69 } else c = *s;
70 return s + 1;
73 char * print_char(char * s, char c)
75 if (c == '\n') {
76 *s++ = '\\'; *s++ = 'n'; *s = '\0'; return s;
77 } else if (c == '\t') {
78 *s++ = '\\'; *s++ = 't'; *s = '\0'; return s;
79 } else if (c == '\'' || c == '\"' || c == '\\') {
80 *s++ = '\\'; *s++ = c; *s= '\0'; return s;
81 } else if (isprint(c)) {
82 *s++ = c; *s = '\0'; return s;
83 } else {
84 unsigned char ch = c;
85 s[0] = '\\';
86 s[1] = ch / 64 + '0';
87 s[2] = (ch / 8) % 8 + '0';
88 s[3] = ch % 8 + '0';
89 s[4] = '\0';
90 return s + 4;
94 const char * print_char(char c)
95 { static char buf[10];
96 print_char(buf,c);
97 return buf;