xref: /aosp_15_r20/external/grpc-grpc/test/cpp/util/byte_buffer_proto_helper.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2016 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include "test/cpp/util/byte_buffer_proto_helper.h"
20 
21 #include "absl/memory/memory.h"
22 
23 namespace grpc {
24 namespace testing {
25 
ParseFromByteBuffer(ByteBuffer * buffer,grpc::protobuf::Message * message)26 bool ParseFromByteBuffer(ByteBuffer* buffer, grpc::protobuf::Message* message) {
27   std::vector<Slice> slices;
28   (void)buffer->Dump(&slices);
29   std::string buf;
30   buf.reserve(buffer->Length());
31   for (auto s = slices.begin(); s != slices.end(); s++) {
32     buf.append(reinterpret_cast<const char*>(s->begin()), s->size());
33   }
34   return message->ParseFromString(buf);
35 }
36 
SerializeToByteBuffer(grpc::protobuf::Message * message)37 std::unique_ptr<ByteBuffer> SerializeToByteBuffer(
38     grpc::protobuf::Message* message) {
39   std::string buf;
40   message->SerializeToString(&buf);
41   Slice slice(buf);
42   return std::make_unique<ByteBuffer>(&slice, 1);
43 }
44 
SerializeToByteBufferInPlace(grpc::protobuf::Message * message,ByteBuffer * buffer)45 bool SerializeToByteBufferInPlace(grpc::protobuf::Message* message,
46                                   ByteBuffer* buffer) {
47   std::string buf;
48   if (!message->SerializeToString(&buf)) {
49     return false;
50   }
51   buffer->Clear();
52   Slice slice(buf);
53   ByteBuffer tmp(&slice, 1);
54   buffer->Swap(&tmp);
55   return true;
56 }
57 
58 }  // namespace testing
59 }  // namespace grpc
60