1 //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains some templates that are useful if you are working with the
13 // No library is required when using these functions.
15 //===----------------------------------------------------------------------===//
17 #ifndef LLVM_ADT_STLEXTRAS_H
18 #define LLVM_ADT_STLEXTRAS_H
20 #include "llvm/Support/Compiler.h"
22 #include <cstddef> // for std::size_t
23 #include <cstdlib> // for qsort
27 #include <utility> // for std::pair
31 //===----------------------------------------------------------------------===//
32 // Extra additions to <functional>
33 //===----------------------------------------------------------------------===//
36 struct identity : public std::unary_function<Ty, Ty> {
37 Ty &operator()(Ty &self) const {
40 const Ty &operator()(const Ty &self) const {
46 struct less_ptr : public std::binary_function<Ty, Ty, bool> {
47 bool operator()(const Ty* left, const Ty* right) const {
48 return *left < *right;
53 struct greater_ptr : public std::binary_function<Ty, Ty, bool> {
54 bool operator()(const Ty* left, const Ty* right) const {
55 return *right < *left;
59 /// An efficient, type-erasing, non-owning reference to a callable. This is
60 /// intended for use as the type of a function parameter that is not used
61 /// after the function in question returns.
63 /// This class does not own the callable, so it is not in general safe to store
65 template<typename Fn> class function_ref;
67 template<typename Ret, typename ...Params>
68 class function_ref<Ret(Params...)> {
69 Ret (*callback)(intptr_t callable, Params ...params);
72 template<typename Callable>
73 static Ret callback_fn(intptr_t callable, Params ...params) {
74 return (*reinterpret_cast<Callable*>(callable))(
75 std::forward<Params>(params)...);
79 template <typename Callable>
80 function_ref(Callable &&callable,
81 typename std::enable_if<
82 !std::is_same<typename std::remove_reference<Callable>::type,
83 function_ref>::value>::type * = nullptr)
84 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
85 callable(reinterpret_cast<intptr_t>(&callable)) {}
86 Ret operator()(Params ...params) const {
87 return callback(callable, std::forward<Params>(params)...);
91 // deleter - Very very very simple method that is used to invoke operator
92 // delete on something. It is used like this:
94 // for_each(V.begin(), B.end(), deleter<Interval>);
97 inline void deleter(T *Ptr) {
103 //===----------------------------------------------------------------------===//
104 // Extra additions to <iterator>
105 //===----------------------------------------------------------------------===//
107 // mapped_iterator - This is a simple iterator adapter that causes a function to
108 // be dereferenced whenever operator* is invoked on the iterator.
110 template <class RootIt, class UnaryFunc>
111 class mapped_iterator {
115 typedef typename std::iterator_traits<RootIt>::iterator_category
117 typedef typename std::iterator_traits<RootIt>::difference_type
119 typedef typename UnaryFunc::result_type value_type;
121 typedef void pointer;
122 //typedef typename UnaryFunc::result_type *pointer;
123 typedef void reference; // Can't modify value returned by fn
125 typedef RootIt iterator_type;
126 typedef mapped_iterator<RootIt, UnaryFunc> _Self;
128 inline const RootIt &getCurrent() const { return current; }
129 inline const UnaryFunc &getFunc() const { return Fn; }
131 inline explicit mapped_iterator(const RootIt &I, UnaryFunc F)
132 : current(I), Fn(F) {}
134 inline value_type operator*() const { // All this work to do this
135 return Fn(*current); // little change
138 _Self& operator++() { ++current; return *this; }
139 _Self& operator--() { --current; return *this; }
140 _Self operator++(int) { _Self __tmp = *this; ++current; return __tmp; }
141 _Self operator--(int) { _Self __tmp = *this; --current; return __tmp; }
142 _Self operator+ (difference_type n) const {
143 return _Self(current + n, Fn);
145 _Self& operator+= (difference_type n) { current += n; return *this; }
146 _Self operator- (difference_type n) const {
147 return _Self(current - n, Fn);
149 _Self& operator-= (difference_type n) { current -= n; return *this; }
150 reference operator[](difference_type n) const { return *(*this + n); }
152 inline bool operator!=(const _Self &X) const { return !operator==(X); }
153 inline bool operator==(const _Self &X) const { return current == X.current; }
154 inline bool operator< (const _Self &X) const { return current < X.current; }
156 inline difference_type operator-(const _Self &X) const {
157 return current - X.current;
161 template <class _Iterator, class Func>
162 inline mapped_iterator<_Iterator, Func>
163 operator+(typename mapped_iterator<_Iterator, Func>::difference_type N,
164 const mapped_iterator<_Iterator, Func>& X) {
165 return mapped_iterator<_Iterator, Func>(X.getCurrent() - N, X.getFunc());
169 // map_iterator - Provide a convenient way to create mapped_iterators, just like
170 // make_pair is useful for creating pairs...
172 template <class ItTy, class FuncTy>
173 inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) {
174 return mapped_iterator<ItTy, FuncTy>(I, F);
177 //===----------------------------------------------------------------------===//
178 // Extra additions to <utility>
179 //===----------------------------------------------------------------------===//
181 /// \brief Function object to check whether the first component of a std::pair
182 /// compares less than the first component of another std::pair.
184 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
185 return lhs.first < rhs.first;
189 /// \brief Function object to check whether the second component of a std::pair
190 /// compares less than the second component of another std::pair.
192 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
193 return lhs.second < rhs.second;
197 //===----------------------------------------------------------------------===//
198 // Extra additions for arrays
199 //===----------------------------------------------------------------------===//
201 /// Find the length of an array.
202 template <class T, std::size_t N>
203 LLVM_CONSTEXPR inline size_t array_lengthof(T (&)[N]) {
207 /// Adapt std::less<T> for array_pod_sort.
209 inline int array_pod_sort_comparator(const void *P1, const void *P2) {
210 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
211 *reinterpret_cast<const T*>(P2)))
213 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
214 *reinterpret_cast<const T*>(P1)))
219 /// get_array_pod_sort_comparator - This is an internal helper function used to
220 /// get type deduction of T right.
222 inline int (*get_array_pod_sort_comparator(const T &))
223 (const void*, const void*) {
224 return array_pod_sort_comparator<T>;
228 /// array_pod_sort - This sorts an array with the specified start and end
229 /// extent. This is just like std::sort, except that it calls qsort instead of
230 /// using an inlined template. qsort is slightly slower than std::sort, but
231 /// most sorts are not performance critical in LLVM and std::sort has to be
232 /// template instantiated for each type, leading to significant measured code
233 /// bloat. This function should generally be used instead of std::sort where
236 /// This function assumes that you have simple POD-like types that can be
237 /// compared with std::less and can be moved with memcpy. If this isn't true,
238 /// you should use std::sort.
240 /// NOTE: If qsort_r were portable, we could allow a custom comparator and
241 /// default to std::less.
242 template<class IteratorTy>
243 inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
244 // Don't dereference start iterator of empty sequence.
245 if (Start == End) return;
246 qsort(&*Start, End-Start, sizeof(*Start),
247 get_array_pod_sort_comparator(*Start));
250 template <class IteratorTy>
251 inline void array_pod_sort(
252 IteratorTy Start, IteratorTy End,
254 const typename std::iterator_traits<IteratorTy>::value_type *,
255 const typename std::iterator_traits<IteratorTy>::value_type *)) {
256 // Don't dereference start iterator of empty sequence.
257 if (Start == End) return;
258 qsort(&*Start, End - Start, sizeof(*Start),
259 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
262 //===----------------------------------------------------------------------===//
263 // Extra additions to <algorithm>
264 //===----------------------------------------------------------------------===//
266 /// For a container of pointers, deletes the pointers and then clears the
268 template<typename Container>
269 void DeleteContainerPointers(Container &C) {
270 for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
275 /// In a container of pairs (usually a map) whose second element is a pointer,
276 /// deletes the second elements and then clears the container.
277 template<typename Container>
278 void DeleteContainerSeconds(Container &C) {
279 for (typename Container::iterator I = C.begin(), E = C.end(); I != E; ++I)
284 //===----------------------------------------------------------------------===//
285 // Extra additions to <memory>
286 //===----------------------------------------------------------------------===//
288 // Implement make_unique according to N3656.
290 /// \brief Constructs a `new T()` with the given args and returns a
291 /// `unique_ptr<T>` which owns the object.
295 /// auto p = make_unique<int>();
296 /// auto p = make_unique<std::tuple<int, int>>(0, 1);
297 template <class T, class... Args>
298 typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
299 make_unique(Args &&... args) {
300 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
303 /// \brief Constructs a `new T[n]` with the given args and returns a
304 /// `unique_ptr<T[]>` which owns the object.
306 /// \param n size of the new array.
310 /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
312 typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
313 std::unique_ptr<T>>::type
314 make_unique(size_t n) {
315 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
318 /// This function isn't used and is only here to provide better compile errors.
319 template <class T, class... Args>
320 typename std::enable_if<std::extent<T>::value != 0>::type
321 make_unique(Args &&...) LLVM_DELETED_FUNCTION;
324 void operator()(void* v) {
329 template<typename First, typename Second>
331 size_t operator()(const std::pair<First, Second> &P) const {
332 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
336 /// A functor like C++14's std::less<void> in its absence.
338 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
339 return std::forward<A>(a) < std::forward<B>(b);
343 /// A functor like C++14's std::equal<void> in its absence.
345 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
346 return std::forward<A>(a) == std::forward<B>(b);
350 /// Binary functor that adapts to any other binary functor after dereferencing
352 template <typename T> struct deref {
354 // Could be further improved to cope with non-derivable functors and
355 // non-binary functors (should be a variadic template member function
357 template <typename A, typename B>
358 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
361 return func(*lhs, *rhs);
365 } // End llvm namespace