trevdatastreams's picture
Add verified Apache Avro C++ varint PoC
a706ef6 verified
Raw
History Blame Contribute Delete
1.79 kB
#include <cstdint>
#include <iostream>
#include <vector>
#include "avro/Decoder.hh"
#include "avro/Reader.hh"
#include "avro/Stream.hh"
#include "avro/buffer/Buffer.hh"
namespace {
avro::InputBuffer makeBuffer(const std::vector<uint8_t> &bytes) {
avro::OutputBuffer output;
output.writeTo(reinterpret_cast<const char *>(bytes.data()), bytes.size());
return output.extractData();
}
void decodeLegacy(const char *label, const std::vector<uint8_t> &bytes) {
avro::Reader reader(makeBuffer(bytes));
int64_t value = 0;
reader.readValue(value);
std::cout << label << ": legacy Reader decoded " << value << '\n';
}
void decodeModern(const char *label, const std::vector<uint8_t> &bytes) {
auto input = avro::memoryInputStream(bytes.data(), bytes.size());
auto decoder = avro::binaryDecoder();
decoder->init(*input);
try {
const int64_t value = decoder->decodeLong();
std::cout << label << ": modern BinaryDecoder decoded " << value << '\n';
} catch (const std::exception &error) {
std::cout << label << ": modern BinaryDecoder rejected input: "
<< error.what() << '\n';
}
}
} // namespace
int main() {
const std::vector<uint8_t> control = {0x02}; // zig-zag encoding of 1
// Eleven continuation bytes advance shift through 0, 7, ... 63, 70.
// The legacy Reader performs uint64_t(...) << shift before checking any
// upper bound, while the modern decoder rejects shift >= 64.
const std::vector<uint8_t> trigger = {
0x81, 0x81, 0x81, 0x81, 0x81, 0x81,
0x81, 0x81, 0x81, 0x81, 0x00,
};
decodeLegacy("control", control);
decodeModern("control", control);
decodeModern("trigger", trigger);
decodeLegacy("trigger", trigger);
return 0;
}