xref: /aosp_15_r20/external/cronet/base/allocator/dispatcher/initializer.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_ALLOCATOR_DISPATCHER_INITIALIZER_H_
6 #define BASE_ALLOCATOR_DISPATCHER_INITIALIZER_H_
7 
8 #include "base/allocator/dispatcher/configuration.h"
9 #include "base/allocator/dispatcher/dispatcher.h"
10 #include "base/allocator/dispatcher/internal/tools.h"
11 
12 #include <tuple>
13 #include <utility>
14 
15 namespace base::allocator::dispatcher {
16 namespace internal {
17 
18 // Filter the passed observers and perform initialization of the passed
19 // dispatcher.
20 template <size_t CurrentIndex,
21           typename DispatcherType,
22           typename CheckObserverPredicate,
23           typename VerifiedObservers,
24           typename UnverifiedObservers,
25           size_t... IndicesToSelect>
DoInitialize(DispatcherType & dispatcher,CheckObserverPredicate check_observer,const VerifiedObservers & verified_observers,const UnverifiedObservers & unverified_observers,std::index_sequence<IndicesToSelect...> indices)26 inline void DoInitialize(DispatcherType& dispatcher,
27                          CheckObserverPredicate check_observer,
28                          const VerifiedObservers& verified_observers,
29                          const UnverifiedObservers& unverified_observers,
30                          std::index_sequence<IndicesToSelect...> indices) {
31   if constexpr (CurrentIndex < std::tuple_size_v<UnverifiedObservers>) {
32     // We still have some items left to handle.
33     if (check_observer(std::get<CurrentIndex>(unverified_observers))) {
34       // The current observer is valid. Hence, append the index of the current
35       // item to the set of indices and head on to the next item.
36       DoInitialize<CurrentIndex + 1>(
37           dispatcher, check_observer, verified_observers, unverified_observers,
38           std::index_sequence<IndicesToSelect..., CurrentIndex>{});
39     } else {
40       // The current observer is not valid. Hence, head on to the next item with
41       // an unaltered list of indices.
42       DoInitialize<CurrentIndex + 1>(dispatcher, check_observer,
43                                      verified_observers, unverified_observers,
44                                      indices);
45     }
46   } else if constexpr (CurrentIndex == std::tuple_size_v<UnverifiedObservers>) {
47     // So we have met the end of the tuple of observers to verify.
48     // Hence, we extract the additional valid observers, append to the tuple of
49     // already verified observers and hand over to the dispatcher.
50     auto observers = std::tuple_cat(
51         verified_observers,
52         std::make_tuple(std::get<IndicesToSelect>(unverified_observers)...));
53 
54     // Do a final check that neither the maximum total number of observers nor
55     // the maximum number of optional observers is exceeded.
56     static_assert(std::tuple_size_v<decltype(observers)> <=
57                   configuration::kMaximumNumberOfObservers);
58     static_assert(sizeof...(IndicesToSelect) <=
59                   configuration::kMaximumNumberOfOptionalObservers);
60 
61     dispatcher.Initialize(std::move(observers));
62   }
63 }
64 
65 }  // namespace internal
66 
67 // The result of concatenating two tuple-types.
68 template <typename... tuples>
69 using TupleCat = decltype(std::tuple_cat(std::declval<tuples>()...));
70 
71 // Initializer collects mandatory and optional observers and initializes the
72 // passed Dispatcher with only the enabled observers.
73 //
74 // In some situations, presence of observers depends on runtime. i.e. command
75 // line parameters or CPU features. With 3 optional observers we already have 8
76 // different combinations. Initializer takes the job of dealing with all
77 // combinations from the user. It allows users to pass all observers (including
78 // nullptr for disabled optional observers) and initializes the Dispatcher with
79 // only the enabled observers.
80 //
81 // Since this process results in a combinatoric explosion, Initializer
82 // distinguishes between optional and mandatory observers. Mandatory observers
83 // are not included in the filtering process and must always be enabled (not
84 // nullptr).
85 //
86 // To allow the Initializer to track the number and exact type of observers, it
87 // is implemented as a templated class which holds information on the types in
88 // the std::tuples passed as template parameters. Therefore, whenever any type
89 // observer it set, the initializer changes its type to reflect this.
90 template <typename MandatoryObservers = std::tuple<>,
91           typename OptionalObservers = std::tuple<>>
92 struct BASE_EXPORT Initializer {
93   Initializer() = default;
InitializerInitializer94   Initializer(MandatoryObservers mandatory_observers,
95               OptionalObservers optional_observers)
96       : mandatory_observers_(std::move(mandatory_observers)),
97         optional_observers_(std::move(optional_observers)) {}
98 
99   // Set the mandatory observers. The number of observers that can be set is
100   // limited by configuration::maximum_number_of_observers.
101   template <typename... NewMandatoryObservers,
102             std::enable_if_t<
103                 internal::LessEqual((sizeof...(NewMandatoryObservers) +
104                                      std::tuple_size_v<OptionalObservers>),
105                                     configuration::kMaximumNumberOfObservers),
106                 bool> = true>
107   Initializer<std::tuple<NewMandatoryObservers*...>, OptionalObservers>
SetMandatoryObserversInitializer108   SetMandatoryObservers(NewMandatoryObservers*... mandatory_observers) const {
109     return {std::make_tuple(mandatory_observers...), GetOptionalObservers()};
110   }
111 
112   // Add mandatory observers. The number of observers that can be added is
113   // limited by the current number of observers, see
114   // configuration::maximum_number_of_observers.
115   template <typename... AdditionalMandatoryObservers,
116             std::enable_if_t<internal::LessEqual(
117                                  std::tuple_size_v<MandatoryObservers> +
118                                      sizeof...(AdditionalMandatoryObservers) +
119                                      std::tuple_size_v<OptionalObservers>,
120                                  configuration::kMaximumNumberOfObservers),
121                              bool> = true>
122   Initializer<TupleCat<MandatoryObservers,
123                        std::tuple<AdditionalMandatoryObservers*...>>,
124               OptionalObservers>
AddMandatoryObserversInitializer125   AddMandatoryObservers(
126       AdditionalMandatoryObservers*... additional_mandatory_observers) const {
127     return {std::tuple_cat(GetMandatoryObservers(),
128                            std::make_tuple(additional_mandatory_observers...)),
129             GetOptionalObservers()};
130   }
131 
132   // Set the optional observers. The number of observers that can be set is
133   // limited by configuration::maximum_number_of_optional_observers as well as
134   // configuration::maximum_number_of_observers.
135   template <
136       typename... NewOptionalObservers,
137       std::enable_if_t<
138           internal::LessEqual(
139               sizeof...(NewOptionalObservers),
140               configuration::kMaximumNumberOfOptionalObservers) &&
141               internal::LessEqual((sizeof...(NewOptionalObservers) +
142                                    std::tuple_size_v<MandatoryObservers>),
143                                   configuration::kMaximumNumberOfObservers),
144           bool> = true>
145   Initializer<MandatoryObservers, std::tuple<NewOptionalObservers*...>>
SetOptionalObserversInitializer146   SetOptionalObservers(NewOptionalObservers*... optional_observers) const {
147     return {GetMandatoryObservers(), std::make_tuple(optional_observers...)};
148   }
149 
150   // Add optional observers. The number of observers that can be added is
151   // limited by the current number of optional observers,
152   // configuration::maximum_number_of_optional_observers as well as
153   // configuration::maximum_number_of_observers.
154   template <
155       typename... AdditionalOptionalObservers,
156       std::enable_if_t<
157           internal::LessEqual(
158               std::tuple_size_v<OptionalObservers> +
159                   sizeof...(AdditionalOptionalObservers),
160               configuration::kMaximumNumberOfOptionalObservers) &&
161               internal::LessEqual((std::tuple_size_v<OptionalObservers> +
162                                    sizeof...(AdditionalOptionalObservers) +
163                                    std::tuple_size_v<MandatoryObservers>),
164                                   configuration::kMaximumNumberOfObservers),
165           bool> = true>
166   Initializer<
167       MandatoryObservers,
168       TupleCat<OptionalObservers, std::tuple<AdditionalOptionalObservers*...>>>
AddOptionalObserversInitializer169   AddOptionalObservers(
170       AdditionalOptionalObservers*... additional_optional_observers) const {
171     return {GetMandatoryObservers(),
172             std::tuple_cat(GetOptionalObservers(),
173                            std::make_tuple(additional_optional_observers...))};
174   }
175 
176   // Perform the actual initialization on the passed dispatcher.
177   // The dispatcher is passed as a template only to provide better testability.
178   template <typename DispatcherType>
DoInitializeInitializer179   void DoInitialize(DispatcherType& dispatcher) const {
180     internal::DoInitialize<0>(dispatcher, internal::IsValidObserver{},
181                               GetMandatoryObservers(), GetOptionalObservers(),
182                               {});
183   }
184 
GetMandatoryObserversInitializer185   const MandatoryObservers& GetMandatoryObservers() const {
186     return mandatory_observers_;
187   }
188 
GetOptionalObserversInitializer189   const OptionalObservers& GetOptionalObservers() const {
190     return optional_observers_;
191   }
192 
193  private:
194   MandatoryObservers mandatory_observers_;
195   OptionalObservers optional_observers_;
196 };
197 
198 // Convenience function for creating an empty Initializer.
CreateInitializer()199 inline Initializer<> CreateInitializer() {
200   return {};
201 }
202 
203 }  // namespace base::allocator::dispatcher
204 
205 #endif  // BASE_ALLOCATOR_DISPATCHER_INITIALIZER_H_
206