String unescaping
h3rald h3rald@h3rald.com
Thu, 02 Jan 2025 21:07:17 +0100
3 files changed,
47 insertions(+),
1 deletions(-)
M
src/hex.h
→
src/hex.h
@@ -308,6 +308,7 @@ void hex_print_string(FILE *stream, char *value);
char *hex_bytes_to_string(const uint8_t *bytes, size_t size); char *hex_process_string(const char *value); size_t hex_min_bytes_to_encode_integer(int32_t value); +char *hex_unescape_string(const char *input); // Native symbols int hex_symbol_store(hex_context_t *ctx);
M
src/symbols.c
→
src/symbols.c
@@ -1835,7 +1835,7 @@ {
FILE *file = fopen(filename->data.str_value, "w"); if (file) { - fputs(data->data.str_value, file); + fputs(hex_unescape_string(data->data.str_value), file); fclose(file); result = 0; }
M
src/utils.c
→
src/utils.c
@@ -385,3 +385,48 @@ }
return 4; // Default to 4 bytes if no smaller size is found. } + +char *hex_unescape_string(const char *input) +{ + if (input == NULL) { + return NULL; // Handle null input + } + + // Allocate memory for the output string (worst-case size: same as input) + char *output = (char *)malloc(strlen(input) + 1); + if (output == NULL) { + fprintf(stderr, "Memory allocation failed\n"); + return NULL; + } + + const char *src = input; + char *dst = output; + + while (*src) { + if (*src == '\\' && *(src + 1)) { + switch (*(src + 1)) { + case 'n': *dst = '\n'; break; + case 't': *dst = '\t'; break; + case 'r': *dst = '\r'; break; + case '\\': *dst = '\\'; break; + case '\'': *dst = '\''; break; + case '\"': *dst = '\"'; break; + case 'b': *dst = '\b'; break; + case 'f': *dst = '\f'; break; + case 'v': *dst = '\v'; break; + default: + // If not a valid escape, copy the backslash and next character + *dst++ = *src; + *dst = *(src + 1); + } + src += 2; // Skip the escape sequence + } else { + *dst = *src; + src++; + } + dst++; + } + + *dst = '\0'; // Null-terminate the output string + return output; +}