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