[ruamoko] Add a builtin to quote strings

All unprintable chars are converted to either standard escape sequences
or \xHH.
This commit is contained in:
Bill Currie 2020-04-01 21:28:25 +09:00
parent a09eabeb4d
commit 6b9d4a747d
3 changed files with 42 additions and 0 deletions

View file

@ -208,6 +208,45 @@ bi_str_char (progs_t *pr)
R_INT (pr) = str[ind];
}
static void
bi_str_quote (progs_t *pr)
{
const char *str = P_GSTRING (pr, 0);
// can have up to 4 chars per char (a -> \x61)
char *quote = alloca (strlen (str) * 4 + 1);
char *q = quote;
char c;
int h;
while ((c = *str++)) {
if (c >= ' ' && c < 127 && c != '\"') {
*q++ = c;
} else {
*q++ = '\\';
switch (c) {
case '\a': c = 'a'; break;
case '\b': c = 'b'; break;
case '\f': c = 'f'; break;
case '\n': c = 'n'; break;
case '\r': c = 'r'; break;
case '\t': c = 't'; break;
case '\"': c = '\"'; break;
default:
*q++ = 'x';
h = (c & 0xf0) >> 4;
*q++ = h > 9 ? h + 'a' - 10 : h + '0';
h = (c & 0x0f);
c = h > 9 ? h + 'a' - 10 : h + '0';
break;
}
*q++ = c;
}
}
*q++ = 0;
RETURN_STRING (pr, quote);
}
static builtin_t builtins[] = {
{"strlen", bi_strlen, -1},
{"sprintf", bi_sprintf, -1},
@ -224,6 +263,7 @@ static builtin_t builtins[] = {
{"str_mid|*ii", bi_str_mid, -1},
{"str_str", bi_str_str, -1},
{"str_char", bi_str_char, -1},
{"str_quote", bi_str_quote, -1},
{0}
};

View file

@ -16,5 +16,6 @@
@extern @overload string str_mid (string str, int start, int len);
@extern string str_str (string haystack, string needle);
@extern int str_char (string str, int ind);
string str_quote (string str);
#endif//__ruamoko_string_h

View file

@ -15,3 +15,4 @@ string (string str, int start) str_mid = #0;
string (string str, int start, int len) str_mid = #0;
string (string haystack, string needle) str_str = #0;
int str_char (string str, int ind) = #0;
string str_quote (string str) = #0;