From: Michael Tremer Date: Thu, 19 Oct 2023 10:26:11 +0000 (+0000) Subject: util: Implement parsing JSON from a buffer X-Git-Tag: 0.9.30~1444 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=7af740f4fc6685454db97d0ebca692b0d53e494b;p=pakfire.git util: Implement parsing JSON from a buffer Signed-off-by: Michael Tremer --- diff --git a/src/libpakfire/include/pakfire/util.h b/src/libpakfire/include/pakfire/util.h index a7a2a849e..47abc3f5d 100644 --- a/src/libpakfire/include/pakfire/util.h +++ b/src/libpakfire/include/pakfire/util.h @@ -95,6 +95,8 @@ int pakfire_archive_copy_data_to_buffer(struct pakfire* pakfire, struct archive* // JSON Stuff +struct json_object* pakfire_json_parse(struct pakfire_ctx* ctx, + const char* buffer, const size_t length); struct json_object* pakfire_json_parse_from_file(struct pakfire_ctx* ctx, const char* path); int pakfire_json_add_string(struct pakfire* pakfire, struct json_object* json, const char* name, const char* value); diff --git a/src/libpakfire/util.c b/src/libpakfire/util.c index b67de4ae4..1368a4743 100644 --- a/src/libpakfire/util.c +++ b/src/libpakfire/util.c @@ -705,16 +705,10 @@ int pakfire_archive_copy_data_to_buffer(struct pakfire* pakfire, struct archive* // JSON Stuff -static struct json_object* pakfire_json_parse(struct pakfire_ctx* ctx, FILE* f) { +struct json_object* pakfire_json_parse(struct pakfire_ctx* ctx, + const char* buffer, const size_t length) { struct json_tokener* tokener = NULL; struct json_object* json = NULL; - char* buffer = NULL; - size_t length; - - // Read everything into memory - int r = pakfire_read_file_into_buffer(f, &buffer, &length); - if (r) - goto ERROR; // Create tokener tokener = json_tokener_new(); @@ -723,7 +717,7 @@ static struct json_object* pakfire_json_parse(struct pakfire_ctx* ctx, FILE* f) goto ERROR; } - // Parse JSON from path + // Parse JSON from buffer json = json_tokener_parse_ex(tokener, buffer, length); if (!json) { enum json_tokener_error error = json_tokener_get_error(tokener); @@ -739,21 +733,38 @@ static struct json_object* pakfire_json_parse(struct pakfire_ctx* ctx, FILE* f) ); ERROR: - if (buffer) - free(buffer); - if (tokener) json_tokener_free(tokener); return json; } +static struct json_object* pakfire_json_parse_file(struct pakfire_ctx* ctx, FILE* f) { + struct json_object* json = NULL; + char* buffer = NULL; + size_t length = 0; + + // Read everything into memory + int r = pakfire_read_file_into_buffer(f, &buffer, &length); + if (r) + goto ERROR; + + // Parse + json = pakfire_json_parse(ctx, buffer, length); + +ERROR: + if (buffer) + free(buffer); + + return json; +} + struct json_object* pakfire_json_parse_from_file(struct pakfire_ctx* ctx, const char* path) { FILE* f = fopen(path, "r"); if (!f) return NULL; - struct json_object* json = pakfire_json_parse(ctx, f); + struct json_object* json = pakfire_json_parse_file(ctx, f); fclose(f); return json;