xref: /aosp_15_r20/external/perfetto/src/trace_processor/containers/implicit_segment_forest_unittest.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2024 The Android Open Source Project
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 "src/trace_processor/containers/implicit_segment_forest.h"
18 
19 #include <cstddef>
20 #include <cstdint>
21 #include <numeric>
22 #include <random>
23 #include <vector>
24 
25 #include "test/gtest_and_gmock.h"
26 
27 namespace perfetto::trace_processor {
28 namespace {
29 
30 struct Value {
31   uint32_t value;
32 };
33 
34 struct Sum {
operator ()perfetto::trace_processor::__anoncfbf86ea0111::Sum35   Value operator()(const Value& a, const Value& b) {
36     return Value{a.value + b.value};
37   }
38 };
39 
TEST(ImplicitSegmentTree,SimpleSum)40 TEST(ImplicitSegmentTree, SimpleSum) {
41   std::vector<uint32_t> res = {209, 330, 901, 3, 10, 0, 3903, 309, 490};
42 
43   ImplicitSegmentForest<Value, Sum> forest;
44   for (uint32_t x : res) {
45     forest.Push(Value{x});
46   }
47 
48   for (uint32_t i = 0; i < res.size(); ++i) {
49     for (uint32_t j = i + 1; j < res.size(); ++j) {
50       ASSERT_EQ(forest.Query(i, j).value,
51                 std::accumulate(res.begin() + i, res.begin() + j, 0u));
52     }
53   }
54 }
55 
TEST(ImplicitSegmentTree,Stress)56 TEST(ImplicitSegmentTree, Stress) {
57   static constexpr size_t kCount = 9249;
58   std::minstd_rand0 rng(42);
59 
60   std::vector<uint32_t> res;
61   ImplicitSegmentForest<Value, Sum> forest;
62   for (uint32_t i = 0; i < kCount; ++i) {
63     res.push_back(static_cast<uint32_t>(rng()));
64     forest.Push(Value{res.back()});
65   }
66 
67   for (uint32_t i = 0; i < 10000; ++i) {
68     uint32_t s = rng() % kCount;
69     uint32_t e = s + 1 + (rng() % (kCount - s));
70     ASSERT_EQ(forest.Query(s, e).value,
71               std::accumulate(res.begin() + s, res.begin() + e, 0u));
72   }
73 }
74 
75 }  // namespace
76 }  // namespace perfetto::trace_processor
77