3 #include <google/protobuf/message.h>
4 #include <google/protobuf/util/json_util.h>
7 #include "odbdesign_export.h"
14 template<
typename TPbMessage>
19 virtual std::unique_ptr<TPbMessage> to_protobuf()
const = 0;
20 virtual void from_protobuf(
const TPbMessage& message) = 0;
23 bool to_pbstring(std::string& pb_string)
const;
24 bool from_pbstring(
const std::string& pb_string);
27 bool to_stream(std::ostream& outputStream)
const;
28 bool from_stream(std::istream& inputStream);
31 std::string to_json()
const override;
32 void from_json(
const std::string& json)
override;
39 static_assert(std::is_base_of<google::protobuf::Message, TPbMessage>::value,
"template parameter type TPbMessage must derive from Protobuf Message class");
43 template<
typename TPbMessage>
46 auto pMessage = to_protobuf();
47 if (pMessage ==
nullptr)
return false;
48 return pMessage->SerializeToString(&pb_string);
51 template<
typename TPbMessage>
52 inline bool IProtoBuffable<TPbMessage>::from_pbstring(
const std::string& pb_string)
54 auto pMessage = std::unique_ptr<TPbMessage>();
55 if (!pMessage->ParseFromString(pb_string))
return false;
56 from_protobuf(*pMessage);
60 template<
typename TPbMessage>
61 inline bool IProtoBuffable<TPbMessage>::to_stream(std::ostream& outputStream)
const
63 auto pMessage = to_protobuf();
64 if (pMessage ==
nullptr)
return false;
65 return pMessage->SerializeToOstream(&outputStream);
68 template<
typename TPbMessage>
69 inline bool IProtoBuffable<TPbMessage>::from_stream(std::istream& inputStream)
71 auto pMessage = std::unique_ptr<TPbMessage>();
72 if (!pMessage->ParseFromIstream(&inputStream))
return false;
73 from_protobuf(*pMessage);
77 template<
typename TPbMessage>
78 std::string IProtoBuffable<TPbMessage>::to_json()
const
81 google::protobuf::util::JsonOptions jsonOptions;
84 auto status = google::protobuf::util::MessageToJsonString(*to_protobuf(), &json, jsonOptions);
85 if (!status.ok()) json.clear();
89 template<
typename TPbMessage>
90 inline void IProtoBuffable<TPbMessage>::from_json(
const std::string& json)
92 google::protobuf::StringPiece sp_json(json);
94 google::protobuf::util::JsonOptions jsonOptions;
96 auto pMessage = std::unique_ptr<TPbMessage>();
97 auto status = google::protobuf::util::JsonStringToMessage(sp_json, pMessage.get());
98 if (!status.ok())
return;
99 from_protobuf(*pMessage);