Skip to content

Commit 595058a

Browse files
committed
unit1 answer
1 parent 5a4fcab commit 595058a

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

tutorial01/leptjson.c

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,21 +24,47 @@ static int lept_parse_null(lept_context* c, lept_value* v) {
2424
return LEPT_PARSE_OK;
2525
}
2626

27+
static int lept_parse_true(lept_context* c, lept_value* v) {
28+
EXPECT(c, 't');
29+
if (c->json[0] != 'r' || c->json[1] != 'u' || c->json[2] != 'e')
30+
return LEPT_PARSE_INVALID_VALUE;
31+
c->json += 3;
32+
v->type = LEPT_TRUE;
33+
return LEPT_PARSE_OK;
34+
}
35+
36+
static int lept_parse_false(lept_context* c, lept_value* v) {
37+
EXPECT(c, 'f');
38+
if (c->json[0] != 'a' || c->json[1] != 'l' || c->json[2] != 's' || c->json[3] != 'e')
39+
return LEPT_PARSE_INVALID_VALUE;
40+
c->json += 4;
41+
v->type = LEPT_FALSE;
42+
return LEPT_PARSE_OK;
43+
}
44+
2745
static int lept_parse_value(lept_context* c, lept_value* v) {
2846
switch (*c->json) {
2947
case 'n': return lept_parse_null(c, v);
48+
case 't': return lept_parse_true(c, v);
49+
case 'f': return lept_parse_false(c, v);
3050
case '\0': return LEPT_PARSE_EXPECT_VALUE;
3151
default: return LEPT_PARSE_INVALID_VALUE;
3252
}
3353
}
3454

3555
int lept_parse(lept_value* v, const char* json) {
3656
lept_context c;
57+
int ret;
3758
assert(v != NULL);
3859
c.json = json;
3960
v->type = LEPT_NULL;
4061
lept_parse_whitespace(&c);
41-
return lept_parse_value(&c, v);
62+
if ((ret = lept_parse_value(&c,v)) == LEPT_PARSE_OK) {
63+
lept_parse_whitespace(&c);
64+
if (*c.json != '\0')
65+
ret = LEPT_PARSE_ROOT_NOT_SINGULAR;
66+
}
67+
return ret;
4268
}
4369

4470
lept_type lept_get_type(const lept_value* v) {

tutorial01/test.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,20 @@ static void test_parse_null() {
2727
EXPECT_EQ_INT(LEPT_NULL, lept_get_type(&v));
2828
}
2929

30+
static void test_parse_true() {
31+
lept_value v;
32+
v.type = LEPT_FALSE;
33+
EXPECT_EQ_INT(LEPT_PARSE_OK, lept_parse(&v, "true"));
34+
EXPECT_EQ_INT(LEPT_TRUE, lept_get_type(&v));
35+
}
36+
37+
static void test_parse_false() {
38+
lept_value v;
39+
v.type = LEPT_TRUE;
40+
EXPECT_EQ_INT(LEPT_PARSE_OK, lept_parse(&v, "false"));
41+
EXPECT_EQ_INT(LEPT_FALSE, lept_get_type(&v));
42+
}
43+
3044
static void test_parse_expect_value() {
3145
lept_value v;
3246

@@ -59,6 +73,8 @@ static void test_parse_root_not_singular() {
5973

6074
static void test_parse() {
6175
test_parse_null();
76+
test_parse_true();
77+
test_parse_false();
6278
test_parse_expect_value();
6379
test_parse_invalid_value();
6480
test_parse_root_not_singular();

0 commit comments

Comments
 (0)