xref: /aosp_15_r20/external/grpc-grpc/test/cpp/util/proto_buffer_writer_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 // Copyright 2023 gRPC authors.
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 #include <gtest/gtest.h>
18 
19 #include <grpcpp/support/byte_buffer.h>
20 #include <grpcpp/support/proto_buffer_writer.h>
21 
22 #include "test/core/util/test_config.h"
23 
24 namespace grpc {
25 namespace {
26 
TEST(ProtoBufferWriterTest,Next)27 TEST(ProtoBufferWriterTest, Next) {
28   ByteBuffer buffer;
29   ProtoBufferWriter writer(&buffer, 16, 256);
30   // 1st next
31   void* data1;
32   int size1;
33   EXPECT_TRUE(writer.Next(&data1, &size1));
34   EXPECT_GT(size1, 0);
35   memset(data1, 1, size1);
36   // 2nd next
37   void* data2;
38   int size2;
39   EXPECT_TRUE(writer.Next(&data2, &size2));
40   EXPECT_GT(size2, 0);
41   memset(data2, 2, size2);
42   // Done
43   EXPECT_EQ(writer.ByteCount(), size1 + size2);
44   EXPECT_EQ(buffer.Length(), size1 + size2);
45   Slice slice;
46   EXPECT_TRUE(buffer.DumpToSingleSlice(&slice).ok());
47   EXPECT_EQ(memcmp(slice.begin(), data1, size1), 0);
48   EXPECT_EQ(memcmp(slice.begin() + size1, data2, size2), 0);
49 }
50 
51 #ifdef GRPC_PROTOBUF_CORD_SUPPORT_ENABLED
52 
TEST(ProtoBufferWriterTest,WriteCord)53 TEST(ProtoBufferWriterTest, WriteCord) {
54   ByteBuffer buffer;
55   ProtoBufferWriter writer(&buffer, 16, 4096);
56   // Cord
57   absl::Cord cord;
58   std::string str1 = std::string(1024, 'a');
59   cord.Append(str1);
60   std::string str2 = std::string(1024, 'b');
61   cord.Append(str2);
62   writer.WriteCord(cord);
63   // Done
64   EXPECT_EQ(writer.ByteCount(), str1.size() + str2.size());
65   EXPECT_EQ(buffer.Length(), str1.size() + str2.size());
66   Slice slice;
67   EXPECT_TRUE(buffer.DumpToSingleSlice(&slice).ok());
68   EXPECT_EQ(memcmp(slice.begin() + str1.size(), str2.c_str(), str2.size()), 0);
69 }
70 
71 #endif  // GRPC_PROTOBUF_CORD_SUPPORT_ENABLED
72 
73 }  // namespace
74 }  // namespace grpc
75 
main(int argc,char ** argv)76 int main(int argc, char** argv) {
77   grpc::testing::TestEnvironment env(&argc, argv);
78   ::testing::InitGoogleTest(&argc, argv);
79   return RUN_ALL_TESTS();
80 }
81