From 95ec49cb709219b1813dfd43c4bc5df1545bd391 Mon Sep 17 00:00:00 2001 From: Leandro Pereira Date: Thu, 16 Mar 2017 10:11:00 -0700 Subject: [PATCH] lib: json: Simplify lexing of "true", "false", and "null" tokens Roll the loop in an accept_run() function and use it to match "rue" and "alse" depending on the first character of the token. Use that to lex "ull" after finding "n" as well. This reduces the code slightly. Jira: ZEP-1607 Change-Id: Iec8ff6ae2fb79e7fe65d476d1574c5943d23e14f Signed-off-by: Leandro Pereira --- lib/json/json.c | 68 ++++++++++++++++--------------------------------- 1 file changed, 22 insertions(+), 46 deletions(-) diff --git a/lib/json/json.c b/lib/json/json.c index 949c0eb95ae..41b7586eee9 100644 --- a/lib/json/json.c +++ b/lib/json/json.c @@ -168,75 +168,51 @@ error: return NULL; } +static int accept_run(struct lexer *lexer, const char *run) +{ + for (; *run; run++) { + if (next(lexer) != *run) { + return -EINVAL; + } + } + + return 0; +} + static void *lexer_boolean(struct lexer *lexer) { backup(lexer); switch (next(lexer)) { case 't': - if (next(lexer) != 'r') { - goto error; + if (!accept_run(lexer, "rue")) { + emit(lexer, JSON_TOK_TRUE); + return lexer_json; } - - if (next(lexer) != 'u') { - goto error; - } - - if (next(lexer) != 'e') { - goto error; - } - - emit(lexer, JSON_TOK_TRUE); - return lexer_json; + break; case 'f': - if (next(lexer) != 'a') { - goto error; + if (!accept_run(lexer, "alse")) { + emit(lexer, JSON_TOK_FALSE); + return lexer_json; } - - if (next(lexer) != 'l') { - goto error; - } - - if (next(lexer) != 's') { - goto error; - } - - if (next(lexer) != 'e') { - goto error; - } - - emit(lexer, JSON_TOK_FALSE); - return lexer_json; + break; } -error: emit(lexer, JSON_TOK_ERROR); return NULL; } static void *lexer_null(struct lexer *lexer) { - if (next(lexer) != 'u') { - goto error; - } - - if (next(lexer) != 'l') { - goto error; - } - - if (next(lexer) != 'l') { - goto error; + if (accept_run(lexer, "ull") < 0) { + emit(lexer, JSON_TOK_ERROR); + return NULL; } emit(lexer, JSON_TOK_NULL); return lexer_json; - -error: - emit(lexer, JSON_TOK_ERROR); - return NULL; } - static void *lexer_number(struct lexer *lexer) { while (true) {