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