micro-utils/libmu/parse_escape.c

74 lines
1014 B
C
Raw Normal View History

2024-07-22 11:29:48 +00:00
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
char *mu_parse_escape(const char *prog_name, const char *src) {
size_t size = 0;
size_t src_len = strlen(src);
for (size_t i = 0; i < src_len; i++) {
size++;
size -= (src[i] == '\\');
}
char *buf = malloc(size + 1);
if (buf == NULL) {
if (prog_name)
fprintf(stderr, "%s: malloc: %s\n", prog_name, strerror(errno));
return NULL;
}
size = 0;
for (size_t i = 0; i < src_len; i++) {
char c = src[i];
if (c == '\\' && i < src_len) {
switch (src[i + 1]) {
case 'n':
c = '\n';
break;
case 'a':
c = '\a';
break;
case 't':
c = '\t';
break;
case 'b':
c = '\b';
break;
case 'e':
c = '\033';
break;
case 'r':
c = '\r';
break;
case 'f':
c = '\f';
break;
case 'v':
c = '\v';
break;
default:
c = '\\';
}
i++;
}
buf[size] = c;
size++;
}
buf[size + 1] = '\0';
return buf;
}