blob: 9990d60df32e0ce034fbab2b66c4b4f94c14ee8b [file] [log] [blame]
Vitaly Bukad4a20762017-03-01 14:23:32 -08001// 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"
Vitaly Buka4b3defd2017-03-08 16:37:38 -080016#include "port/protobuf.h"
Vitaly Bukad4a20762017-03-01 14:23:32 -080017
18namespace protobuf_mutator {
19
20using protobuf::Message;
21using protobuf::TextFormat;
22
23bool ParseTextMessage(const uint8_t* data, size_t size, Message* output) {
24 return ParseTextMessage({data, data + size}, output);
25}
26
27bool ParseTextMessage(const std::string& data, protobuf::Message* output) {
28 output->Clear();
29 TextFormat::Parser parser;
30 parser.AllowPartialMessage(true);
Vitaly Bukac0a20382017-06-13 11:48:09 -070031 if (!parser.ParseFromString(data, output)) {
32 output->Clear();
33 return false;
34 }
35 return true;
Vitaly Bukad4a20762017-03-01 14:23:32 -080036}
37
38size_t SaveMessageAsText(const Message& message, uint8_t* data,
39 size_t max_size) {
40 std::string result = SaveMessageAsText(message);
41 if (result.size() <= max_size) {
42 memcpy(data, result.data(), result.size());
43 return result.size();
44 }
45 return 0;
46}
47
48std::string SaveMessageAsText(const protobuf::Message& message) {
Vitaly Buka829ad002017-03-01 16:26:00 -080049 String tmp;
50 if (!protobuf::TextFormat::PrintToString(message, &tmp)) return {};
51 return tmp;
Vitaly Bukad4a20762017-03-01 14:23:32 -080052}
53
54} // namespace protobuf_mutator