1 // Copyright 2017 Google Inc. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "src/text_format.h"
16
17 #include "port/protobuf.h"
18
19 namespace protobuf_mutator {
20
21 using protobuf::Message;
22 using protobuf::TextFormat;
23
ParseTextMessage(const uint8_t * data,size_t size,Message * output)24 bool ParseTextMessage(const uint8_t* data, size_t size, Message* output) {
25 return ParseTextMessage({reinterpret_cast<const char*>(data), size}, output);
26 }
27
ParseTextMessage(const std::string & data,protobuf::Message * output)28 bool ParseTextMessage(const std::string& data, protobuf::Message* output) {
29 output->Clear();
30 TextFormat::Parser parser;
31 parser.SetRecursionLimit(100);
32 parser.AllowPartialMessage(true);
33 parser.AllowUnknownField(true);
34 if (!parser.ParseFromString(data, output)) {
35 output->Clear();
36 return false;
37 }
38 return true;
39 }
40
SaveMessageAsText(const Message & message,uint8_t * data,size_t max_size)41 size_t SaveMessageAsText(const Message& message, uint8_t* data,
42 size_t max_size) {
43 std::string result = SaveMessageAsText(message);
44 if (result.size() <= max_size) {
45 memcpy(data, result.data(), result.size());
46 return result.size();
47 }
48 return 0;
49 }
50
SaveMessageAsText(const protobuf::Message & message)51 std::string SaveMessageAsText(const protobuf::Message& message) {
52 String tmp;
53 if (!protobuf::TextFormat::PrintToString(message, &tmp)) return {};
54 return tmp;
55 }
56
57 } // namespace protobuf_mutator
58