|
| 1 | +#include <ROOT/REntry.hxx> |
| 2 | +#include <ROOT/RNTupleReader.hxx> |
| 3 | + |
| 4 | +using ROOT::Experimental::REntry; |
| 5 | +using ROOT::Experimental::RNTupleReader; |
| 6 | + |
| 7 | +#include <cstdint> |
| 8 | +#include <fstream> |
| 9 | +#include <ostream> |
| 10 | +#include <string> |
| 11 | +#include <string_view> |
| 12 | +#include <variant> |
| 13 | +#include <vector> |
| 14 | + |
| 15 | +using Vector = std::vector<std::int32_t>; |
| 16 | +using Variant = std::variant<std::int32_t, std::string, Vector>; |
| 17 | + |
| 18 | +static void PrintVariantValue(const REntry &entry, std::string_view name, |
| 19 | + std::ostream &os, bool last = false) { |
| 20 | + Variant &value = *entry.GetPtr<Variant>(name); |
| 21 | + os << " \"" << name << "\": "; |
| 22 | + if (value.index() == 0) { |
| 23 | + os << std::get<std::int32_t>(value); |
| 24 | + } else if (value.index() == 1) { |
| 25 | + os << "\"" << std::get<std::string>(value) << "\""; |
| 26 | + } else if (value.index() == 2) { |
| 27 | + Vector &vectorValue = std::get<Vector>(value); |
| 28 | + os << "["; |
| 29 | + bool first = true; |
| 30 | + for (auto element : vectorValue) { |
| 31 | + if (first) { |
| 32 | + first = false; |
| 33 | + } else { |
| 34 | + os << ","; |
| 35 | + } |
| 36 | + os << "\n " << element; |
| 37 | + } |
| 38 | + if (!vectorValue.empty()) { |
| 39 | + os << "\n "; |
| 40 | + } |
| 41 | + os << "]"; |
| 42 | + } |
| 43 | + |
| 44 | + if (!last) { |
| 45 | + os << ","; |
| 46 | + } |
| 47 | + os << "\n"; |
| 48 | +} |
| 49 | + |
| 50 | +void read(std::string_view input = "types.variant.root", |
| 51 | + std::string_view output = "types.variant.json") { |
| 52 | + std::ofstream os(std::string{output}); |
| 53 | + os << "[\n"; |
| 54 | + |
| 55 | + auto reader = RNTupleReader::Open("ntpl", input); |
| 56 | + auto &entry = reader->GetModel().GetDefaultEntry(); |
| 57 | + bool first = true; |
| 58 | + for (auto index : *reader) { |
| 59 | + reader->LoadEntry(index); |
| 60 | + |
| 61 | + if (first) { |
| 62 | + first = false; |
| 63 | + } else { |
| 64 | + os << ",\n"; |
| 65 | + } |
| 66 | + os << " {\n"; |
| 67 | + |
| 68 | + PrintVariantValue(entry, "f", os, /*last=*/true); |
| 69 | + |
| 70 | + os << " }"; |
| 71 | + // Newline is intentionally missing, may need to print a comma before the |
| 72 | + // next entry. |
| 73 | + } |
| 74 | + os << "\n"; |
| 75 | + os << "]\n"; |
| 76 | +} |
0 commit comments