Skip to content

Commit 4c2fe64

Browse files
committed
updata code
1 parent 332bbde commit 4c2fe64

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

tutorial07/leptjson.c

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -347,21 +347,62 @@ int lept_parse(lept_value* v, const char* json) {
347347
}
348348

349349
static void lept_stringify_string(lept_context* c, const char* s, size_t len) {
350-
/* ... */
350+
static const char hex_digits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
351+
size_t i, size;
352+
char *head, *p;
353+
unsigned char ch;
354+
head = p = lept_context_push(c, size = 6 * len + 2);
355+
*p++ = '\"';
356+
for (i = 0; i < len; i++) {
357+
ch = (unsigned char)s[i];
358+
switch (ch) {
359+
case '\"': *p++ = '\\'; *p++ = '\"'; break;
360+
case '\\': *p++ = '\\'; *p++ = '\\'; break;
361+
case '\b': *p++ = '\\'; *p++ = 'b'; break;
362+
case '\f': *p++ = '\\'; *p++ = 'f'; break;
363+
case '\n': *p++ = '\\'; *p++ = 'n'; break;
364+
case '\r': *p++ = '\\'; *p++ = 'r'; break;
365+
case '\t': *p++ = '\\'; *p++ = 't'; break;
366+
default:
367+
if (ch < 0x20) {
368+
*p++ = '\\'; *p++ = 'u'; *p++ = '0'; *p++ = '0';
369+
*p++ = hex_digits[ch >> 4];
370+
*p++ = hex_digits[ch & 0xFF];
371+
}
372+
else {
373+
*p++ = ch;
374+
}
375+
}
376+
}
377+
*p++ = '\"';
378+
c->top -= size - (p -head);
351379
}
352380

353381
static void lept_stringify_value(lept_context* c, const lept_value* v) {
382+
size_t i;
354383
switch (v->type) {
355384
case LEPT_NULL: PUTS(c, "null", 4); break;
356385
case LEPT_FALSE: PUTS(c, "false", 5); break;
357386
case LEPT_TRUE: PUTS(c, "true", 4); break;
358387
case LEPT_NUMBER: c->top -= 32 - sprintf(lept_context_push(c, 32), "%.17g", v->u.n); break;
359388
case LEPT_STRING: lept_stringify_string(c, v->u.s.s, v->u.s.len); break;
360389
case LEPT_ARRAY:
361-
/* ... */
390+
PUTC(c, '[');
391+
for (i = 0; i < v->u.a.size; i++) {
392+
lept_stringify_value(c, &v->u.a.e[i]);
393+
if (i < v->u.a.size - 1) PUTC(c, ',');
394+
}
395+
PUTC(c, ']');
362396
break;
363397
case LEPT_OBJECT:
364-
/* ... */
398+
PUTC(c, '{');
399+
for (i = 0; i < v->u.o.size; i++) {
400+
lept_stringify_string(c, v->u.o.m[i].k, v->u.o.m[i].klen);
401+
PUTC(c, ':');
402+
lept_stringify_value(c, &v->u.o.m[i].v);
403+
if (i < v->u.o.size - 1) PUTC(c, ',');
404+
}
405+
PUTC(c, '}');
365406
break;
366407
default: assert(0 && "invalid type");
367408
}

0 commit comments

Comments
 (0)