data_proto2_to_proto3_util.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_
  2. #define PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_
  3. #include "google/protobuf/message.h"
  4. #include "google/protobuf/descriptor.h"
  5. using google::protobuf::FieldDescriptor;
  6. using google::protobuf::Message;
  7. using google::protobuf::Reflection;
  8. namespace google {
  9. namespace protobuf {
  10. namespace util {
  11. class DataStripper {
  12. public:
  13. void StripMessage(Message *message) {
  14. std::vector<const FieldDescriptor*> set_fields;
  15. const Reflection* reflection = message->GetReflection();
  16. reflection->ListFields(*message, &set_fields);
  17. for (size_t i = 0; i < set_fields.size(); i++) {
  18. const FieldDescriptor* field = set_fields[i];
  19. if (ShouldBeClear(field)) {
  20. reflection->ClearField(message, field);
  21. continue;
  22. }
  23. if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
  24. if (field->is_repeated()) {
  25. for (int j = 0; j < reflection->FieldSize(*message, field); j++) {
  26. StripMessage(reflection->MutableRepeatedMessage(message, field, j));
  27. }
  28. } else {
  29. StripMessage(reflection->MutableMessage(message, field));
  30. }
  31. }
  32. }
  33. reflection->MutableUnknownFields(message)->Clear();
  34. }
  35. private:
  36. virtual bool ShouldBeClear(const FieldDescriptor *field) = 0;
  37. };
  38. class GogoDataStripper : public DataStripper {
  39. private:
  40. virtual bool ShouldBeClear(const FieldDescriptor *field) {
  41. return field->type() == FieldDescriptor::TYPE_GROUP;
  42. }
  43. };
  44. class Proto3DataStripper : public DataStripper {
  45. private:
  46. virtual bool ShouldBeClear(const FieldDescriptor *field) {
  47. return field->type() == FieldDescriptor::TYPE_GROUP ||
  48. field->is_extension();
  49. }
  50. };
  51. } // namespace util
  52. } // namespace protobuf
  53. } // namespace google
  54. #endif // PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_