-
Notifications
You must be signed in to change notification settings - Fork 0
/
rewrite_json.cpp
68 lines (58 loc) · 1.56 KB
/
rewrite_json.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
#include "tjson.h"
#include <fstream>
#include <iostream>
static std::vector<uint8_t>
ReadStream(std::istream* const in, std::string* const out_err)
{
std::vector<uint8_t> ret(1000*1000);
uint64_t pos = 0;
while (true) {
in->read((char*)ret.data() + pos, ret.size() - pos);
pos += in->gcount();
if (in->good()) {
ret.resize(ret.size() * 2);
continue;
}
if (in->eof()) {
ret.resize(pos);
return ret;
}
*out_err = std::string("rdstate: ") + std::to_string(in->rdstate());
return {};
}
}
int
main(int argc, const char* const argv[])
{
std::string err;
const auto bytes = [&]() {
std::istream* in;
std::ifstream file_in;
if (argc < 2) {
fprintf(stderr, "Reading STDIN...\n");
in = &std::cin;
} else {
const auto path = argv[1];
fprintf(stderr, "Reading %s...\n", path);
file_in.open(path, std::ios_base::in | std::ios_base::binary);
in = &file_in;
}
return ReadStream(in, &err);
}();
if (err.size()) {
fprintf(stderr, "%s\n", err.c_str());
return 1;
}
fprintf(stderr, " Read %llu bytes.\n", uint64_t(bytes.size()));
fprintf(stderr, "Parsing...\n");
const auto val = tjson::read((const char*)bytes.data(),
(const char*)bytes.data()+bytes.size(), &err);
if (!val) {
fprintf(stderr, "%s\n", err.c_str());
return 1;
}
fprintf(stderr, "Writing:\n");
val->write(&std::cout, "");
std::cout << "\n";
return 0;
}