data_proto2_to_proto3_util.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. }
  22. if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
  23. if (field->is_repeated()) {
  24. for (int j = 0; j < reflection->FieldSize(*message, field); j++) {
  25. StripMessage(reflection->MutableRepeatedMessage(message, field, j));
  26. }
  27. } else {
  28. StripMessage(reflection->MutableMessage(message, field));
  29. }
  30. }
  31. }
  32. reflection->MutableUnknownFields(message)->Clear();
  33. }
  34. private:
  35. virtual bool ShouldBeClear(const FieldDescriptor *field) = 0;
  36. };
  37. class GogoDataStripper : public DataStripper {
  38. private:
  39. virtual bool ShouldBeClear(const FieldDescriptor *field) {
  40. return field->type() == FieldDescriptor::TYPE_GROUP;
  41. }
  42. };
  43. class Proto3DataStripper : public DataStripper {
  44. private:
  45. virtual bool ShouldBeClear(const FieldDescriptor *field) {
  46. return field->type() == FieldDescriptor::TYPE_GROUP ||
  47. field->is_extension();
  48. }
  49. };
  50. } // namespace util
  51. } // namespace protobuf
  52. } // namespace google
  53. #endif // PROTOBUF_BENCHMARKS_UTIL_DATA_PROTO2_TO_PROTO3_UTIL_H_