-
Notifications
You must be signed in to change notification settings - Fork 255
/
test_simdjson_dom.cpp
88 lines (71 loc) · 2.03 KB
/
test_simdjson_dom.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
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <libnotify.h>
#include "simdjson.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;
}
};
using namespace simdjson;
using namespace simdjson::builtin;
coordinate_t calc(const padded_string &text) {
dom::parser pj;
// allocate memory for parsing up to p.size() bytes
auto allocate_error = pj.allocate(text.size());
if (allocate_error) {
cerr << allocate_error << endl;
exit(EXIT_FAILURE);
}
dom::object doc;
const auto &error = pj.parse(text).get(doc);
if (error) {
cerr << error << endl;
exit(EXIT_FAILURE);
}
auto x = 0.0, y = 0.0, z = 0.0;
auto len = 0;
for (auto coord : doc["coordinates"]) {
double x_coord = coord["x"];
x += x_coord;
double y_coord = coord["y"];
y += y_coord;
double z_coord = coord["z"];
z += z_coord;
len++;
}
return coordinate_t{x / len, y / len, z / len};
}
int main() {
auto right = coordinate_t{2.0, 0.5, 0.25};
// The _padded suffix creates a simdjson::padded_string instance
for (const padded_string &v :
{R"({"coordinates":[{"x":2.0,"y":0.5,"z":0.25}]})"_padded,
R"({"coordinates":[{"y":0.5,"x":2.0,"z":0.25}]})"_padded}) {
auto left = calc(v);
if (left != right) {
cerr << left << " != " << right << endl;
exit(EXIT_FAILURE);
}
}
padded_string text;
const auto &error = padded_string::load("/tmp/1.json").get(text);
if (error) {
cerr << "could not load file" << endl;
return EXIT_FAILURE;
}
const auto &results = notifying_invoke([&]() { return calc(text); },
"C++/{} (simdjson DOM)", COMPILER);
cout << results << endl;
}