-
Notifications
You must be signed in to change notification settings - Fork 255
/
test_libjson.cpp
79 lines (64 loc) · 2 KB
/
test_libjson.cpp
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <fstream>
#include <iostream>
#include <json-c/json.h>
#include <libnotify.h>
#ifdef __clang__
static constexpr auto COMPILER = "clang++";
#else
static constexpr auto COMPILER = "g++";
#endif
using namespace std;
struct coordinate_t {
double x;
double y;
double z;
auto operator<=>(const coordinate_t &) const = default;
friend ostream &operator<<(ostream &out, const coordinate_t &point) {
out << "coordinate_t {x: " << point.x << ", y: " << point.y
<< ", z: " << point.z << "}";
return out;
}
};
string read_file(const string &filename) {
ifstream file{filename};
if (!file.good()) {
return {};
}
return string{istreambuf_iterator<char>{file}, {}};
}
coordinate_t calc(const string &text) {
auto jobj = json_tokener_parse(text.c_str());
json_object *coordinates;
if (!json_object_object_get_ex(jobj, "coordinates", &coordinates)) {
exit(EXIT_FAILURE);
}
auto len = json_object_array_length(coordinates);
auto x = 0.0, y = 0.0, z = 0.0;
for (size_t i = 0; i < len; i++) {
auto coord = json_object_array_get_idx(coordinates, i);
json_object *xobj, *yobj, *zobj;
if (json_object_object_get_ex(coord, "x", &xobj) &&
json_object_object_get_ex(coord, "y", &yobj) &&
json_object_object_get_ex(coord, "z", &zobj)) {
x += json_object_get_double(xobj);
y += json_object_get_double(yobj);
z += json_object_get_double(zobj);
}
}
return coordinate_t{x / len, y / len, z / len};
}
int main() {
auto right = coordinate_t{2.0, 0.5, 0.25};
for (auto v : {R"({"coordinates":[{"x":2.0,"y":0.5,"z":0.25}]})",
R"({"coordinates":[{"y":0.5,"x":2.0,"z":0.25}]})"}) {
auto left = calc(v);
if (left != right) {
cerr << left << " != " << right << endl;
exit(EXIT_FAILURE);
}
}
const auto &text = read_file("/tmp/1.json");
const auto &results = notifying_invoke([&]() { return calc(text); },
"C++/{} (json-c)", COMPILER);
cout << results << endl;
}