1 #include <u.h>
2 #include <libc.h>
3
4 int (*doquote)(int);
5
6 extern int _needsquotes(char*, int*);
7 extern int _runeneedsquotes(Rune*, int*);
8
9 char*
unquotestrdup(char * s)10 unquotestrdup(char *s)
11 {
12 char *t, *ret;
13 int quoting;
14
15 ret = s = strdup(s); /* return unquoted copy */
16 if(ret == nil)
17 return ret;
18 quoting = 0;
19 t = s; /* s is output string, t is input string */
20 while(*t!='\0' && (quoting || (*t!=' ' && *t!='\t'))){
21 if(*t != '\''){
22 *s++ = *t++;
23 continue;
24 }
25 /* *t is a quote */
26 if(!quoting){
27 quoting = 1;
28 t++;
29 continue;
30 }
31 /* quoting and we're on a quote */
32 if(t[1] != '\''){
33 /* end of quoted section; absorb closing quote */
34 t++;
35 quoting = 0;
36 continue;
37 }
38 /* doubled quote; fold one quote into two */
39 t++;
40 *s++ = *t++;
41 }
42 if(t != s)
43 memmove(s, t, strlen(t)+1);
44 return ret;
45 }
46
47 Rune*
unquoterunestrdup(Rune * s)48 unquoterunestrdup(Rune *s)
49 {
50 Rune *t, *ret;
51 int quoting;
52
53 ret = s = runestrdup(s); /* return unquoted copy */
54 if(ret == nil)
55 return ret;
56 quoting = 0;
57 t = s; /* s is output string, t is input string */
58 while(*t!='\0' && (quoting || (*t!=' ' && *t!='\t'))){
59 if(*t != '\''){
60 *s++ = *t++;
61 continue;
62 }
63 /* *t is a quote */
64 if(!quoting){
65 quoting = 1;
66 t++;
67 continue;
68 }
69 /* quoting and we're on a quote */
70 if(t[1] != '\''){
71 /* end of quoted section; absorb closing quote */
72 t++;
73 quoting = 0;
74 continue;
75 }
76 /* doubled quote; fold one quote into two */
77 t++;
78 *s++ = *t++;
79 }
80 if(t != s)
81 memmove(s, t, (runestrlen(t)+1)*sizeof(Rune));
82 return ret;
83 }
84
85 char*
quotestrdup(char * s)86 quotestrdup(char *s)
87 {
88 char *t, *u, *ret;
89 int quotelen;
90 Rune r;
91
92 if(_needsquotes(s, "elen) == 0)
93 return strdup(s);
94
95 ret = malloc(quotelen+1);
96 if(ret == nil)
97 return nil;
98 u = ret;
99 *u++ = '\'';
100 for(t=s; *t; t++){
101 r = *t;
102 if(r == L'\'')
103 *u++ = r; /* double the quote */
104 *u++ = r;
105 }
106 *u++ = '\'';
107 *u = '\0';
108 return ret;
109 }
110
111 Rune*
quoterunestrdup(Rune * s)112 quoterunestrdup(Rune *s)
113 {
114 Rune *t, *u, *ret;
115 int quotelen;
116 Rune r;
117
118 if(_runeneedsquotes(s, "elen) == 0)
119 return runestrdup(s);
120
121 ret = malloc((quotelen+1)*sizeof(Rune));
122 if(ret == nil)
123 return nil;
124 u = ret;
125 *u++ = '\'';
126 for(t=s; *t; t++){
127 r = *t;
128 if(r == L'\'')
129 *u++ = r; /* double the quote */
130 *u++ = r;
131 }
132 *u++ = '\'';
133 *u = '\0';
134 return ret;
135 }
136