• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 #ifndef ART_LIBARTBASE_BASE_STL_UTIL_H_
18 #define ART_LIBARTBASE_BASE_STL_UTIL_H_
19 
20 #include <algorithm>
21 #include <iterator>
22 #include <set>
23 #include <sstream>
24 
25 #include <android-base/logging.h>
26 
27 #include "base/iteration_range.h"
28 
29 namespace art {
30 
31 // STLDeleteContainerPointers()
32 //  For a range within a container of pointers, calls delete
33 //  (non-array version) on these pointers.
34 // NOTE: for these three functions, we could just implement a DeleteObject
35 // functor and then call for_each() on the range and functor, but this
36 // requires us to pull in all of algorithm.h, which seems expensive.
37 // For hash_[multi]set, it is important that this deletes behind the iterator
38 // because the hash_set may call the hash function on the iterator when it is
39 // advanced, which could result in the hash function trying to deference a
40 // stale pointer.
41 template <class ForwardIterator>
STLDeleteContainerPointers(ForwardIterator begin,ForwardIterator end)42 void STLDeleteContainerPointers(ForwardIterator begin,
43                                 ForwardIterator end) {
44   while (begin != end) {
45     ForwardIterator temp = begin;
46     ++begin;
47     delete *temp;
48   }
49 }
50 
51 // STLDeleteElements() deletes all the elements in an STL container and clears
52 // the container.  This function is suitable for use with a vector, set,
53 // hash_set, or any other STL container which defines sensible begin(), end(),
54 // and clear() methods.
55 //
56 // If container is null, this function is a no-op.
57 //
58 // As an alternative to calling STLDeleteElements() directly, consider
59 // using a container of std::unique_ptr, which ensures that your container's
60 // elements are deleted when the container goes out of scope.
61 template <class T>
STLDeleteElements(T * container)62 void STLDeleteElements(T *container) {
63   if (container != nullptr) {
64     STLDeleteContainerPointers(container->begin(), container->end());
65     container->clear();
66   }
67 }
68 
69 // Given an STL container consisting of (key, value) pairs, STLDeleteValues
70 // deletes all the "value" components and clears the container.  Does nothing
71 // in the case it's given a null pointer.
72 template <class T>
STLDeleteValues(T * v)73 void STLDeleteValues(T *v) {
74   if (v != nullptr) {
75     for (typename T::iterator i = v->begin(); i != v->end(); ++i) {
76       delete i->second;
77     }
78     v->clear();
79   }
80 }
81 
82 // Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
83 struct FreeDelete {
84   // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
operatorFreeDelete85   void operator()(const void* ptr) const {
86     free(const_cast<void*>(ptr));
87   }
88 };
89 
90 // Alias for std::unique_ptr<> that uses the C function free() to delete objects.
91 template <typename T>
92 using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
93 
94 // Find index of the first element with the specified value known to be in the container.
95 template <typename Container, typename T>
IndexOfElement(const Container & container,const T & value)96 size_t IndexOfElement(const Container& container, const T& value) {
97   auto it = std::find(container.begin(), container.end(), value);
98   DCHECK(it != container.end());  // Must exist.
99   return std::distance(container.begin(), it);
100 }
101 
102 // Remove the first element with the specified value known to be in the container.
103 template <typename Container, typename T>
RemoveElement(Container & container,const T & value)104 void RemoveElement(Container& container, const T& value) {
105   auto it = std::find(container.begin(), container.end(), value);
106   DCHECK(it != container.end());  // Must exist.
107   container.erase(it);
108 }
109 
110 // Replace the first element with the specified old_value known to be in the container.
111 template <typename Container, typename T>
ReplaceElement(Container & container,const T & old_value,const T & new_value)112 void ReplaceElement(Container& container, const T& old_value, const T& new_value) {
113   auto it = std::find(container.begin(), container.end(), old_value);
114   DCHECK(it != container.end());  // Must exist.
115   *it = new_value;
116 }
117 
118 // Search for an element with the specified value and return true if it was found, false otherwise.
119 template <typename Container, typename T>
120 bool ContainsElement(const Container& container, const T& value, size_t start_pos = 0u) {
121   DCHECK_LE(start_pos, container.size());
122   auto start = container.begin();
123   std::advance(start, start_pos);
124   auto it = std::find(start, container.end(), value);
125   return it != container.end();
126 }
127 
128 template <typename T>
ContainsElement(const std::set<T> & container,const T & value)129 bool ContainsElement(const std::set<T>& container, const T& value) {
130   return container.count(value) != 0u;
131 }
132 
133 // 32-bit FNV-1a hash function suitable for std::unordered_map.
134 // It can be used with any container which works with range-based for loop.
135 // See http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
136 template <typename Vector>
137 struct FNVHash {
operatorFNVHash138   size_t operator()(const Vector& vector) const {
139     uint32_t hash = 2166136261u;
140     for (const auto& value : vector) {
141       hash = (hash ^ value) * 16777619u;
142     }
143     return hash;
144   }
145 };
146 
147 // Returns a copy of the passed vector that doesn't memory-own its entries.
148 template <typename T>
MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>> & src)149 static inline std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
150   std::vector<T*> result;
151   result.reserve(src.size());
152   for (const std::unique_ptr<T>& t : src) {
153     result.push_back(t.get());
154   }
155   return result;
156 }
157 
158 template <typename IterLeft, typename IterRight>
159 class ZipLeftIter {
160  public:
161   using iterator_category = std::forward_iterator_tag;
162   using value_type = std::pair<typename IterLeft::value_type, typename IterRight::value_type>;
163   using difference_type = ptrdiff_t;
164   using pointer = void;
165   using reference = void;
166 
ZipLeftIter(IterLeft left,IterRight right)167   ZipLeftIter(IterLeft left, IterRight right) : left_iter_(left), right_iter_(right) {}
168   ZipLeftIter<IterLeft, IterRight>& operator++() {
169     ++left_iter_;
170     ++right_iter_;
171     return *this;
172   }
173   ZipLeftIter<IterLeft, IterRight> operator++(int) {
174     ZipLeftIter<IterLeft, IterRight> ret(left_iter_, right_iter_);
175     ++(*this);
176     return ret;
177   }
178   bool operator==(const ZipLeftIter<IterLeft, IterRight>& other) const {
179     return left_iter_ == other.left_iter_;
180   }
181   bool operator!=(const ZipLeftIter<IterLeft, IterRight>& other) const {
182     return !(*this == other);
183   }
184   std::pair<typename IterLeft::value_type, typename IterRight::value_type> operator*() const {
185     return std::make_pair(*left_iter_, *right_iter_);
186   }
187 
188  private:
189   IterLeft left_iter_;
190   IterRight right_iter_;
191 };
192 
193 class CountIter {
194  public:
195   using iterator_category = std::forward_iterator_tag;
196   using value_type = size_t;
197   using difference_type = size_t;
198   using pointer = void;
199   using reference = void;
200 
CountIter()201   CountIter() : count_(0) {}
CountIter(size_t count)202   explicit CountIter(size_t count) : count_(count) {}
203   CountIter& operator++() {
204     ++count_;
205     return *this;
206   }
207   CountIter operator++(int) {
208     size_t ret = count_;
209     ++count_;
210     return CountIter(ret);
211   }
212   bool operator==(const CountIter& other) const {
213     return count_ == other.count_;
214   }
215   bool operator!=(const CountIter& other) const {
216     return !(*this == other);
217   }
218   size_t operator*() const {
219     return count_;
220   }
221 
222  private:
223   size_t count_;
224 };
225 
226 // Make an iteration range that returns a pair of the element and the index of the element.
227 template <typename Iter>
ZipCount(IterationRange<Iter> iter)228 static inline IterationRange<ZipLeftIter<Iter, CountIter>> ZipCount(IterationRange<Iter> iter) {
229   return IterationRange(ZipLeftIter(iter.begin(), CountIter(0)),
230                         ZipLeftIter(iter.end(), CountIter(-1)));
231 }
232 
233 // Make an iteration range that returns a pair of the outputs of two iterators. Stops when the first
234 // (left) one is exhausted. The left iterator must be at least as long as the right one.
235 template <typename IterLeft, typename IterRight>
ZipLeft(IterationRange<IterLeft> iter_left,IterationRange<IterRight> iter_right)236 static inline IterationRange<ZipLeftIter<IterLeft, IterRight>> ZipLeft(
237     IterationRange<IterLeft> iter_left, IterationRange<IterRight> iter_right) {
238   return IterationRange(ZipLeftIter(iter_left.begin(), iter_right.begin()),
239                         ZipLeftIter(iter_left.end(), iter_right.end()));
240 }
241 
Range(size_t start,size_t end)242 static inline IterationRange<CountIter> Range(size_t start, size_t end) {
243   return IterationRange(CountIter(start), CountIter(end));
244 }
245 
Range(size_t end)246 static inline IterationRange<CountIter> Range(size_t end) {
247   return Range(0, end);
248 }
249 
250 template <typename RealIter, typename Filter>
251 struct FilterIterator {
252  public:
253   using iterator_category = std::forward_iterator_tag;
254   using value_type = typename std::iterator_traits<RealIter>::value_type;
255   using difference_type = ptrdiff_t;
256   using pointer = typename std::iterator_traits<RealIter>::pointer;
257   using reference = typename std::iterator_traits<RealIter>::reference;
258 
259   FilterIterator(RealIter rl,
260                  Filter cond,
261                  std::optional<RealIter> end = std::nullopt)
real_iter_FilterIterator262       : real_iter_(rl), cond_(cond), end_(end) {
263     DCHECK(std::make_optional(rl) == end_ || cond_(*real_iter_));
264   }
265 
266   FilterIterator<RealIter, Filter>& operator++() {
267     DCHECK(std::make_optional(real_iter_) != end_);
268     do {
269       if (std::make_optional(++real_iter_) == end_) {
270         break;
271       }
272     } while (!cond_(*real_iter_));
273     return *this;
274   }
275   FilterIterator<RealIter, Filter> operator++(int) {
276     FilterIterator<RealIter, Filter> ret(real_iter_, cond_, end_);
277     ++(*this);
278     return ret;
279   }
280   bool operator==(const FilterIterator<RealIter, Filter>& other) const {
281     return real_iter_ == other.real_iter_;
282   }
283   bool operator!=(const FilterIterator<RealIter, Filter>& other) const {
284     return !(*this == other);
285   }
286   typename RealIter::value_type operator*() const {
287     return *real_iter_;
288   }
289 
290  private:
291   RealIter real_iter_;
292   Filter cond_;
293   std::optional<RealIter> end_;
294 };
295 
296 template <typename BaseRange, typename FilterT>
Filter(BaseRange && range,FilterT cond)297 static inline auto Filter(BaseRange&& range, FilterT cond) {
298   auto end = range.end();
299   auto start = std::find_if(range.begin(), end, cond);
300   return MakeIterationRange(FilterIterator(start, cond, std::make_optional(end)),
301                             FilterIterator(end, cond, std::make_optional(end)));
302 }
303 
304 template <typename Val>
305 struct NonNullFilter {
306  public:
307   static_assert(std::is_pointer_v<Val>, "Must be pointer type!");
operatorNonNullFilter308   constexpr bool operator()(Val v) const {
309     return v != nullptr;
310   }
311 };
312 
313 template <typename InnerIter>
314 using FilterNull = FilterIterator<InnerIter, NonNullFilter<typename InnerIter::value_type>>;
315 
316 template <typename InnerIter>
FilterOutNull(IterationRange<InnerIter> inner)317 static inline IterationRange<FilterNull<InnerIter>> FilterOutNull(IterationRange<InnerIter> inner) {
318   return Filter(inner, NonNullFilter<typename InnerIter::value_type>());
319 }
320 
321 template <typename Val>
322 struct SafePrinter  {
323   const Val* val_;
324 };
325 
326 template<typename Val>
327 std::ostream& operator<<(std::ostream& os, const SafePrinter<Val>& v) {
328   if (v.val_ == nullptr) {
329     return os << "NULL";
330   } else {
331     return os << *v.val_;
332   }
333 }
334 
335 template<typename Val>
SafePrint(const Val * v)336 SafePrinter<Val> SafePrint(const Val* v) {
337   return SafePrinter<Val>{v};
338 }
339 
340 // Helper struct for iterating a split-string without allocation.
341 struct SplitStringIter {
342  public:
343   using iterator_category = std::forward_iterator_tag;
344   using value_type = std::string_view;
345   using difference_type = ptrdiff_t;
346   using pointer = void;
347   using reference = void;
348 
349   // Direct iterator constructor. The iteration state is only the current index.
350   // We use that with the split char and the full string to get the current and
351   // next segment.
SplitStringIterSplitStringIter352   SplitStringIter(size_t index, char split, std::string_view sv)
353       : cur_index_(index), split_on_(split), sv_(sv) {}
354   SplitStringIter(const SplitStringIter&) = default;
355   SplitStringIter(SplitStringIter&&) = default;
356   SplitStringIter& operator=(SplitStringIter&&) = default;
357   SplitStringIter& operator=(const SplitStringIter&) = default;
358 
359   SplitStringIter& operator++() {
360     size_t nxt = sv_.find(split_on_, cur_index_);
361     if (nxt == std::string_view::npos) {
362       cur_index_ = std::string_view::npos;
363     } else {
364       cur_index_ = nxt + 1;
365     }
366     return *this;
367   }
368 
369   SplitStringIter operator++(int) {
370     SplitStringIter ret(cur_index_, split_on_, sv_);
371     ++(*this);
372     return ret;
373   }
374 
375   bool operator==(const SplitStringIter& other) const {
376     return sv_ == other.sv_ && split_on_ == other.split_on_ && cur_index_== other.cur_index_;
377   }
378 
379   bool operator!=(const SplitStringIter& other) const {
380     return !(*this == other);
381   }
382 
383   typename std::string_view operator*() const {
384     return sv_.substr(cur_index_, sv_.substr(cur_index_).find(split_on_));
385   }
386 
387  private:
388   size_t cur_index_;
389   char split_on_;
390   std::string_view sv_;
391 };
392 
393 // Create an iteration range over the string 'sv' split at each 'target' occurrence.
394 // Eg: SplitString(":foo::bar") -> ["", "foo", "", "bar"]
SplitString(std::string_view sv,char target)395 inline IterationRange<SplitStringIter> SplitString(std::string_view sv, char target) {
396   return MakeIterationRange(SplitStringIter(0, target, sv),
397                             SplitStringIter(std::string_view::npos, target, sv));
398 }
399 
400 }  // namespace art
401 
402 #endif  // ART_LIBARTBASE_BASE_STL_UTIL_H_
403