Debian Codegraph @

src/compose/escape.h

raw
1 /*
2 * Copyright © 2023 Pierre Le Marre <[email protected]>
3 * SPDX-License-Identifier: MIT
4 */
5 #pragma once
6
7 #include "config.h"
8
9 #include <stdlib.h>
10
11 #include "src/utils.h"
12
13 /* Ad-hoc escaping for UTF-8 string
14 *
15 * Note that it only escapes the strict minimum to get a valid Compose file.
16 * It also escapes hexadecimal digits after an hexadecimal escape. This is not
17 * strictly needed by the current implementation: "\x0abcg" parses as "␊bcg",
18 * but better be cautious than sorry and produce "\x0a\x62\x63g" instead.
19 * In the latter string there is no ambiguity and no need to know the maximum
20 * number of digits supported by the escape sequence.
21 */
22 static inline char*
23 escape_utf8_string_literal(const char *from)
24 {
25 const size_t length = strlen(from);
26 /* Longest escape is converting ASCII character to "\xNN" */
27 char* to = calloc(4 * length + 1, sizeof(*to));
28 if (!to)
29 return NULL;
30
31 size_t t = 0;
32 bool previous_is_hex_escape = false;
33 uint8_t nbytes = 0;
34 for (size_t f = 0; f < length;) {
35 if ((unsigned char) from[f] < 0x80) {
36 /* ASCII */
37 if (from[f] <= 0x10 || from[f] == 0x7f ||
38 (is_xdigit(from[f]) && previous_is_hex_escape))
39 {
40 /* Control character or
41 hexadecimal digit following an hexadecimal escape */
42 snprintf_safe(&to[t], 5, "\\x%02x", from[f]);
43 t += 4;
44 previous_is_hex_escape = true;
45 } else if (from[f] == '"' || from[f] == '\\') {
46 /* Quote and backslash */
47 snprintf_safe(&to[t], 3, "\\%c", from[f]);
48 t += 2;
49 previous_is_hex_escape = false;
50 } else {
51 /* Other characters */
52 to[t++] = from[f];
53 previous_is_hex_escape = false;
54 }
55 f++;
56 continue;
57 }
58 /* Test next byte for the next Unicode codepoint’s bytes count */
59 else if ((unsigned char) from[f] < 0xe0)
60 nbytes = 2;
61 else if ((unsigned char) from[f] < 0xf0)
62 nbytes = 3;
63 else
64 nbytes = 4;
65 memcpy(&to[t], &from[f], nbytes);
66 t += nbytes;
67 f += nbytes;
68 previous_is_hex_escape = false;
69 }
70 to[t++] = '\0';
71 char* ret = realloc(to, t);
72 if (!ret)
73 free(to);
74 return ret;
75 }