Files
spark/src/lib/io/ProtoReader.h
T

65 lines
1.6 KiB
C++

#pragma once
#include <fstream>
#include <google/protobuf/text_format.h>
#include <iostream>
#include <optional>
#include <string>
namespace bts::io {
class ProtoReader {
public:
template <class T>
static bool read_proto(const std::string &path, T &result);
template <class T>
static bool read_proto(
const std::string &path, T &result, std::ostream &err);
template <class T>
static std::optional<T> read_proto(const std::string &path);
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <class T>
bool ProtoReader::read_proto(
const std::string &path, T &result, std::ostream &err) {
std::ifstream f(path);
if (f.good()) {
std::string str(
(std::istreambuf_iterator<char>(f)),
(std::istreambuf_iterator<char>()));
if (google::protobuf::TextFormat::ParseFromString(str, &result)) {
return true;
}
err << "Invalid config in " << path << "\n";
} else {
err << "File not found in " << path << "\n";
}
return false;
}
template <class T>
bool ProtoReader::read_proto(const std::string &path, T &result) {
struct NullBuffer : std::streambuf {
int overflow(int c) override { return c; }
};
NullBuffer null_buff;
std::ostream no_op(&null_buff);
return read_proto(path, result, no_op);
}
template <class T>
std::optional<T> ProtoReader::read_proto(const std::string &path) {
T result;
if (read_proto(path, result)) {
return result;
}
return std::nullopt;
}
} // namespace bts::io