1 /* MIT (BSD) license - see LICENSE file for details */
2 #include <ccan/json_escape/json_escape.h>
5 struct json_escape *json_escape_string_(const tal_t *ctx,
6 const void *bytes, size_t len)
8 struct json_escape *esc;
10 esc = (void *)tal_arr_label(ctx, char, len + 1,
11 TAL_LABEL(struct json_escape, ""));
12 memcpy(esc->s, bytes, len);
17 bool json_escape_eq(const struct json_escape *a, const struct json_escape *b)
19 return streq(a->s, b->s);
22 static struct json_escape *escape(const tal_t *ctx,
23 const char *str TAKES,
27 struct json_escape *esc;
30 /* Worst case: all \uXXXX */
31 esc = (struct json_escape *)tal_arr(ctx, char, len * 6 + 1);
33 for (i = n = 0; i < len; i++, n++) {
53 /* Don't double-escape standard escapes. */
67 && cisxdigit(str[i+2])
68 && cisxdigit(str[i+3])
69 && cisxdigit(str[i+4])
70 && cisxdigit(str[i+5])) {
71 memcpy(esc->s + n, str + i, 6);
81 if ((unsigned)str[i] < ' ' || str[i] == 127) {
82 snprintf(esc->s + n, 7, "\\u%04X", str[i]);
100 struct json_escape *json_partial_escape(const tal_t *ctx, const char *str TAKES)
102 return escape(ctx, str, strlen(str), true);
105 struct json_escape *json_escape(const tal_t *ctx, const char *str TAKES)
107 return escape(ctx, str, strlen(str), false);
110 struct json_escape *json_escape_len(const tal_t *ctx, const char *str TAKES,
113 return escape(ctx, str, len, false);
116 /* By policy, we don't handle \u. Use UTF-8. */
117 const char *json_escape_unescape(const tal_t *ctx, const struct json_escape *esc)
119 char *unesc = tal_arr(ctx, char, strlen(esc->s) + 1);
122 for (i = n = 0; esc->s[i]; i++, n++) {
123 if (esc->s[i] != '\\') {
124 unesc[n] = esc->s[i];
148 unesc[n] = esc->s[i];
151 return tal_free(unesc);