all repos — hex @ efce6524478d419c8c028067c52dac38f964e68d

A tiny, minimalist, slightly-esoteric concatenative programming lannguage.

String unescaping
h3rald h3rald@h3rald.com
Thu, 02 Jan 2025 21:07:17 +0100
commit

efce6524478d419c8c028067c52dac38f964e68d

parent

5006bf734e500029e9c247e4aba9dd0f2b4f6c3b

3 files changed, 47 insertions(+), 1 deletions(-)

jump to
M src/hex.hsrc/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.csrc/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.csrc/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; +}