#define AL_LOG_SECTION "file_ext" #include #include "file_ext.h" bool nn_file_open_and_read_wholly(str *path, str *out, bool lock) { struct nn_file file; if (!nn_file_open(&file, path, lock ? NNWT_FILE_LOCK : NNWT_FILE_READONLY)) { return false; } s32 ret = nn_file_read_as_str(&file, out); nn_file_close(&file); return ret != -1; } bool nn_file_open_and_replace(str *path, str *buf, bool lock) { struct nn_file file; if (!nn_file_open(&file, path, lock ? NNWT_FILE_LOCK : 0)) { return false; } s32 ret = nn_file_replace(&file, buf); nn_file_close(&file); return ret != -1; } json_t *nn_file_open_as_json(str *path) { str s; if (!nn_file_open_and_read_wholly(path, &s, false)) { return NULL; } json_error_t error; json_t *root = json_loadb(s.data, s.length, 0, &error); if (!root) { log_error("json_loadb(%.*s, %u) failed (%s)", al_str_x(path), s.length, error.text); } al_str_free(&s); return root; } bool nn_dump_json_and_decref(str *path, json_t *root) { str s; size_t size = json_dumpb(root, NULL, 0, JSON_INDENT(4)); al_str_sized(&s, size); s.length = json_dumpb(root, s.data, size, JSON_INDENT(4)); if (s.length == 0) { json_decref(root); return false; } bool ret = nn_file_open_and_replace(path, &s, false); al_str_free(&s); json_decref(root); return ret; }