1/**
2 * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15
16 * \author jiliang.ljl
17 * \date Feb 2021
18 * \brief protobuf helper
19 */
20
21#pragma once
22
23#include <string>
24
25#ifdef __GNUC__
26#pragma GCC diagnostic push
27#pragma GCC diagnostic ignored "-Wshadow"
28#pragma GCC diagnostic ignored "-Wunused-parameter"
29#endif
30#include <google/protobuf/message.h>
31#ifdef __GNUC__
32#pragma GCC diagnostic pop
33#endif
34
35namespace proxima {
36namespace be {
37
38//! See data type mapping:
39//! https://developers.google.com/protocol-buffers/docs/proto3#json
40class ProtobufHelper {
41 public:
42 struct PrintOptions {
43 // Whether to always print primitive fields.
44 bool always_print_primitive_fields{true};
45 };
46
47 struct JsonParseOptions {
48 // Whether to ignore unknown JSON fields during parsing
49 bool ignore_unknown_fields{false};
50 };
51
52 //! Perform json serialization.
53 static bool MessageToJson(const google::protobuf::Message &message,
54 std::string *json) {
55 return MessageToJson(message, PrintOptions(), json);
56 }
57
58 //! Perform json serialization.
59 static bool MessageToJson(const google::protobuf::Message &message,
60 const PrintOptions &options, std::string *json);
61
62 //! Perform json deserialization.
63 static bool JsonToMessage(const std::string &json,
64 google::protobuf::Message *message) {
65 return JsonToMessage(json, JsonParseOptions{}, message);
66 }
67
68 //! Perform json deserialization.
69 static bool JsonToMessage(const std::string &json,
70 const JsonParseOptions &options,
71 google::protobuf::Message *message);
72};
73
74} // namespace be
75} // namespace proxima
76