CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/Common/Data/Format/JSONReader.h
Views: 1401
1
#pragma once
2
3
#include <cstring>
4
#include <string>
5
#include <vector>
6
7
#include "ext/gason/gason.h"
8
#include "Common/Common.h"
9
10
namespace json {
11
12
struct JsonGet {
13
JsonGet(const JsonValue &value) : value_(value) {}
14
15
int numChildren() const;
16
const JsonNode *get(const char *child_name) const;
17
const JsonNode *get(const char *child_name, JsonTag type) const;
18
const JsonNode *getArray(const char *child_name) const {
19
return get(child_name, JSON_ARRAY);
20
}
21
const JsonGet getDict(const char *child_name) const {
22
return JsonGet(get(child_name, JSON_OBJECT)->value);
23
}
24
const char *getStringOrNull(const char *child_name) const;
25
const char *getStringOr(const char *child_name, const char *default_value) const;
26
bool getString(const char *child_name, std::string *output) const;
27
bool getStringVector(std::vector<std::string> *vec) const;
28
double getFloat(const char *child_name) const;
29
double getFloat(const char *child_name, double default_value) const;
30
int getInt(const char *child_name) const;
31
int getInt(const char *child_name, int default_value) const;
32
bool getBool(const char *child_name) const;
33
bool getBool(const char *child_name, bool default_value) const;
34
35
bool hasChild(const char *child_name, JsonTag child_type) const {
36
return get(child_name, child_type) != nullptr;
37
}
38
39
operator bool() const {
40
return value_.getTag() != JSON_NULL;
41
}
42
43
JsonValue value_;
44
};
45
46
// Easy-wrapper
47
class JsonReader {
48
public:
49
JsonReader(const std::string &filename);
50
// Makes a copy, after this returns you can free the input buffer. Zero termination is not necessary.
51
JsonReader(const char *data, size_t size) {
52
buffer_ = (char *)malloc(size + 1);
53
if (buffer_) {
54
memcpy(buffer_, data, size);
55
buffer_[size] = 0;
56
parse();
57
}
58
}
59
JsonReader(const JsonNode *node) {
60
ok_ = true;
61
}
62
63
~JsonReader() {
64
free(buffer_);
65
}
66
67
bool ok() const { return ok_; }
68
69
JsonGet root() { return root_.getTag() == JSON_OBJECT ? JsonGet(root_) : JsonGet(JSON_NULL); }
70
const JsonValue rootArray() const { return root_.getTag() == JSON_ARRAY ? root_ : JSON_NULL; }
71
72
const JsonValue rootValue() const { return root_; }
73
74
private:
75
bool parse();
76
77
char *buffer_ = nullptr;
78
JsonAllocator alloc_;
79
JsonValue root_;
80
bool ok_ = false;
81
82
DISALLOW_COPY_AND_ASSIGN(JsonReader);
83
};
84
85
} // namespace json
86
87