refl.h
1 // Copyright 2019, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 
5 #pragma once
6 #include <google/protobuf/descriptor.h>
7 #include <google/protobuf/message.h>
8 
9 namespace util {
10 namespace pb {
11 
12 using FD = ::google::protobuf::FieldDescriptor;
13 using Msg = ::google::protobuf::Message;
14 
15 template <FD::CppType t> struct FD_Traits;
16 
17 #define DECLARE_FD_TRAITS(CPP_TYPE, src_type) \
18  template <> struct FD_Traits<FD::CPP_TYPE> { typedef src_type type; }
19 
20 DECLARE_FD_TRAITS(CPPTYPE_BOOL, bool);
21 DECLARE_FD_TRAITS(CPPTYPE_INT32, int32_t);
22 DECLARE_FD_TRAITS(CPPTYPE_UINT32, uint32_t);
23 DECLARE_FD_TRAITS(CPPTYPE_INT64, int64_t);
24 DECLARE_FD_TRAITS(CPPTYPE_UINT64, uint64_t);
25 DECLARE_FD_TRAITS(CPPTYPE_DOUBLE, double);
26 DECLARE_FD_TRAITS(CPPTYPE_FLOAT, float);
27 DECLARE_FD_TRAITS(CPPTYPE_STRING, std::string);
28 DECLARE_FD_TRAITS(CPPTYPE_MESSAGE, Msg);
29 
30 #undef DECLARE_FD_TRAITS
31 
32 template <FD::CppType t> using FD_Traits_t = typename FD_Traits<t>::type;
33 
34 template <FD::CppType t>
35 auto GetMutableArray(const ::google::protobuf::Reflection* refl, const FD* field, Msg* msg) {
36  return refl->GetMutableRepeatedFieldRef<FD_Traits_t<t>>(msg, field);
37 }
38 
39 template <FD::CppType t>
40 void SetField(const ::google::protobuf::Reflection* refl, const FD* field,
41  const FD_Traits_t<t>& val, Msg* msg);
42 
43 template <FD::CppType t>
44 FD_Traits_t<t> GetField(const ::google::protobuf::Reflection* refl, const FD* field,
45  const Msg* msg);
46 
47 #define DEFINE_MODIFIER(CPP_TYPE, Name) \
48  template <> inline \
49  FD_Traits_t<FD::CPP_TYPE> GetField<FD::CPP_TYPE>(const ::google::protobuf::Reflection* refl, \
50  const FD* field, const Msg* msg) { \
51  return refl->Get##Name(*msg, field); \
52  } \
53  \
54  template <> inline \
55  void SetField<FD::CPP_TYPE>(const ::google::protobuf::Reflection* refl, const FD* field, \
56  const FD_Traits_t<FD::CPP_TYPE>& val, Msg* msg) { \
57  refl->Set##Name(msg, field, val); \
58  }
59 
60 DEFINE_MODIFIER(CPPTYPE_BOOL, Bool);
61 DEFINE_MODIFIER(CPPTYPE_INT32, Int32);
62 DEFINE_MODIFIER(CPPTYPE_UINT32, UInt32);
63 DEFINE_MODIFIER(CPPTYPE_INT64, Int64);
64 DEFINE_MODIFIER(CPPTYPE_UINT64, UInt64);
65 DEFINE_MODIFIER(CPPTYPE_DOUBLE, Double);
66 DEFINE_MODIFIER(CPPTYPE_FLOAT, Float);
67 DEFINE_MODIFIER(CPPTYPE_STRING, String);
68 
69 } // namespace pb
70 
71 } // namespace util