text
stringlengths
0
14.1k
return mbuf_write(dst, buf, 5);
}
return mbuf_write_byte(dst, ec);
}
static bool render_string(struct RenderState *rs, struct JsonValue *jv)
{
const char *s, *last;
const char *val = get_cstring(jv);
size_t len = jv->u.v_size;
const char *end = val + len;
unsigned int c;
/* start quote */
if (!mbuf_write_byte(rs->dst, '""'))
return false;
for (s = last = val; s < end; s++) {
if (*s == '""' || *s == '\\' || (unsigned char)*s < 0x20 ||
/* Valid in JSON, but not in JS:
\u2028 - Line separator
\u2029 - Paragraph separator */
((unsigned char)s[0] == 0xE2 && (unsigned char)s[1] == 0x80 &&
((unsigned char)s[2] == 0xA8 || (unsigned char)s[2] == 0xA9)))
{
/* flush */
if (last < s) {
if (!mbuf_write(rs->dst, last, s - last))
return false;
}
if ((unsigned char)s[0] == 0xE2) {
c = 0x2028 + ((unsigned char)s[2] - 0xA8);
last = s + 3;
} else {
c = (unsigned char)*s;
last = s + 1;
}
/* output escaped char */
if (!escape_char(rs->dst, c))
return false;
}
}
/* flush */
if (last < s) {
if (!mbuf_write(rs->dst, last, s - last))
return false;
}
/* final quote */
if (!mbuf_write_byte(rs->dst, '""'))
return false;
return true;
}
/*
* Render complex values
*/
struct ElemWriterState {
struct RenderState *rs;
char sep;
};
static bool list_elem_writer(void *arg, struct JsonValue *elem)
{
struct ElemWriterState *state = arg;
if (state->sep && !mbuf_write_byte(state->rs->dst, state->sep))
return false;
state->sep = ',';
return render_any(state->rs, elem);
}
static bool render_list(struct RenderState *rs, struct JsonValue *list)
{
struct ElemWriterState state;
state.rs = rs;
state.sep = 0;
if (!mbuf_write_byte(rs->dst, '['))
return false;
if (!json_list_iter(list, list_elem_writer, &state))
return false;
if (!mbuf_write_byte(rs->dst, ']'))
return false;
return true;
}
static bool dict_elem_writer(void *ctx, struct JsonValue *key, struct JsonValue *val)
{
struct ElemWriterState *state = ctx;
if (state->sep && !mbuf_write_byte(state->rs->dst, state->sep))
return false;