jescape.c 698 Bytes
Newer Older
Julian Rother's avatar
Julian Rother committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <stdlib.h>

#include "../util.h"

char *jescape(char *s)
{
	int i;
	char *ptr;
	size_t size;
	FILE *stream;
	if (!(stream = open_memstream(&ptr, &size)))
		exit(99);
	for (; *s; s ++)
		switch (*s)
		{
			case '"':
				fputs("\\\"", stream); break;
			case '\\':
				fputs("\\\\", stream); break;
			case '\b':
				fputs("\\b", stream); break;
			case '\f':
				fputs("\\f", stream); break;
			case '\n':
				fputs("\\n", stream); break;
			case '\r':
				fputs("\\r", stream); break;
			case '\t':
				fputs("\\t", stream); break;
			default:
				if (*s <= 0x1f)
					fprintf(stream, "\\u%04x", *s);
				else
					fputc(*s, stream);
		}
	fclose(stream);
	return ptr;
}