qpdf/libtests/json_parse.cc

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

112 lines
2.3 KiB
C++
Raw Normal View History

#include <qpdf/FileInputSource.hh>
2022-01-17 23:40:38 +00:00
#include <qpdf/JSON.hh>
2022-05-01 18:06:31 +00:00
#include <cstdlib>
#include <cstring>
2022-01-17 23:40:38 +00:00
#include <iostream>
2022-05-01 18:06:31 +00:00
#include <memory>
namespace
{
class Reactor: public JSON::Reactor
{
public:
~Reactor() override = default;
2023-05-20 12:56:33 +00:00
void dictionaryStart() override;
void arrayStart() override;
void containerEnd(JSON const& value) override;
void topLevelScalar() override;
2022-05-01 18:06:31 +00:00
bool dictionaryItem(std::string const& key, JSON const& value) override;
2023-05-20 12:56:33 +00:00
bool arrayItem(JSON const& value) override;
2022-05-01 18:06:31 +00:00
private:
void printItem(JSON const&);
};
} // namespace
void
Reactor::dictionaryStart()
{
std::cout << "dictionary start" << std::endl;
}
void
Reactor::arrayStart()
{
std::cout << "array start" << std::endl;
}
void
Reactor::containerEnd(JSON const& value)
{
std::cout << "container end: ";
printItem(value);
}
void
Reactor::topLevelScalar()
{
std::cout << "top-level scalar" << std::endl;
}
bool
Reactor::dictionaryItem(std::string const& key, JSON const& value)
{
std::cout << "dictionary item: " << key << " -> ";
printItem(value);
if (key == "keep") {
return false;
}
return true;
}
bool
Reactor::arrayItem(JSON const& value)
{
std::cout << "array item: ";
printItem(value);
std::string n;
if (value.getString(n) && n == "keep") {
return false;
}
return true;
}
void
Reactor::printItem(JSON const& j)
{
std::cout << "[" << j.getStart() << ", " << j.getEnd() << "): " << j.unparse() << std::endl;
}
static void
usage()
{
std::cerr << "Usage: json_parse file [--react]" << std::endl;
exit(2);
}
2022-01-17 23:40:38 +00:00
int
main(int argc, char* argv[])
{
2022-05-01 18:06:31 +00:00
if ((argc < 2) || (argc > 3)) {
usage();
2022-01-17 23:40:38 +00:00
return 2;
}
char const* filename = argv[1];
2022-05-01 18:06:31 +00:00
std::shared_ptr<Reactor> reactor;
if (argc == 3) {
if (strcmp(argv[2], "--react") == 0) {
reactor = std::make_shared<Reactor>();
} else {
usage();
}
}
2022-01-17 23:40:38 +00:00
try {
FileInputSource is(filename);
std::cout << JSON::parse(is, reactor.get()).unparse() << std::endl;
2022-01-17 23:40:38 +00:00
} catch (std::exception& e) {
std::cerr << "exception: " << filename << ": " << e.what() << std::endl;
return 2;
}
return 0;
}