Google Protobuf会检查字段是否已被修改

时间:2013-11-30 11:42:32

标签: c++ protocol-buffers

让我说我有这个

test::User user;
user.SerializeFromString(str_user);
insert_to_sql_db(user); // putting it in sql makes some fields searchable

// we process some events and any of the user fields may change.
// ...

/* here I would like to have a list of fields that changed 
without keeping state for each field. */
update_to_sql_db(user);

换句话说,我只想要“脏”字段,所以我可以在几个字段而不是所有字段上执行sql update。有没有办法检测protobuf中的变化字段?是否还有其他消息协议库可以生成我需要的is_dirty()函数?

更新

这是我用来过滤“脏”字段的临时解决方案。它涉及制作原始信息的副本并保留它以供以后比较。

std::vector<google::protobuf::FieldDescriptor const*> dirty(google::protobuf::Message const &mold, google::protobuf::Message const &mnew)
{
  std::vector<google::protobuf::FieldDescriptor const*> fields, dirty;
  auto r= mold.GetReflection();
  r-> ListFields(mold, &fields);
  for(auto &fp: fields)
    if(fp-> type()== google::protobuf::FieldDescriptor::TYPE_INT32 && r-> GetInt32(mold, fp)!= r-> GetInt32(mnew, fp))
      dirty.push_back(fp);
    else if(fp-> type()== google::protobuf::FieldDescriptor::TYPE_STRING && r-> GetString(mold, fp)!= r-> GetString(mnew, fp))
      dirty.push_back(fp);
    else if(fp-> type()== google::protobuf::FieldDescriptor::TYPE_DOUBLE && r-> GetDouble(mold, fp)!= r-> GetDouble(mnew, fp))
      dirty.push_back(fp);
  return dirty;
}

// P.S.我知道如何比较双打​​,这只是一个演示。

0 个答案:

没有答案