Files
spark/src/lib/core/ProtoReader.h
T
John Colvin cd6fcacc4f refactor: Clean up CryptoCommand
* Replace BinanceDemo w/ general purpose LiveLadderDemo
* Get rid of CryptoConfig.proto, as it inappropriately depended on
non-config protos
2021-12-07 17:52:42 -05:00

65 lines
1.6 KiB
C++

#pragma once
#include <fstream>
#include <google/protobuf/text_format.h>
#include <iostream>
#include <optional>
#include <string>
namespace bts::core {
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 spartan::core