From 39e8fc6d24173d723c675d564b3487b0f9d98fad Mon Sep 17 00:00:00 2001 From: Veit Heller Date: Thu, 29 Jul 2021 08:30:42 +0200 Subject: [PATCH] fix: escape quotes in String.prn (#1287) --- core/carp_string.h | 24 +++++++++++++++++++++--- test/string.carp | 4 ++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/core/carp_string.h b/core/carp_string.h index 88380542..1d73c241 100644 --- a/core/carp_string.h +++ b/core/carp_string.h @@ -8,7 +8,7 @@ String String_allocate(int len, char byte) { * String_alloc(10, "a") == "aaaaaaaaaa" */ String ptr = CARP_MALLOC(len + 1); - if( ptr!=NULL) { + if (ptr != NULL) { // calling memset(NULL,...) would exercise undefined behaviour... memset(ptr, byte, len); ptr[len] = '\0'; @@ -107,10 +107,28 @@ String String_str(const String *s) { return String_copy(s); } +int count_occurrences(String s, char c) { + int res = 0; + while (*s != '\0') { + if (*s == c) res++; + s++; + } + return res; +} + String String_prn(const String *s) { - int n = strlen(*s) + 4; + int n = strlen(*s) + 4 + count_occurrences(*s, '"'); String buffer = CARP_MALLOC(n); - sprintf(buffer, "@\"%s\"", *s); + buffer[0] = '@'; + buffer[1] = '"'; + String c = *s; + for (int i = 2; i < n - 2; i++) { + if (*c == '"') buffer[i++] = '\\'; + buffer[i] = *c; + c++; + } + buffer[n - 2] = '"'; + buffer[n - 1] = '\0'; return buffer; } diff --git a/test/string.carp b/test/string.carp index 1598a29c..728c42af 100644 --- a/test/string.carp +++ b/test/string.carp @@ -331,4 +331,8 @@ "HäLLO WöRLD" &(ascii-to-upper "HälLo WöRld") "ascii-to-upper works for valid UTF-8" ) + (assert-equal test + "@\"\\\"h\\\"i\\\"\"" + &(prn "\"h\"i\"") + "prn works on quoted strings") )