f8/cpp/utils.cc
2018-08-15 10:57:32 +08:00

76 lines
2.6 KiB
C++

#include <a8/a8.h>
#include <a8/stringlist.h>
#include <a8/csvreader.h>
#include <google/protobuf/message.h>
#include "utils.h"
bool ReadCsvMetaFile(const std::string& filename,
google::protobuf::Message* prototype,
std::function<void (google::protobuf::Message*)> push_back_func)
{
const google::protobuf::Descriptor* descriptor = prototype->GetDescriptor();
const google::protobuf::Reflection* reflection = prototype->GetReflection();
a8::CsvReader reader;
reader.Load(filename);
while (reader.NextLine()) {
google::protobuf::Message* msg = prototype->New();
for (int i = 0; i < descriptor->field_count(); ++i) {
const google::protobuf::FieldDescriptor* field_desc = descriptor->field(i);
const std::string& field_name = field_desc->name();
switch (field_desc->cpp_type()) {
case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
{
reflection->SetString(msg, field_desc, reader.GetValue(field_name));
}
break;
case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
{
reflection->SetInt32(msg, field_desc, reader.GetValue(field_name));
}
break;
case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
{
reflection->SetUInt32(msg, field_desc, reader.GetValue(field_name));
}
break;
case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
{
reflection->SetInt64(msg, field_desc, reader.GetValue(field_name));
}
break;
case google::protobuf::FieldDescriptor::CPPTYPE_UINT64:
{
reflection->SetUInt64(msg, field_desc, reader.GetValue(field_name));
}
break;
case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT:
{
reflection->SetFloat(msg, field_desc, (double)reader.GetValue(field_name));
}
break;
case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE:
{
reflection->SetDouble(msg, field_desc, reader.GetValue(field_name));
}
break;
default:
{
abort();
}
break;
}//end switch
}//end for
push_back_func(msg);
delete msg;
}
return true;
}