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
|
#define AL_LOG_SECTION "file_ext"
#include <al/log.h>
#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;
}
|