diff --git a/libs/ruamoko/rua_string.c b/libs/ruamoko/rua_string.c index a8240a85c..6de9c5c01 100644 --- a/libs/ruamoko/rua_string.c +++ b/libs/ruamoko/rua_string.c @@ -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} }; diff --git a/ruamoko/include/string.h b/ruamoko/include/string.h index b374b8335..008e7d883 100644 --- a/ruamoko/include/string.h +++ b/ruamoko/include/string.h @@ -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 diff --git a/ruamoko/lib/string.r b/ruamoko/lib/string.r index 89ecc6aef..48a9a7bf7 100644 --- a/ruamoko/lib/string.r +++ b/ruamoko/lib/string.r @@ -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;