xref: /aosp_15_r20/external/federated-compute/fcp/testing/parse_text_proto.h (revision 14675a029014e728ec732f129a32e299b2da0601)
1 /*
2  * Copyright 2020 Google LLC
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 
17 #ifndef FCP_TESTING_PARSE_TEXT_PROTO_H_
18 #define FCP_TESTING_PARSE_TEXT_PROTO_H_
19 
20 #include <type_traits>
21 
22 #include "google/protobuf/text_format.h"
23 #include "absl/strings/string_view.h"
24 #include "fcp/base/monitoring.h"
25 
26 namespace fcp {
27 
28 // Convenience macro for parsing text formatted protos in test code.
29 // The input string should include only the proto fields but not the proto
30 // itself. For example:
31 //
32 //   const MyProtoType foo = PARSE_TEXT_PROTO("foo:1 sub { bar:2 }");
33 //   const MyProtoType bar = PARSE_TEXT_PROTO(R"(
34 //       foo: 1
35 //       sub {
36 //         bar: 2
37 //       })");
38 //
39 // Note that the output of the macro has to be assigned to proper proto message
40 // type in order for the parsing to work.
41 #define PARSE_TEXT_PROTO(STR) ParseProtoHelper(STR)
42 
43 class ParseProtoHelper {
44  public:
ParseProtoHelper(absl::string_view string_view)45   explicit ParseProtoHelper(absl::string_view string_view)
46       : string_view_(string_view) {}
47 
48   template <class T>
T()49   operator T() {  // NOLINT
50     static_assert(std::is_base_of<google::protobuf::Message, T>::value &&
51                   !std::is_same<google::protobuf::Message, T>::value);
52     T msg;
53     FCP_CHECK(google::protobuf::TextFormat::ParseFromString(
54         std::string(string_view_),  // NOLINT(OSS)
55         &msg));
56     return msg;
57   }
58 
59  private:
60   absl::string_view string_view_;
61 };
62 
63 }  // namespace fcp
64 
65 #endif  // FCP_TESTING_PARSE_TEXT_PROTO_H_
66