-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleptjson.c
82 lines (69 loc) · 2.1 KB
/
leptjson.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "leptjson.h"
#include <assert.h> /*assert()*/
#include <stdlib.h> /*null*/
#define EXPECT(c, char) do {assert(*(c -> json) == (char)); c -> json++;} while(0)
typedef struct {
const char* json;
} lept_context;
/*
lept_value v;
const char json[] = ...;
int ret = lept_parse(&v, json);
*/
int lept_parse(lept_value* v, const char* json) {
lept_context c;
assert(v != NULL);
v -> type = LEPT_NULL;
c.json = json;
lept_parse_whitespace(&c);
return lept_parse_value(&c, v);
}
void lept_parse_whitespace(lept_context* c) {
const char *p = c -> json;
while(*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
p++;
c -> json = p;
}
int lept_parse_value(lept_context* c, lept_value* v) {
switch (*(c -> json)) {
case 'n':
return lept_parse_null(c, v);
case 't':
return lept_parse_true(c, v);
case 'f':
return lept_parse_false(c, v);
case '\0':
return LEPT_PARSE_EXPECT_VALUE;
default:
return LEPT_PARSE_INVALID_VALUE;
}
}
int lept_parse_null(lept_context* c, lept_value* v) {
if(c -> json[0] != 'n' || c -> json[1] != 'u' ||
c -> json[2] != 'l' || c -> json[3] != 'l')
return LEPT_PARSE_INVALID_VALUE;
c -> json += 4;
v -> type = LEPT_NULL;
return LEPT_PARSE_OK;
}
int lept_parse_true(lept_context* c, lept_value* v) {
if(c -> json[0] != 't' || c -> json[1] != 'r' ||
c -> json[2] != 'u' || c -> json[3] != 'e')
return LEPT_PARSE_INVALID_VALUE;
c -> json += 4;
v -> type = LEPT_TRUE;
return LEPT_PARSE_OK;
}
int lept_parse_false(lept_context* c, lept_value* v) {
if(c -> json[0] != 'f' || c -> json[1] != 'a' ||
c -> json[2] != 'l' || c -> json[3] != 's' ||
c -> json[4] != 'e')
return LEPT_PARSE_INVALID_VALUE;
c -> json += 5;
v -> type = LEPT_FALSE;
return LEPT_PARSE_OK;
}
lept_type lept_get_type(const lept_value* v) {
assert(v != NULL);
return v->type;
}