1 #ifndef __TEST_UTIL_H__
2 #define __TEST_UTIL_H__
3 
4 #include "../jsmn.c"
5 
vtokeq(const char * s,jsmntok_t * t,int numtok,va_list ap)6 static int vtokeq(const char *s, jsmntok_t *t, int numtok, va_list ap) {
7 	if (numtok > 0) {
8 		int i, start, end, size;
9 		int type;
10 		char *value;
11 
12 		size = -1;
13 		value = NULL;
14 		for (i = 0; i < numtok; i++) {
15 			type = va_arg(ap, int);
16 			if (type == JSMN_STRING) {
17 				value = va_arg(ap, char *);
18 				size = va_arg(ap, int);
19 				start = end = -1;
20 			} else if (type == JSMN_PRIMITIVE) {
21 				value = va_arg(ap, char *);
22 				start = end = size = -1;
23 			} else {
24 				start = va_arg(ap, int);
25 				end = va_arg(ap, int);
26 				size = va_arg(ap, int);
27 				value = NULL;
28 			}
29 			if (t[i].type != type) {
30 				printf("token %d type is %d, not %d\n", i, t[i].type, type);
31 				return 0;
32 			}
33 			if (start != -1 && end != -1) {
34 				if (t[i].start != start) {
35 					printf("token %d start is %d, not %d\n", i, t[i].start, start);
36 					return 0;
37 				}
38 				if (t[i].end != end ) {
39 					printf("token %d end is %d, not %d\n", i, t[i].end, end);
40 					return 0;
41 				}
42 			}
43 			if (size != -1 && t[i].size != size) {
44 				printf("token %d size is %d, not %d\n", i, t[i].size, size);
45 				return 0;
46 			}
47 
48 			if (s != NULL && value != NULL) {
49 				const char *p = s + t[i].start;
50 				if (strlen(value) != t[i].end - t[i].start ||
51 						strncmp(p, value, t[i].end - t[i].start) != 0) {
52 					printf("token %d value is %.*s, not %s\n", i, t[i].end-t[i].start,
53 							s+t[i].start, value);
54 					return 0;
55 				}
56 			}
57 		}
58 	}
59 	return 1;
60 }
61 
tokeq(const char * s,jsmntok_t * tokens,int numtok,...)62 static int tokeq(const char *s, jsmntok_t *tokens, int numtok, ...) {
63 	int ok;
64 	va_list args;
65 	va_start(args, numtok);
66 	ok = vtokeq(s, tokens, numtok, args);
67 	va_end(args);
68 	return ok;
69 }
70 
parse(const char * s,int status,int numtok,...)71 static int parse(const char *s, int status, int numtok, ...) {
72 	int r;
73 	int ok = 1;
74 	va_list args;
75 	jsmn_parser p;
76 	jsmntok_t *t = malloc(numtok * sizeof(jsmntok_t));
77 
78 	jsmn_init(&p);
79 	r = jsmn_parse(&p, s, strlen(s), t, numtok);
80 	if (r != status) {
81 		printf("status is %d, not %d\n", r, status);
82 		return 0;
83 	}
84 
85 	if (status >= 0) {
86 		va_start(args, numtok);
87 		ok = vtokeq(s, t, numtok, args);
88 		va_end(args);
89 	}
90 	free(t);
91 	return ok;
92 }
93 
94 #endif /* __TEST_UTIL_H__ */
95