aboutsummaryrefslogtreecommitdiffstats
path: root/wsutil/str_util.c
diff options
context:
space:
mode:
authorJoão Valverde <j@v6e.pt>2021-11-29 13:52:09 +0000
committerWireshark GitLab Utility <gerald+gitlab-utility@wireshark.org>2021-11-29 17:47:53 +0000
commit44121e2c3b28e4550c5011668253b0025811b08a (patch)
tree799c1a9d871bd29cf7300195db42e27115f6d22b /wsutil/str_util.c
parente11cdf2f465c9f33fbf3611c2a95e40e3433eff2 (diff)
Move escape_string() to wsutil
Move this utility function to wsutil. Rename to ws_escape_string(). Also add tests.
Diffstat (limited to 'wsutil/str_util.c')
-rw-r--r--wsutil/str_util.c65
1 files changed, 65 insertions, 0 deletions
diff --git a/wsutil/str_util.c b/wsutil/str_util.c
index cc4b24fcd2..651e457816 100644
--- a/wsutil/str_util.c
+++ b/wsutil/str_util.c
@@ -265,6 +265,71 @@ printable_char_or_period(gchar c)
return g_ascii_isprint(c) ? c : '.';
}
+size_t
+ws_escape_string_len(const char *string)
+{
+ const char *p;
+ gchar c;
+ size_t repr_len;
+
+ repr_len = 0;
+ for (p = string; (c = *p) != '\0'; p++) {
+ /* Backslashes and double-quotes must
+ * be escaped */
+ if (c == '\\' || c == '"') {
+ repr_len += 2;
+ }
+ /* Values that can't nicely be represented
+ * in ASCII need to be escaped. */
+ else if (!g_ascii_isprint(c)) {
+ /* c --> \xNN */
+ repr_len += 4;
+ }
+ /* Other characters are just passed through. */
+ else {
+ repr_len++;
+ }
+ }
+ return repr_len + 2; /* string plus leading and trailing quotes */
+}
+
+char *
+ws_escape_string(char *buf, const char *string)
+{
+ const gchar *p;
+ gchar c;
+ char *bufp;
+ char hexbuf[3];
+
+ bufp = buf;
+ *bufp++ = '"';
+ for (p = string; (c = *p) != '\0'; p++) {
+ /* Backslashes and double-quotes must
+ * be escaped. */
+ if (c == '\\' || c == '"') {
+ *bufp++ = '\\';
+ *bufp++ = c;
+ }
+ /* Values that can't nicely be represented
+ * in ASCII need to be escaped. */
+ else if (!g_ascii_isprint(c)) {
+ /* c --> \xNN */
+ g_snprintf(hexbuf,sizeof(hexbuf), "%02x", (unsigned char) c);
+ *bufp++ = '\\';
+ *bufp++ = 'x';
+ *bufp++ = hexbuf[0];
+ *bufp++ = hexbuf[1];
+ }
+ /* Other characters are just passed through. */
+ else {
+ *bufp++ = c;
+ }
+ }
+ *bufp++ = '"';
+ *bufp = '\0';
+ return buf;
+}
+
/*
* Editor modelines - https://www.wireshark.org/tools/modelines.html
*