1 // Copyright 2022 The gRPC Authors
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 <string.h>
16
17 #include <memory>
18 #include <utility>
19
20 #include "gtest/gtest.h"
21
22 #include <grpc/event_engine/slice.h>
23 #include <grpc/event_engine/slice_buffer.h>
24 #include <grpc/slice.h>
25 #include <grpc/support/alloc.h>
26 #include <grpc/support/log.h>
27 #include <grpc/support/port_platform.h>
28
29 using ::grpc_event_engine::experimental::Slice;
30 using ::grpc_event_engine::experimental::SliceBuffer;
31
32 static constexpr int kNewSliceLength = 100;
33
MakeSlice(size_t len)34 Slice MakeSlice(size_t len) {
35 GPR_ASSERT(len > 0);
36 unsigned char* contents = static_cast<unsigned char*>(gpr_malloc(len));
37 memset(contents, 'a', len);
38 return Slice(grpc_slice_new(contents, len, gpr_free));
39 }
40
TEST(SliceBufferTest,AddAndRemoveTest)41 TEST(SliceBufferTest, AddAndRemoveTest) {
42 SliceBuffer sb;
43 Slice first_slice = MakeSlice(kNewSliceLength);
44 Slice second_slice = MakeSlice(kNewSliceLength);
45 Slice first_slice_copy = first_slice.Copy();
46 sb.Append(std::move(first_slice));
47 sb.Append(std::move(second_slice));
48 ASSERT_EQ(sb.Count(), 2);
49 ASSERT_EQ(sb.Length(), 2 * kNewSliceLength);
50 Slice popped = sb.TakeFirst();
51 ASSERT_EQ(popped, first_slice_copy);
52 ASSERT_EQ(sb.Count(), 1);
53 ASSERT_EQ(sb.Length(), kNewSliceLength);
54 sb.Prepend(std::move(popped));
55 ASSERT_EQ(sb.Count(), 2);
56 ASSERT_EQ(sb.Length(), 2 * kNewSliceLength);
57 sb.Clear();
58 ASSERT_EQ(sb.Count(), 0);
59 ASSERT_EQ(sb.Length(), 0);
60 }
61
TEST(SliceBufferTest,SliceRefTest)62 TEST(SliceBufferTest, SliceRefTest) {
63 SliceBuffer sb;
64 Slice first_slice = MakeSlice(kNewSliceLength);
65 Slice second_slice = MakeSlice(kNewSliceLength + 1);
66 Slice first_slice_copy = first_slice.Copy();
67 Slice second_slice_copy = second_slice.Copy();
68 ASSERT_EQ(sb.AppendIndexed(std::move(first_slice)), 0);
69 ASSERT_EQ(sb.AppendIndexed(std::move(second_slice)), 1);
70 Slice first_reffed = sb.RefSlice(0);
71 Slice second_reffed = sb.RefSlice(1);
72 ASSERT_EQ(first_reffed, first_slice_copy);
73 ASSERT_EQ(second_reffed, second_slice_copy);
74 ASSERT_EQ(sb.Count(), 2);
75 ASSERT_EQ(sb.Length(), 2 * kNewSliceLength + 1);
76 sb.Clear();
77 }
78
main(int argc,char ** argv)79 int main(int argc, char** argv) {
80 testing::InitGoogleTest(&argc, argv);
81 return RUN_ALL_TESTS();
82 }
83