10b57cec5SDimitry Andric //===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 81fd87a68SDimitry Andric /// 91fd87a68SDimitry Andric /// \file 101fd87a68SDimitry Andric /// This file contains some templates that are useful if you are working with 111fd87a68SDimitry Andric /// the STL at all. 121fd87a68SDimitry Andric /// 131fd87a68SDimitry Andric /// No library is required when using these functions. 141fd87a68SDimitry Andric /// 150b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 160b57cec5SDimitry Andric 170b57cec5SDimitry Andric #ifndef LLVM_ADT_STLEXTRAS_H 180b57cec5SDimitry Andric #define LLVM_ADT_STLEXTRAS_H 190b57cec5SDimitry Andric 20*bdd1243dSDimitry Andric #include "llvm/ADT/Hashing.h" 21fe6060f1SDimitry Andric #include "llvm/ADT/STLForwardCompat.h" 2204eeddc0SDimitry Andric #include "llvm/ADT/STLFunctionalExtras.h" 231fd87a68SDimitry Andric #include "llvm/ADT/identity.h" 240b57cec5SDimitry Andric #include "llvm/ADT/iterator.h" 250b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h" 260b57cec5SDimitry Andric #include "llvm/Config/abi-breaking.h" 270b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 280b57cec5SDimitry Andric #include <algorithm> 290b57cec5SDimitry Andric #include <cassert> 300b57cec5SDimitry Andric #include <cstddef> 310b57cec5SDimitry Andric #include <cstdint> 320b57cec5SDimitry Andric #include <cstdlib> 330b57cec5SDimitry Andric #include <functional> 340b57cec5SDimitry Andric #include <initializer_list> 350b57cec5SDimitry Andric #include <iterator> 360b57cec5SDimitry Andric #include <limits> 370b57cec5SDimitry Andric #include <memory> 38*bdd1243dSDimitry Andric #include <optional> 390b57cec5SDimitry Andric #include <tuple> 400b57cec5SDimitry Andric #include <type_traits> 410b57cec5SDimitry Andric #include <utility> 420b57cec5SDimitry Andric 430b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 440b57cec5SDimitry Andric #include <random> // for std::mt19937 450b57cec5SDimitry Andric #endif 460b57cec5SDimitry Andric 470b57cec5SDimitry Andric namespace llvm { 480b57cec5SDimitry Andric 490b57cec5SDimitry Andric // Only used by compiler if both template types are the same. Useful when 500b57cec5SDimitry Andric // using SFINAE to test for the existence of member functions. 510b57cec5SDimitry Andric template <typename T, T> struct SameType; 520b57cec5SDimitry Andric 530b57cec5SDimitry Andric namespace detail { 540b57cec5SDimitry Andric 550b57cec5SDimitry Andric template <typename RangeT> 560b57cec5SDimitry Andric using IterOfRange = decltype(std::begin(std::declval<RangeT &>())); 570b57cec5SDimitry Andric 585ffd83dbSDimitry Andric template <typename RangeT> 59*bdd1243dSDimitry Andric using ValueOfRange = 60*bdd1243dSDimitry Andric std::remove_reference_t<decltype(*std::begin(std::declval<RangeT &>()))>; 615ffd83dbSDimitry Andric 620b57cec5SDimitry Andric } // end namespace detail 630b57cec5SDimitry Andric 640b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 650b57cec5SDimitry Andric // Extra additions to <type_traits> 660b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric template <typename T> struct make_const_ptr { 69*bdd1243dSDimitry Andric using type = std::add_pointer_t<std::add_const_t<T>>; 700b57cec5SDimitry Andric }; 710b57cec5SDimitry Andric 720b57cec5SDimitry Andric template <typename T> struct make_const_ref { 73*bdd1243dSDimitry Andric using type = std::add_lvalue_reference_t<std::add_const_t<T>>; 740b57cec5SDimitry Andric }; 750b57cec5SDimitry Andric 765ffd83dbSDimitry Andric namespace detail { 775ffd83dbSDimitry Andric template <class, template <class...> class Op, class... Args> struct detector { 785ffd83dbSDimitry Andric using value_t = std::false_type; 795ffd83dbSDimitry Andric }; 805ffd83dbSDimitry Andric template <template <class...> class Op, class... Args> 81*bdd1243dSDimitry Andric struct detector<std::void_t<Op<Args...>>, Op, Args...> { 825ffd83dbSDimitry Andric using value_t = std::true_type; 835ffd83dbSDimitry Andric }; 845ffd83dbSDimitry Andric } // end namespace detail 855ffd83dbSDimitry Andric 86fe6060f1SDimitry Andric /// Detects if a given trait holds for some set of arguments 'Args'. 87fe6060f1SDimitry Andric /// For example, the given trait could be used to detect if a given type 88fe6060f1SDimitry Andric /// has a copy assignment operator: 89fe6060f1SDimitry Andric /// template<class T> 90fe6060f1SDimitry Andric /// using has_copy_assign_t = decltype(std::declval<T&>() 91fe6060f1SDimitry Andric /// = std::declval<const T&>()); 92fe6060f1SDimitry Andric /// bool fooHasCopyAssign = is_detected<has_copy_assign_t, FooClass>::value; 935ffd83dbSDimitry Andric template <template <class...> class Op, class... Args> 945ffd83dbSDimitry Andric using is_detected = typename detail::detector<void, Op, Args...>::value_t; 955ffd83dbSDimitry Andric 965ffd83dbSDimitry Andric /// This class provides various trait information about a callable object. 975ffd83dbSDimitry Andric /// * To access the number of arguments: Traits::num_args 985ffd83dbSDimitry Andric /// * To access the type of an argument: Traits::arg_t<Index> 995ffd83dbSDimitry Andric /// * To access the type of the result: Traits::result_t 1005ffd83dbSDimitry Andric template <typename T, bool isClass = std::is_class<T>::value> 1015ffd83dbSDimitry Andric struct function_traits : public function_traits<decltype(&T::operator())> {}; 1025ffd83dbSDimitry Andric 1035ffd83dbSDimitry Andric /// Overload for class function types. 1045ffd83dbSDimitry Andric template <typename ClassType, typename ReturnType, typename... Args> 1055ffd83dbSDimitry Andric struct function_traits<ReturnType (ClassType::*)(Args...) const, false> { 1065ffd83dbSDimitry Andric /// The number of arguments to this function. 1075ffd83dbSDimitry Andric enum { num_args = sizeof...(Args) }; 1085ffd83dbSDimitry Andric 1095ffd83dbSDimitry Andric /// The result type of this function. 1105ffd83dbSDimitry Andric using result_t = ReturnType; 1115ffd83dbSDimitry Andric 1125ffd83dbSDimitry Andric /// The type of an argument to this function. 1135ffd83dbSDimitry Andric template <size_t Index> 114*bdd1243dSDimitry Andric using arg_t = std::tuple_element_t<Index, std::tuple<Args...>>; 1155ffd83dbSDimitry Andric }; 1165ffd83dbSDimitry Andric /// Overload for class function types. 1175ffd83dbSDimitry Andric template <typename ClassType, typename ReturnType, typename... Args> 1185ffd83dbSDimitry Andric struct function_traits<ReturnType (ClassType::*)(Args...), false> 11981ad6265SDimitry Andric : public function_traits<ReturnType (ClassType::*)(Args...) const> {}; 1205ffd83dbSDimitry Andric /// Overload for non-class function types. 1215ffd83dbSDimitry Andric template <typename ReturnType, typename... Args> 1225ffd83dbSDimitry Andric struct function_traits<ReturnType (*)(Args...), false> { 1235ffd83dbSDimitry Andric /// The number of arguments to this function. 1245ffd83dbSDimitry Andric enum { num_args = sizeof...(Args) }; 1255ffd83dbSDimitry Andric 1265ffd83dbSDimitry Andric /// The result type of this function. 1275ffd83dbSDimitry Andric using result_t = ReturnType; 1285ffd83dbSDimitry Andric 1295ffd83dbSDimitry Andric /// The type of an argument to this function. 1305ffd83dbSDimitry Andric template <size_t i> 131*bdd1243dSDimitry Andric using arg_t = std::tuple_element_t<i, std::tuple<Args...>>; 1325ffd83dbSDimitry Andric }; 13381ad6265SDimitry Andric template <typename ReturnType, typename... Args> 13481ad6265SDimitry Andric struct function_traits<ReturnType (*const)(Args...), false> 13581ad6265SDimitry Andric : public function_traits<ReturnType (*)(Args...)> {}; 1365ffd83dbSDimitry Andric /// Overload for non-class function type references. 1375ffd83dbSDimitry Andric template <typename ReturnType, typename... Args> 1385ffd83dbSDimitry Andric struct function_traits<ReturnType (&)(Args...), false> 1395ffd83dbSDimitry Andric : public function_traits<ReturnType (*)(Args...)> {}; 1405ffd83dbSDimitry Andric 1410eae32dcSDimitry Andric /// traits class for checking whether type T is one of any of the given 1420eae32dcSDimitry Andric /// types in the variadic list. 1430eae32dcSDimitry Andric template <typename T, typename... Ts> 144*bdd1243dSDimitry Andric using is_one_of = std::disjunction<std::is_same<T, Ts>...>; 1450eae32dcSDimitry Andric 1460eae32dcSDimitry Andric /// traits class for checking whether type T is a base class for all 1470eae32dcSDimitry Andric /// the given types in the variadic list. 1480eae32dcSDimitry Andric template <typename T, typename... Ts> 149*bdd1243dSDimitry Andric using are_base_of = std::conjunction<std::is_base_of<T, Ts>...>; 1500eae32dcSDimitry Andric 1510eae32dcSDimitry Andric namespace detail { 1520eae32dcSDimitry Andric template <typename T, typename... Us> struct TypesAreDistinct; 1530eae32dcSDimitry Andric template <typename T, typename... Us> 1540eae32dcSDimitry Andric struct TypesAreDistinct 1550eae32dcSDimitry Andric : std::integral_constant<bool, !is_one_of<T, Us...>::value && 1560eae32dcSDimitry Andric TypesAreDistinct<Us...>::value> {}; 1570eae32dcSDimitry Andric template <typename T> struct TypesAreDistinct<T> : std::true_type {}; 1580eae32dcSDimitry Andric } // namespace detail 1590eae32dcSDimitry Andric 1600eae32dcSDimitry Andric /// Determine if all types in Ts are distinct. 1610eae32dcSDimitry Andric /// 1620eae32dcSDimitry Andric /// Useful to statically assert when Ts is intended to describe a non-multi set 1630eae32dcSDimitry Andric /// of types. 1640eae32dcSDimitry Andric /// 1650eae32dcSDimitry Andric /// Expensive (currently quadratic in sizeof(Ts...)), and so should only be 1660eae32dcSDimitry Andric /// asserted once per instantiation of a type which requires it. 1670eae32dcSDimitry Andric template <typename... Ts> struct TypesAreDistinct; 1680eae32dcSDimitry Andric template <> struct TypesAreDistinct<> : std::true_type {}; 1690eae32dcSDimitry Andric template <typename... Ts> 1700eae32dcSDimitry Andric struct TypesAreDistinct 1710eae32dcSDimitry Andric : std::integral_constant<bool, detail::TypesAreDistinct<Ts...>::value> {}; 1720eae32dcSDimitry Andric 1730eae32dcSDimitry Andric /// Find the first index where a type appears in a list of types. 1740eae32dcSDimitry Andric /// 1750eae32dcSDimitry Andric /// FirstIndexOfType<T, Us...>::value is the first index of T in Us. 1760eae32dcSDimitry Andric /// 1770eae32dcSDimitry Andric /// Typically only meaningful when it is otherwise statically known that the 1780eae32dcSDimitry Andric /// type pack has no duplicate types. This should be guaranteed explicitly with 1790eae32dcSDimitry Andric /// static_assert(TypesAreDistinct<Us...>::value). 1800eae32dcSDimitry Andric /// 1810eae32dcSDimitry Andric /// It is a compile-time error to instantiate when T is not present in Us, i.e. 1820eae32dcSDimitry Andric /// if is_one_of<T, Us...>::value is false. 1830eae32dcSDimitry Andric template <typename T, typename... Us> struct FirstIndexOfType; 1840eae32dcSDimitry Andric template <typename T, typename U, typename... Us> 1850eae32dcSDimitry Andric struct FirstIndexOfType<T, U, Us...> 1860eae32dcSDimitry Andric : std::integral_constant<size_t, 1 + FirstIndexOfType<T, Us...>::value> {}; 1870eae32dcSDimitry Andric template <typename T, typename... Us> 1880eae32dcSDimitry Andric struct FirstIndexOfType<T, T, Us...> : std::integral_constant<size_t, 0> {}; 1890eae32dcSDimitry Andric 1900eae32dcSDimitry Andric /// Find the type at a given index in a list of types. 1910eae32dcSDimitry Andric /// 1920eae32dcSDimitry Andric /// TypeAtIndex<I, Ts...> is the type at index I in Ts. 1930eae32dcSDimitry Andric template <size_t I, typename... Ts> 1940eae32dcSDimitry Andric using TypeAtIndex = std::tuple_element_t<I, std::tuple<Ts...>>; 1950eae32dcSDimitry Andric 19681ad6265SDimitry Andric /// Helper which adds two underlying types of enumeration type. 19781ad6265SDimitry Andric /// Implicit conversion to a common type is accepted. 19881ad6265SDimitry Andric template <typename EnumTy1, typename EnumTy2, 19981ad6265SDimitry Andric typename UT1 = std::enable_if_t<std::is_enum<EnumTy1>::value, 20081ad6265SDimitry Andric std::underlying_type_t<EnumTy1>>, 20181ad6265SDimitry Andric typename UT2 = std::enable_if_t<std::is_enum<EnumTy2>::value, 20281ad6265SDimitry Andric std::underlying_type_t<EnumTy2>>> 20381ad6265SDimitry Andric constexpr auto addEnumValues(EnumTy1 LHS, EnumTy2 RHS) { 20481ad6265SDimitry Andric return static_cast<UT1>(LHS) + static_cast<UT2>(RHS); 20581ad6265SDimitry Andric } 20681ad6265SDimitry Andric 2070b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 2080b57cec5SDimitry Andric // Extra additions to <iterator> 2090b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 2100b57cec5SDimitry Andric 211*bdd1243dSDimitry Andric namespace callable_detail { 212*bdd1243dSDimitry Andric 213*bdd1243dSDimitry Andric /// Templated storage wrapper for a callable. 214*bdd1243dSDimitry Andric /// 215*bdd1243dSDimitry Andric /// This class is consistently default constructible, copy / move 216*bdd1243dSDimitry Andric /// constructible / assignable. 217*bdd1243dSDimitry Andric /// 218*bdd1243dSDimitry Andric /// Supported callable types: 219*bdd1243dSDimitry Andric /// - Function pointer 220*bdd1243dSDimitry Andric /// - Function reference 221*bdd1243dSDimitry Andric /// - Lambda 222*bdd1243dSDimitry Andric /// - Function object 223*bdd1243dSDimitry Andric template <typename T, 224*bdd1243dSDimitry Andric bool = std::is_function_v<std::remove_pointer_t<remove_cvref_t<T>>>> 225*bdd1243dSDimitry Andric class Callable { 226*bdd1243dSDimitry Andric using value_type = std::remove_reference_t<T>; 227*bdd1243dSDimitry Andric using reference = value_type &; 228*bdd1243dSDimitry Andric using const_reference = value_type const &; 229*bdd1243dSDimitry Andric 230*bdd1243dSDimitry Andric std::optional<value_type> Obj; 231*bdd1243dSDimitry Andric 232*bdd1243dSDimitry Andric static_assert(!std::is_pointer_v<value_type>, 233*bdd1243dSDimitry Andric "Pointers to non-functions are not callable."); 234*bdd1243dSDimitry Andric 235*bdd1243dSDimitry Andric public: 236*bdd1243dSDimitry Andric Callable() = default; 237*bdd1243dSDimitry Andric Callable(T const &O) : Obj(std::in_place, O) {} 238*bdd1243dSDimitry Andric 239*bdd1243dSDimitry Andric Callable(Callable const &Other) = default; 240*bdd1243dSDimitry Andric Callable(Callable &&Other) = default; 241*bdd1243dSDimitry Andric 242*bdd1243dSDimitry Andric Callable &operator=(Callable const &Other) { 243*bdd1243dSDimitry Andric Obj = std::nullopt; 244*bdd1243dSDimitry Andric if (Other.Obj) 245*bdd1243dSDimitry Andric Obj.emplace(*Other.Obj); 246*bdd1243dSDimitry Andric return *this; 247*bdd1243dSDimitry Andric } 248*bdd1243dSDimitry Andric 249*bdd1243dSDimitry Andric Callable &operator=(Callable &&Other) { 250*bdd1243dSDimitry Andric Obj = std::nullopt; 251*bdd1243dSDimitry Andric if (Other.Obj) 252*bdd1243dSDimitry Andric Obj.emplace(std::move(*Other.Obj)); 253*bdd1243dSDimitry Andric return *this; 254*bdd1243dSDimitry Andric } 255*bdd1243dSDimitry Andric 256*bdd1243dSDimitry Andric template <typename... Pn, 257*bdd1243dSDimitry Andric std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0> 258*bdd1243dSDimitry Andric decltype(auto) operator()(Pn &&...Params) { 259*bdd1243dSDimitry Andric return (*Obj)(std::forward<Pn>(Params)...); 260*bdd1243dSDimitry Andric } 261*bdd1243dSDimitry Andric 262*bdd1243dSDimitry Andric template <typename... Pn, 263*bdd1243dSDimitry Andric std::enable_if_t<std::is_invocable_v<T const, Pn...>, int> = 0> 264*bdd1243dSDimitry Andric decltype(auto) operator()(Pn &&...Params) const { 265*bdd1243dSDimitry Andric return (*Obj)(std::forward<Pn>(Params)...); 266*bdd1243dSDimitry Andric } 267*bdd1243dSDimitry Andric 268*bdd1243dSDimitry Andric bool valid() const { return Obj != std::nullopt; } 269*bdd1243dSDimitry Andric bool reset() { return Obj = std::nullopt; } 270*bdd1243dSDimitry Andric 271*bdd1243dSDimitry Andric operator reference() { return *Obj; } 272*bdd1243dSDimitry Andric operator const_reference() const { return *Obj; } 273*bdd1243dSDimitry Andric }; 274*bdd1243dSDimitry Andric 275*bdd1243dSDimitry Andric // Function specialization. No need to waste extra space wrapping with a 276*bdd1243dSDimitry Andric // std::optional. 277*bdd1243dSDimitry Andric template <typename T> class Callable<T, true> { 278*bdd1243dSDimitry Andric static constexpr bool IsPtr = std::is_pointer_v<remove_cvref_t<T>>; 279*bdd1243dSDimitry Andric 280*bdd1243dSDimitry Andric using StorageT = std::conditional_t<IsPtr, T, std::remove_reference_t<T> *>; 281*bdd1243dSDimitry Andric using CastT = std::conditional_t<IsPtr, T, T &>; 282*bdd1243dSDimitry Andric 283*bdd1243dSDimitry Andric private: 284*bdd1243dSDimitry Andric StorageT Func = nullptr; 285*bdd1243dSDimitry Andric 286*bdd1243dSDimitry Andric private: 287*bdd1243dSDimitry Andric template <typename In> static constexpr auto convertIn(In &&I) { 288*bdd1243dSDimitry Andric if constexpr (IsPtr) { 289*bdd1243dSDimitry Andric // Pointer... just echo it back. 290*bdd1243dSDimitry Andric return I; 291*bdd1243dSDimitry Andric } else { 292*bdd1243dSDimitry Andric // Must be a function reference. Return its address. 293*bdd1243dSDimitry Andric return &I; 294*bdd1243dSDimitry Andric } 295*bdd1243dSDimitry Andric } 296*bdd1243dSDimitry Andric 297*bdd1243dSDimitry Andric public: 298*bdd1243dSDimitry Andric Callable() = default; 299*bdd1243dSDimitry Andric 300*bdd1243dSDimitry Andric // Construct from a function pointer or reference. 301*bdd1243dSDimitry Andric // 302*bdd1243dSDimitry Andric // Disable this constructor for references to 'Callable' so we don't violate 303*bdd1243dSDimitry Andric // the rule of 0. 304*bdd1243dSDimitry Andric template < // clang-format off 305*bdd1243dSDimitry Andric typename FnPtrOrRef, 306*bdd1243dSDimitry Andric std::enable_if_t< 307*bdd1243dSDimitry Andric !std::is_same_v<remove_cvref_t<FnPtrOrRef>, Callable>, int 308*bdd1243dSDimitry Andric > = 0 309*bdd1243dSDimitry Andric > // clang-format on 310*bdd1243dSDimitry Andric Callable(FnPtrOrRef &&F) : Func(convertIn(F)) {} 311*bdd1243dSDimitry Andric 312*bdd1243dSDimitry Andric template <typename... Pn, 313*bdd1243dSDimitry Andric std::enable_if_t<std::is_invocable_v<T, Pn...>, int> = 0> 314*bdd1243dSDimitry Andric decltype(auto) operator()(Pn &&...Params) const { 315*bdd1243dSDimitry Andric return Func(std::forward<Pn>(Params)...); 316*bdd1243dSDimitry Andric } 317*bdd1243dSDimitry Andric 318*bdd1243dSDimitry Andric bool valid() const { return Func != nullptr; } 319*bdd1243dSDimitry Andric void reset() { Func = nullptr; } 320*bdd1243dSDimitry Andric 321*bdd1243dSDimitry Andric operator T const &() const { 322*bdd1243dSDimitry Andric if constexpr (IsPtr) { 323*bdd1243dSDimitry Andric // T is a pointer... just echo it back. 324*bdd1243dSDimitry Andric return Func; 325*bdd1243dSDimitry Andric } else { 326*bdd1243dSDimitry Andric static_assert(std::is_reference_v<T>, 327*bdd1243dSDimitry Andric "Expected a reference to a function."); 328*bdd1243dSDimitry Andric // T is a function reference... dereference the stored pointer. 329*bdd1243dSDimitry Andric return *Func; 330*bdd1243dSDimitry Andric } 331*bdd1243dSDimitry Andric } 332*bdd1243dSDimitry Andric }; 333*bdd1243dSDimitry Andric 334*bdd1243dSDimitry Andric } // namespace callable_detail 335*bdd1243dSDimitry Andric 3360b57cec5SDimitry Andric namespace adl_detail { 3370b57cec5SDimitry Andric 3380b57cec5SDimitry Andric using std::begin; 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric template <typename ContainerTy> 3415ffd83dbSDimitry Andric decltype(auto) adl_begin(ContainerTy &&container) { 3420b57cec5SDimitry Andric return begin(std::forward<ContainerTy>(container)); 3430b57cec5SDimitry Andric } 3440b57cec5SDimitry Andric 3450b57cec5SDimitry Andric using std::end; 3460b57cec5SDimitry Andric 3470b57cec5SDimitry Andric template <typename ContainerTy> 3485ffd83dbSDimitry Andric decltype(auto) adl_end(ContainerTy &&container) { 3490b57cec5SDimitry Andric return end(std::forward<ContainerTy>(container)); 3500b57cec5SDimitry Andric } 3510b57cec5SDimitry Andric 3520b57cec5SDimitry Andric using std::swap; 3530b57cec5SDimitry Andric 3540b57cec5SDimitry Andric template <typename T> 3550b57cec5SDimitry Andric void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(), 3560b57cec5SDimitry Andric std::declval<T>()))) { 3570b57cec5SDimitry Andric swap(std::forward<T>(lhs), std::forward<T>(rhs)); 3580b57cec5SDimitry Andric } 3590b57cec5SDimitry Andric 3600b57cec5SDimitry Andric } // end namespace adl_detail 3610b57cec5SDimitry Andric 3620b57cec5SDimitry Andric template <typename ContainerTy> 3635ffd83dbSDimitry Andric decltype(auto) adl_begin(ContainerTy &&container) { 3640b57cec5SDimitry Andric return adl_detail::adl_begin(std::forward<ContainerTy>(container)); 3650b57cec5SDimitry Andric } 3660b57cec5SDimitry Andric 3670b57cec5SDimitry Andric template <typename ContainerTy> 3685ffd83dbSDimitry Andric decltype(auto) adl_end(ContainerTy &&container) { 3690b57cec5SDimitry Andric return adl_detail::adl_end(std::forward<ContainerTy>(container)); 3700b57cec5SDimitry Andric } 3710b57cec5SDimitry Andric 3720b57cec5SDimitry Andric template <typename T> 3730b57cec5SDimitry Andric void adl_swap(T &&lhs, T &&rhs) noexcept( 3740b57cec5SDimitry Andric noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) { 3750b57cec5SDimitry Andric adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs)); 3760b57cec5SDimitry Andric } 3770b57cec5SDimitry Andric 3785ffd83dbSDimitry Andric /// Returns true if the given container only contains a single element. 3795ffd83dbSDimitry Andric template <typename ContainerTy> bool hasSingleElement(ContainerTy &&C) { 3805ffd83dbSDimitry Andric auto B = std::begin(C), E = std::end(C); 3815ffd83dbSDimitry Andric return B != E && std::next(B) == E; 3825ffd83dbSDimitry Andric } 3835ffd83dbSDimitry Andric 384480093f4SDimitry Andric /// Return a range covering \p RangeOrContainer with the first N elements 385480093f4SDimitry Andric /// excluded. 386e8d8bef9SDimitry Andric template <typename T> auto drop_begin(T &&RangeOrContainer, size_t N = 1) { 387480093f4SDimitry Andric return make_range(std::next(adl_begin(RangeOrContainer), N), 388480093f4SDimitry Andric adl_end(RangeOrContainer)); 389480093f4SDimitry Andric } 390480093f4SDimitry Andric 39181ad6265SDimitry Andric /// Return a range covering \p RangeOrContainer with the last N elements 39281ad6265SDimitry Andric /// excluded. 39381ad6265SDimitry Andric template <typename T> auto drop_end(T &&RangeOrContainer, size_t N = 1) { 39481ad6265SDimitry Andric return make_range(adl_begin(RangeOrContainer), 39581ad6265SDimitry Andric std::prev(adl_end(RangeOrContainer), N)); 39681ad6265SDimitry Andric } 39781ad6265SDimitry Andric 3980b57cec5SDimitry Andric // mapped_iterator - This is a simple iterator adapter that causes a function to 3990b57cec5SDimitry Andric // be applied whenever operator* is invoked on the iterator. 4000b57cec5SDimitry Andric 4010b57cec5SDimitry Andric template <typename ItTy, typename FuncTy, 402349cc55cSDimitry Andric typename ReferenceTy = 4030b57cec5SDimitry Andric decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))> 4040b57cec5SDimitry Andric class mapped_iterator 4050b57cec5SDimitry Andric : public iterator_adaptor_base< 4060b57cec5SDimitry Andric mapped_iterator<ItTy, FuncTy>, ItTy, 4070b57cec5SDimitry Andric typename std::iterator_traits<ItTy>::iterator_category, 408349cc55cSDimitry Andric std::remove_reference_t<ReferenceTy>, 409349cc55cSDimitry Andric typename std::iterator_traits<ItTy>::difference_type, 410349cc55cSDimitry Andric std::remove_reference_t<ReferenceTy> *, ReferenceTy> { 4110b57cec5SDimitry Andric public: 412*bdd1243dSDimitry Andric mapped_iterator() = default; 4130b57cec5SDimitry Andric mapped_iterator(ItTy U, FuncTy F) 4140b57cec5SDimitry Andric : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {} 4150b57cec5SDimitry Andric 4160b57cec5SDimitry Andric ItTy getCurrent() { return this->I; } 4170b57cec5SDimitry Andric 418349cc55cSDimitry Andric const FuncTy &getFunction() const { return F; } 419349cc55cSDimitry Andric 420349cc55cSDimitry Andric ReferenceTy operator*() const { return F(*this->I); } 4210b57cec5SDimitry Andric 4220b57cec5SDimitry Andric private: 423*bdd1243dSDimitry Andric callable_detail::Callable<FuncTy> F{}; 4240b57cec5SDimitry Andric }; 4250b57cec5SDimitry Andric 4260b57cec5SDimitry Andric // map_iterator - Provide a convenient way to create mapped_iterators, just like 4270b57cec5SDimitry Andric // make_pair is useful for creating pairs... 4280b57cec5SDimitry Andric template <class ItTy, class FuncTy> 4290b57cec5SDimitry Andric inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) { 4300b57cec5SDimitry Andric return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F)); 4310b57cec5SDimitry Andric } 4320b57cec5SDimitry Andric 4330b57cec5SDimitry Andric template <class ContainerTy, class FuncTy> 4345ffd83dbSDimitry Andric auto map_range(ContainerTy &&C, FuncTy F) { 4350b57cec5SDimitry Andric return make_range(map_iterator(C.begin(), F), map_iterator(C.end(), F)); 4360b57cec5SDimitry Andric } 4370b57cec5SDimitry Andric 438349cc55cSDimitry Andric /// A base type of mapped iterator, that is useful for building derived 439349cc55cSDimitry Andric /// iterators that do not need/want to store the map function (as in 440349cc55cSDimitry Andric /// mapped_iterator). These iterators must simply provide a `mapElement` method 441349cc55cSDimitry Andric /// that defines how to map a value of the iterator to the provided reference 442349cc55cSDimitry Andric /// type. 443349cc55cSDimitry Andric template <typename DerivedT, typename ItTy, typename ReferenceTy> 444349cc55cSDimitry Andric class mapped_iterator_base 445349cc55cSDimitry Andric : public iterator_adaptor_base< 446349cc55cSDimitry Andric DerivedT, ItTy, 447349cc55cSDimitry Andric typename std::iterator_traits<ItTy>::iterator_category, 448349cc55cSDimitry Andric std::remove_reference_t<ReferenceTy>, 449349cc55cSDimitry Andric typename std::iterator_traits<ItTy>::difference_type, 450349cc55cSDimitry Andric std::remove_reference_t<ReferenceTy> *, ReferenceTy> { 451349cc55cSDimitry Andric public: 452349cc55cSDimitry Andric using BaseT = mapped_iterator_base; 453349cc55cSDimitry Andric 454349cc55cSDimitry Andric mapped_iterator_base(ItTy U) 455349cc55cSDimitry Andric : mapped_iterator_base::iterator_adaptor_base(std::move(U)) {} 456349cc55cSDimitry Andric 457349cc55cSDimitry Andric ItTy getCurrent() { return this->I; } 458349cc55cSDimitry Andric 459349cc55cSDimitry Andric ReferenceTy operator*() const { 460349cc55cSDimitry Andric return static_cast<const DerivedT &>(*this).mapElement(*this->I); 461349cc55cSDimitry Andric } 462349cc55cSDimitry Andric }; 463349cc55cSDimitry Andric 4640b57cec5SDimitry Andric /// Helper to determine if type T has a member called rbegin(). 4650b57cec5SDimitry Andric template <typename Ty> class has_rbegin_impl { 4660b57cec5SDimitry Andric using yes = char[1]; 4670b57cec5SDimitry Andric using no = char[2]; 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric template <typename Inner> 4700b57cec5SDimitry Andric static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr); 4710b57cec5SDimitry Andric 4720b57cec5SDimitry Andric template <typename> 4730b57cec5SDimitry Andric static no& test(...); 4740b57cec5SDimitry Andric 4750b57cec5SDimitry Andric public: 4760b57cec5SDimitry Andric static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); 4770b57cec5SDimitry Andric }; 4780b57cec5SDimitry Andric 4790b57cec5SDimitry Andric /// Metafunction to determine if T& or T has a member called rbegin(). 4800b57cec5SDimitry Andric template <typename Ty> 481*bdd1243dSDimitry Andric struct has_rbegin : has_rbegin_impl<std::remove_reference_t<Ty>> {}; 4820b57cec5SDimitry Andric 4830b57cec5SDimitry Andric // Returns an iterator_range over the given container which iterates in reverse. 484*bdd1243dSDimitry Andric template <typename ContainerTy> auto reverse(ContainerTy &&C) { 485*bdd1243dSDimitry Andric if constexpr (has_rbegin<ContainerTy>::value) 4860b57cec5SDimitry Andric return make_range(C.rbegin(), C.rend()); 487*bdd1243dSDimitry Andric else 48804eeddc0SDimitry Andric return make_range(std::make_reverse_iterator(std::end(C)), 48904eeddc0SDimitry Andric std::make_reverse_iterator(std::begin(C))); 4900b57cec5SDimitry Andric } 4910b57cec5SDimitry Andric 4920b57cec5SDimitry Andric /// An iterator adaptor that filters the elements of given inner iterators. 4930b57cec5SDimitry Andric /// 4940b57cec5SDimitry Andric /// The predicate parameter should be a callable object that accepts the wrapped 4950b57cec5SDimitry Andric /// iterator's reference type and returns a bool. When incrementing or 4960b57cec5SDimitry Andric /// decrementing the iterator, it will call the predicate on each element and 4970b57cec5SDimitry Andric /// skip any where it returns false. 4980b57cec5SDimitry Andric /// 4990b57cec5SDimitry Andric /// \code 5000b57cec5SDimitry Andric /// int A[] = { 1, 2, 3, 4 }; 5010b57cec5SDimitry Andric /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; }); 5020b57cec5SDimitry Andric /// // R contains { 1, 3 }. 5030b57cec5SDimitry Andric /// \endcode 5040b57cec5SDimitry Andric /// 5050b57cec5SDimitry Andric /// Note: filter_iterator_base implements support for forward iteration. 5060b57cec5SDimitry Andric /// filter_iterator_impl exists to provide support for bidirectional iteration, 5070b57cec5SDimitry Andric /// conditional on whether the wrapped iterator supports it. 5080b57cec5SDimitry Andric template <typename WrappedIteratorT, typename PredicateT, typename IterTag> 5090b57cec5SDimitry Andric class filter_iterator_base 5100b57cec5SDimitry Andric : public iterator_adaptor_base< 5110b57cec5SDimitry Andric filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>, 5120b57cec5SDimitry Andric WrappedIteratorT, 513*bdd1243dSDimitry Andric std::common_type_t<IterTag, 514*bdd1243dSDimitry Andric typename std::iterator_traits< 515*bdd1243dSDimitry Andric WrappedIteratorT>::iterator_category>> { 516349cc55cSDimitry Andric using BaseT = typename filter_iterator_base::iterator_adaptor_base; 5170b57cec5SDimitry Andric 5180b57cec5SDimitry Andric protected: 5190b57cec5SDimitry Andric WrappedIteratorT End; 5200b57cec5SDimitry Andric PredicateT Pred; 5210b57cec5SDimitry Andric 5220b57cec5SDimitry Andric void findNextValid() { 5230b57cec5SDimitry Andric while (this->I != End && !Pred(*this->I)) 5240b57cec5SDimitry Andric BaseT::operator++(); 5250b57cec5SDimitry Andric } 5260b57cec5SDimitry Andric 527*bdd1243dSDimitry Andric filter_iterator_base() = default; 528*bdd1243dSDimitry Andric 5290b57cec5SDimitry Andric // Construct the iterator. The begin iterator needs to know where the end 5300b57cec5SDimitry Andric // is, so that it can properly stop when it gets there. The end iterator only 5310b57cec5SDimitry Andric // needs the predicate to support bidirectional iteration. 5320b57cec5SDimitry Andric filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End, 5330b57cec5SDimitry Andric PredicateT Pred) 5340b57cec5SDimitry Andric : BaseT(Begin), End(End), Pred(Pred) { 5350b57cec5SDimitry Andric findNextValid(); 5360b57cec5SDimitry Andric } 5370b57cec5SDimitry Andric 5380b57cec5SDimitry Andric public: 5390b57cec5SDimitry Andric using BaseT::operator++; 5400b57cec5SDimitry Andric 5410b57cec5SDimitry Andric filter_iterator_base &operator++() { 5420b57cec5SDimitry Andric BaseT::operator++(); 5430b57cec5SDimitry Andric findNextValid(); 5440b57cec5SDimitry Andric return *this; 5450b57cec5SDimitry Andric } 54681ad6265SDimitry Andric 54781ad6265SDimitry Andric decltype(auto) operator*() const { 54881ad6265SDimitry Andric assert(BaseT::wrapped() != End && "Cannot dereference end iterator!"); 54981ad6265SDimitry Andric return BaseT::operator*(); 55081ad6265SDimitry Andric } 55181ad6265SDimitry Andric 55281ad6265SDimitry Andric decltype(auto) operator->() const { 55381ad6265SDimitry Andric assert(BaseT::wrapped() != End && "Cannot dereference end iterator!"); 55481ad6265SDimitry Andric return BaseT::operator->(); 55581ad6265SDimitry Andric } 5560b57cec5SDimitry Andric }; 5570b57cec5SDimitry Andric 5580b57cec5SDimitry Andric /// Specialization of filter_iterator_base for forward iteration only. 5590b57cec5SDimitry Andric template <typename WrappedIteratorT, typename PredicateT, 5600b57cec5SDimitry Andric typename IterTag = std::forward_iterator_tag> 5610b57cec5SDimitry Andric class filter_iterator_impl 5620b57cec5SDimitry Andric : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> { 5630b57cec5SDimitry Andric public: 564*bdd1243dSDimitry Andric filter_iterator_impl() = default; 565*bdd1243dSDimitry Andric 5660b57cec5SDimitry Andric filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, 5670b57cec5SDimitry Andric PredicateT Pred) 568349cc55cSDimitry Andric : filter_iterator_impl::filter_iterator_base(Begin, End, Pred) {} 5690b57cec5SDimitry Andric }; 5700b57cec5SDimitry Andric 5710b57cec5SDimitry Andric /// Specialization of filter_iterator_base for bidirectional iteration. 5720b57cec5SDimitry Andric template <typename WrappedIteratorT, typename PredicateT> 5730b57cec5SDimitry Andric class filter_iterator_impl<WrappedIteratorT, PredicateT, 5740b57cec5SDimitry Andric std::bidirectional_iterator_tag> 5750b57cec5SDimitry Andric : public filter_iterator_base<WrappedIteratorT, PredicateT, 5760b57cec5SDimitry Andric std::bidirectional_iterator_tag> { 577349cc55cSDimitry Andric using BaseT = typename filter_iterator_impl::filter_iterator_base; 578349cc55cSDimitry Andric 5790b57cec5SDimitry Andric void findPrevValid() { 5800b57cec5SDimitry Andric while (!this->Pred(*this->I)) 5810b57cec5SDimitry Andric BaseT::operator--(); 5820b57cec5SDimitry Andric } 5830b57cec5SDimitry Andric 5840b57cec5SDimitry Andric public: 5850b57cec5SDimitry Andric using BaseT::operator--; 5860b57cec5SDimitry Andric 587*bdd1243dSDimitry Andric filter_iterator_impl() = default; 588*bdd1243dSDimitry Andric 5890b57cec5SDimitry Andric filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End, 5900b57cec5SDimitry Andric PredicateT Pred) 5910b57cec5SDimitry Andric : BaseT(Begin, End, Pred) {} 5920b57cec5SDimitry Andric 5930b57cec5SDimitry Andric filter_iterator_impl &operator--() { 5940b57cec5SDimitry Andric BaseT::operator--(); 5950b57cec5SDimitry Andric findPrevValid(); 5960b57cec5SDimitry Andric return *this; 5970b57cec5SDimitry Andric } 5980b57cec5SDimitry Andric }; 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric namespace detail { 6010b57cec5SDimitry Andric 6020b57cec5SDimitry Andric template <bool is_bidirectional> struct fwd_or_bidi_tag_impl { 6030b57cec5SDimitry Andric using type = std::forward_iterator_tag; 6040b57cec5SDimitry Andric }; 6050b57cec5SDimitry Andric 6060b57cec5SDimitry Andric template <> struct fwd_or_bidi_tag_impl<true> { 6070b57cec5SDimitry Andric using type = std::bidirectional_iterator_tag; 6080b57cec5SDimitry Andric }; 6090b57cec5SDimitry Andric 6100b57cec5SDimitry Andric /// Helper which sets its type member to forward_iterator_tag if the category 6110b57cec5SDimitry Andric /// of \p IterT does not derive from bidirectional_iterator_tag, and to 6120b57cec5SDimitry Andric /// bidirectional_iterator_tag otherwise. 6130b57cec5SDimitry Andric template <typename IterT> struct fwd_or_bidi_tag { 6140b57cec5SDimitry Andric using type = typename fwd_or_bidi_tag_impl<std::is_base_of< 6150b57cec5SDimitry Andric std::bidirectional_iterator_tag, 6160b57cec5SDimitry Andric typename std::iterator_traits<IterT>::iterator_category>::value>::type; 6170b57cec5SDimitry Andric }; 6180b57cec5SDimitry Andric 6190b57cec5SDimitry Andric } // namespace detail 6200b57cec5SDimitry Andric 6210b57cec5SDimitry Andric /// Defines filter_iterator to a suitable specialization of 6220b57cec5SDimitry Andric /// filter_iterator_impl, based on the underlying iterator's category. 6230b57cec5SDimitry Andric template <typename WrappedIteratorT, typename PredicateT> 6240b57cec5SDimitry Andric using filter_iterator = filter_iterator_impl< 6250b57cec5SDimitry Andric WrappedIteratorT, PredicateT, 6260b57cec5SDimitry Andric typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>; 6270b57cec5SDimitry Andric 6280b57cec5SDimitry Andric /// Convenience function that takes a range of elements and a predicate, 6290b57cec5SDimitry Andric /// and return a new filter_iterator range. 6300b57cec5SDimitry Andric /// 6310b57cec5SDimitry Andric /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the 6320b57cec5SDimitry Andric /// lifetime of that temporary is not kept by the returned range object, and the 6330b57cec5SDimitry Andric /// temporary is going to be dropped on the floor after the make_iterator_range 6340b57cec5SDimitry Andric /// full expression that contains this function call. 6350b57cec5SDimitry Andric template <typename RangeT, typename PredicateT> 6360b57cec5SDimitry Andric iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>> 6370b57cec5SDimitry Andric make_filter_range(RangeT &&Range, PredicateT Pred) { 6380b57cec5SDimitry Andric using FilterIteratorT = 6390b57cec5SDimitry Andric filter_iterator<detail::IterOfRange<RangeT>, PredicateT>; 6400b57cec5SDimitry Andric return make_range( 6410b57cec5SDimitry Andric FilterIteratorT(std::begin(std::forward<RangeT>(Range)), 6420b57cec5SDimitry Andric std::end(std::forward<RangeT>(Range)), Pred), 6430b57cec5SDimitry Andric FilterIteratorT(std::end(std::forward<RangeT>(Range)), 6440b57cec5SDimitry Andric std::end(std::forward<RangeT>(Range)), Pred)); 6450b57cec5SDimitry Andric } 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric /// A pseudo-iterator adaptor that is designed to implement "early increment" 6480b57cec5SDimitry Andric /// style loops. 6490b57cec5SDimitry Andric /// 6500b57cec5SDimitry Andric /// This is *not a normal iterator* and should almost never be used directly. It 6510b57cec5SDimitry Andric /// is intended primarily to be used with range based for loops and some range 6520b57cec5SDimitry Andric /// algorithms. 6530b57cec5SDimitry Andric /// 6540b57cec5SDimitry Andric /// The iterator isn't quite an `OutputIterator` or an `InputIterator` but 6550b57cec5SDimitry Andric /// somewhere between them. The constraints of these iterators are: 6560b57cec5SDimitry Andric /// 6570b57cec5SDimitry Andric /// - On construction or after being incremented, it is comparable and 6580b57cec5SDimitry Andric /// dereferencable. It is *not* incrementable. 6590b57cec5SDimitry Andric /// - After being dereferenced, it is neither comparable nor dereferencable, it 6600b57cec5SDimitry Andric /// is only incrementable. 6610b57cec5SDimitry Andric /// 6620b57cec5SDimitry Andric /// This means you can only dereference the iterator once, and you can only 6630b57cec5SDimitry Andric /// increment it once between dereferences. 6640b57cec5SDimitry Andric template <typename WrappedIteratorT> 6650b57cec5SDimitry Andric class early_inc_iterator_impl 6660b57cec5SDimitry Andric : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>, 6670b57cec5SDimitry Andric WrappedIteratorT, std::input_iterator_tag> { 668349cc55cSDimitry Andric using BaseT = typename early_inc_iterator_impl::iterator_adaptor_base; 6690b57cec5SDimitry Andric 6700b57cec5SDimitry Andric using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer; 6710b57cec5SDimitry Andric 6720b57cec5SDimitry Andric protected: 6730b57cec5SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS 6740b57cec5SDimitry Andric bool IsEarlyIncremented = false; 6750b57cec5SDimitry Andric #endif 6760b57cec5SDimitry Andric 6770b57cec5SDimitry Andric public: 6780b57cec5SDimitry Andric early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {} 6790b57cec5SDimitry Andric 6800b57cec5SDimitry Andric using BaseT::operator*; 681e8d8bef9SDimitry Andric decltype(*std::declval<WrappedIteratorT>()) operator*() { 6820b57cec5SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS 6830b57cec5SDimitry Andric assert(!IsEarlyIncremented && "Cannot dereference twice!"); 6840b57cec5SDimitry Andric IsEarlyIncremented = true; 6850b57cec5SDimitry Andric #endif 6860b57cec5SDimitry Andric return *(this->I)++; 6870b57cec5SDimitry Andric } 6880b57cec5SDimitry Andric 6890b57cec5SDimitry Andric using BaseT::operator++; 6900b57cec5SDimitry Andric early_inc_iterator_impl &operator++() { 6910b57cec5SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS 6920b57cec5SDimitry Andric assert(IsEarlyIncremented && "Cannot increment before dereferencing!"); 6930b57cec5SDimitry Andric IsEarlyIncremented = false; 6940b57cec5SDimitry Andric #endif 6950b57cec5SDimitry Andric return *this; 6960b57cec5SDimitry Andric } 6970b57cec5SDimitry Andric 698e8d8bef9SDimitry Andric friend bool operator==(const early_inc_iterator_impl &LHS, 699e8d8bef9SDimitry Andric const early_inc_iterator_impl &RHS) { 7000b57cec5SDimitry Andric #if LLVM_ENABLE_ABI_BREAKING_CHECKS 701e8d8bef9SDimitry Andric assert(!LHS.IsEarlyIncremented && "Cannot compare after dereferencing!"); 7020b57cec5SDimitry Andric #endif 703e8d8bef9SDimitry Andric return (const BaseT &)LHS == (const BaseT &)RHS; 7040b57cec5SDimitry Andric } 7050b57cec5SDimitry Andric }; 7060b57cec5SDimitry Andric 7070b57cec5SDimitry Andric /// Make a range that does early increment to allow mutation of the underlying 7080b57cec5SDimitry Andric /// range without disrupting iteration. 7090b57cec5SDimitry Andric /// 7100b57cec5SDimitry Andric /// The underlying iterator will be incremented immediately after it is 7110b57cec5SDimitry Andric /// dereferenced, allowing deletion of the current node or insertion of nodes to 7120b57cec5SDimitry Andric /// not disrupt iteration provided they do not invalidate the *next* iterator -- 7130b57cec5SDimitry Andric /// the current iterator can be invalidated. 7140b57cec5SDimitry Andric /// 7150b57cec5SDimitry Andric /// This requires a very exact pattern of use that is only really suitable to 7160b57cec5SDimitry Andric /// range based for loops and other range algorithms that explicitly guarantee 7170b57cec5SDimitry Andric /// to dereference exactly once each element, and to increment exactly once each 7180b57cec5SDimitry Andric /// element. 7190b57cec5SDimitry Andric template <typename RangeT> 7200b57cec5SDimitry Andric iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>> 7210b57cec5SDimitry Andric make_early_inc_range(RangeT &&Range) { 7220b57cec5SDimitry Andric using EarlyIncIteratorT = 7230b57cec5SDimitry Andric early_inc_iterator_impl<detail::IterOfRange<RangeT>>; 7240b57cec5SDimitry Andric return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))), 7250b57cec5SDimitry Andric EarlyIncIteratorT(std::end(std::forward<RangeT>(Range)))); 7260b57cec5SDimitry Andric } 7270b57cec5SDimitry Andric 728*bdd1243dSDimitry Andric // Forward declarations required by zip_shortest/zip_equal/zip_first/zip_longest 7290b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 7300b57cec5SDimitry Andric bool all_of(R &&range, UnaryPredicate P); 731*bdd1243dSDimitry Andric 7320b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 7330b57cec5SDimitry Andric bool any_of(R &&range, UnaryPredicate P); 7340b57cec5SDimitry Andric 735*bdd1243dSDimitry Andric template <typename T> bool all_equal(std::initializer_list<T> Values); 736*bdd1243dSDimitry Andric 7370b57cec5SDimitry Andric namespace detail { 7380b57cec5SDimitry Andric 7390b57cec5SDimitry Andric using std::declval; 7400b57cec5SDimitry Andric 7410b57cec5SDimitry Andric // We have to alias this since inlining the actual type at the usage site 7420b57cec5SDimitry Andric // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017. 7430b57cec5SDimitry Andric template<typename... Iters> struct ZipTupleType { 7440b57cec5SDimitry Andric using type = std::tuple<decltype(*declval<Iters>())...>; 7450b57cec5SDimitry Andric }; 7460b57cec5SDimitry Andric 7470b57cec5SDimitry Andric template <typename ZipType, typename... Iters> 7480b57cec5SDimitry Andric using zip_traits = iterator_facade_base< 749*bdd1243dSDimitry Andric ZipType, 750*bdd1243dSDimitry Andric std::common_type_t< 751*bdd1243dSDimitry Andric std::bidirectional_iterator_tag, 752*bdd1243dSDimitry Andric typename std::iterator_traits<Iters>::iterator_category...>, 7530b57cec5SDimitry Andric // ^ TODO: Implement random access methods. 7540b57cec5SDimitry Andric typename ZipTupleType<Iters...>::type, 755*bdd1243dSDimitry Andric typename std::iterator_traits< 756*bdd1243dSDimitry Andric std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type, 7570b57cec5SDimitry Andric // ^ FIXME: This follows boost::make_zip_iterator's assumption that all 7580b57cec5SDimitry Andric // inner iterators have the same difference_type. It would fail if, for 7590b57cec5SDimitry Andric // instance, the second field's difference_type were non-numeric while the 7600b57cec5SDimitry Andric // first is. 7610b57cec5SDimitry Andric typename ZipTupleType<Iters...>::type *, 7620b57cec5SDimitry Andric typename ZipTupleType<Iters...>::type>; 7630b57cec5SDimitry Andric 7640b57cec5SDimitry Andric template <typename ZipType, typename... Iters> 7650b57cec5SDimitry Andric struct zip_common : public zip_traits<ZipType, Iters...> { 7660b57cec5SDimitry Andric using Base = zip_traits<ZipType, Iters...>; 7670b57cec5SDimitry Andric using value_type = typename Base::value_type; 7680b57cec5SDimitry Andric 7690b57cec5SDimitry Andric std::tuple<Iters...> iterators; 7700b57cec5SDimitry Andric 7710b57cec5SDimitry Andric protected: 7728bcb0991SDimitry Andric template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const { 7730b57cec5SDimitry Andric return value_type(*std::get<Ns>(iterators)...); 7740b57cec5SDimitry Andric } 7750b57cec5SDimitry Andric 7760b57cec5SDimitry Andric template <size_t... Ns> 7778bcb0991SDimitry Andric decltype(iterators) tup_inc(std::index_sequence<Ns...>) const { 7780b57cec5SDimitry Andric return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...); 7790b57cec5SDimitry Andric } 7800b57cec5SDimitry Andric 7810b57cec5SDimitry Andric template <size_t... Ns> 7828bcb0991SDimitry Andric decltype(iterators) tup_dec(std::index_sequence<Ns...>) const { 7830b57cec5SDimitry Andric return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...); 7840b57cec5SDimitry Andric } 7850b57cec5SDimitry Andric 786349cc55cSDimitry Andric template <size_t... Ns> 787349cc55cSDimitry Andric bool test_all_equals(const zip_common &other, 788349cc55cSDimitry Andric std::index_sequence<Ns...>) const { 789*bdd1243dSDimitry Andric return ((std::get<Ns>(this->iterators) == std::get<Ns>(other.iterators)) && 790*bdd1243dSDimitry Andric ...); 791349cc55cSDimitry Andric } 792349cc55cSDimitry Andric 7930b57cec5SDimitry Andric public: 7940b57cec5SDimitry Andric zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {} 7950b57cec5SDimitry Andric 796349cc55cSDimitry Andric value_type operator*() const { 7978bcb0991SDimitry Andric return deref(std::index_sequence_for<Iters...>{}); 7980b57cec5SDimitry Andric } 7990b57cec5SDimitry Andric 8000b57cec5SDimitry Andric ZipType &operator++() { 8018bcb0991SDimitry Andric iterators = tup_inc(std::index_sequence_for<Iters...>{}); 8020b57cec5SDimitry Andric return *reinterpret_cast<ZipType *>(this); 8030b57cec5SDimitry Andric } 8040b57cec5SDimitry Andric 8050b57cec5SDimitry Andric ZipType &operator--() { 8060b57cec5SDimitry Andric static_assert(Base::IsBidirectional, 8070b57cec5SDimitry Andric "All inner iterators must be at least bidirectional."); 8088bcb0991SDimitry Andric iterators = tup_dec(std::index_sequence_for<Iters...>{}); 8090b57cec5SDimitry Andric return *reinterpret_cast<ZipType *>(this); 8100b57cec5SDimitry Andric } 811349cc55cSDimitry Andric 812349cc55cSDimitry Andric /// Return true if all the iterator are matching `other`'s iterators. 813349cc55cSDimitry Andric bool all_equals(zip_common &other) { 814349cc55cSDimitry Andric return test_all_equals(other, std::index_sequence_for<Iters...>{}); 815349cc55cSDimitry Andric } 8160b57cec5SDimitry Andric }; 8170b57cec5SDimitry Andric 8180b57cec5SDimitry Andric template <typename... Iters> 8190b57cec5SDimitry Andric struct zip_first : public zip_common<zip_first<Iters...>, Iters...> { 8200b57cec5SDimitry Andric using Base = zip_common<zip_first<Iters...>, Iters...>; 8210b57cec5SDimitry Andric 8220b57cec5SDimitry Andric bool operator==(const zip_first<Iters...> &other) const { 8230b57cec5SDimitry Andric return std::get<0>(this->iterators) == std::get<0>(other.iterators); 8240b57cec5SDimitry Andric } 8250b57cec5SDimitry Andric 8260b57cec5SDimitry Andric zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {} 8270b57cec5SDimitry Andric }; 8280b57cec5SDimitry Andric 8290b57cec5SDimitry Andric template <typename... Iters> 8300b57cec5SDimitry Andric class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> { 8310b57cec5SDimitry Andric template <size_t... Ns> 8328bcb0991SDimitry Andric bool test(const zip_shortest<Iters...> &other, 8338bcb0991SDimitry Andric std::index_sequence<Ns...>) const { 834*bdd1243dSDimitry Andric return ((std::get<Ns>(this->iterators) != std::get<Ns>(other.iterators)) && 835*bdd1243dSDimitry Andric ...); 8360b57cec5SDimitry Andric } 8370b57cec5SDimitry Andric 8380b57cec5SDimitry Andric public: 8390b57cec5SDimitry Andric using Base = zip_common<zip_shortest<Iters...>, Iters...>; 8400b57cec5SDimitry Andric 8410b57cec5SDimitry Andric zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {} 8420b57cec5SDimitry Andric 8430b57cec5SDimitry Andric bool operator==(const zip_shortest<Iters...> &other) const { 8448bcb0991SDimitry Andric return !test(other, std::index_sequence_for<Iters...>{}); 8450b57cec5SDimitry Andric } 8460b57cec5SDimitry Andric }; 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric template <template <typename...> class ItType, typename... Args> class zippy { 8490b57cec5SDimitry Andric public: 8500b57cec5SDimitry Andric using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>; 8510b57cec5SDimitry Andric using iterator_category = typename iterator::iterator_category; 8520b57cec5SDimitry Andric using value_type = typename iterator::value_type; 8530b57cec5SDimitry Andric using difference_type = typename iterator::difference_type; 8540b57cec5SDimitry Andric using pointer = typename iterator::pointer; 8550b57cec5SDimitry Andric using reference = typename iterator::reference; 8560b57cec5SDimitry Andric 8570b57cec5SDimitry Andric private: 8580b57cec5SDimitry Andric std::tuple<Args...> ts; 8590b57cec5SDimitry Andric 8608bcb0991SDimitry Andric template <size_t... Ns> 8618bcb0991SDimitry Andric iterator begin_impl(std::index_sequence<Ns...>) const { 8620b57cec5SDimitry Andric return iterator(std::begin(std::get<Ns>(ts))...); 8630b57cec5SDimitry Andric } 8648bcb0991SDimitry Andric template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const { 8650b57cec5SDimitry Andric return iterator(std::end(std::get<Ns>(ts))...); 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric 8680b57cec5SDimitry Andric public: 8690b57cec5SDimitry Andric zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} 8700b57cec5SDimitry Andric 8718bcb0991SDimitry Andric iterator begin() const { 8728bcb0991SDimitry Andric return begin_impl(std::index_sequence_for<Args...>{}); 8738bcb0991SDimitry Andric } 8748bcb0991SDimitry Andric iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); } 8750b57cec5SDimitry Andric }; 8760b57cec5SDimitry Andric 8770b57cec5SDimitry Andric } // end namespace detail 8780b57cec5SDimitry Andric 879*bdd1243dSDimitry Andric /// zip iterator for two or more iteratable types. Iteration continues until the 880*bdd1243dSDimitry Andric /// end of the *shortest* iteratee is reached. 8810b57cec5SDimitry Andric template <typename T, typename U, typename... Args> 8820b57cec5SDimitry Andric detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u, 8830b57cec5SDimitry Andric Args &&...args) { 8840b57cec5SDimitry Andric return detail::zippy<detail::zip_shortest, T, U, Args...>( 8850b57cec5SDimitry Andric std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 8860b57cec5SDimitry Andric } 8870b57cec5SDimitry Andric 888*bdd1243dSDimitry Andric /// zip iterator that assumes that all iteratees have the same length. 889*bdd1243dSDimitry Andric /// In builds with assertions on, this assumption is checked before the 890*bdd1243dSDimitry Andric /// iteration starts. 891*bdd1243dSDimitry Andric template <typename T, typename U, typename... Args> 892*bdd1243dSDimitry Andric detail::zippy<detail::zip_first, T, U, Args...> zip_equal(T &&t, U &&u, 893*bdd1243dSDimitry Andric Args &&...args) { 894*bdd1243dSDimitry Andric assert(all_equal({std::distance(adl_begin(t), adl_end(t)), 895*bdd1243dSDimitry Andric std::distance(adl_begin(u), adl_end(u)), 896*bdd1243dSDimitry Andric std::distance(adl_begin(args), adl_end(args))...}) && 897*bdd1243dSDimitry Andric "Iteratees do not have equal length"); 898*bdd1243dSDimitry Andric return detail::zippy<detail::zip_first, T, U, Args...>( 899*bdd1243dSDimitry Andric std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 900*bdd1243dSDimitry Andric } 901*bdd1243dSDimitry Andric 9020b57cec5SDimitry Andric /// zip iterator that, for the sake of efficiency, assumes the first iteratee to 903*bdd1243dSDimitry Andric /// be the shortest. Iteration continues until the end of the first iteratee is 904*bdd1243dSDimitry Andric /// reached. In builds with assertions on, we check that the assumption about 905*bdd1243dSDimitry Andric /// the first iteratee being the shortest holds. 9060b57cec5SDimitry Andric template <typename T, typename U, typename... Args> 9070b57cec5SDimitry Andric detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u, 9080b57cec5SDimitry Andric Args &&...args) { 909*bdd1243dSDimitry Andric assert(std::distance(adl_begin(t), adl_end(t)) <= 910*bdd1243dSDimitry Andric std::min({std::distance(adl_begin(u), adl_end(u)), 911*bdd1243dSDimitry Andric std::distance(adl_begin(args), adl_end(args))...}) && 912*bdd1243dSDimitry Andric "First iteratee is not the shortest"); 913*bdd1243dSDimitry Andric 9140b57cec5SDimitry Andric return detail::zippy<detail::zip_first, T, U, Args...>( 9150b57cec5SDimitry Andric std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 9160b57cec5SDimitry Andric } 9170b57cec5SDimitry Andric 9180b57cec5SDimitry Andric namespace detail { 9190b57cec5SDimitry Andric template <typename Iter> 9205ffd83dbSDimitry Andric Iter next_or_end(const Iter &I, const Iter &End) { 9210b57cec5SDimitry Andric if (I == End) 9220b57cec5SDimitry Andric return End; 9230b57cec5SDimitry Andric return std::next(I); 9240b57cec5SDimitry Andric } 9250b57cec5SDimitry Andric 9260b57cec5SDimitry Andric template <typename Iter> 927*bdd1243dSDimitry Andric auto deref_or_none(const Iter &I, const Iter &End) -> std::optional< 9285ffd83dbSDimitry Andric std::remove_const_t<std::remove_reference_t<decltype(*I)>>> { 9290b57cec5SDimitry Andric if (I == End) 930*bdd1243dSDimitry Andric return std::nullopt; 9310b57cec5SDimitry Andric return *I; 9320b57cec5SDimitry Andric } 9330b57cec5SDimitry Andric 9340b57cec5SDimitry Andric template <typename Iter> struct ZipLongestItemType { 935*bdd1243dSDimitry Andric using type = std::optional<std::remove_const_t< 936*bdd1243dSDimitry Andric std::remove_reference_t<decltype(*std::declval<Iter>())>>>; 9370b57cec5SDimitry Andric }; 9380b57cec5SDimitry Andric 9390b57cec5SDimitry Andric template <typename... Iters> struct ZipLongestTupleType { 9400b57cec5SDimitry Andric using type = std::tuple<typename ZipLongestItemType<Iters>::type...>; 9410b57cec5SDimitry Andric }; 9420b57cec5SDimitry Andric 9430b57cec5SDimitry Andric template <typename... Iters> 9440b57cec5SDimitry Andric class zip_longest_iterator 9450b57cec5SDimitry Andric : public iterator_facade_base< 9460b57cec5SDimitry Andric zip_longest_iterator<Iters...>, 947*bdd1243dSDimitry Andric std::common_type_t< 9480b57cec5SDimitry Andric std::forward_iterator_tag, 949*bdd1243dSDimitry Andric typename std::iterator_traits<Iters>::iterator_category...>, 9500b57cec5SDimitry Andric typename ZipLongestTupleType<Iters...>::type, 951*bdd1243dSDimitry Andric typename std::iterator_traits< 952*bdd1243dSDimitry Andric std::tuple_element_t<0, std::tuple<Iters...>>>::difference_type, 9530b57cec5SDimitry Andric typename ZipLongestTupleType<Iters...>::type *, 9540b57cec5SDimitry Andric typename ZipLongestTupleType<Iters...>::type> { 9550b57cec5SDimitry Andric public: 9560b57cec5SDimitry Andric using value_type = typename ZipLongestTupleType<Iters...>::type; 9570b57cec5SDimitry Andric 9580b57cec5SDimitry Andric private: 9590b57cec5SDimitry Andric std::tuple<Iters...> iterators; 9600b57cec5SDimitry Andric std::tuple<Iters...> end_iterators; 9610b57cec5SDimitry Andric 9620b57cec5SDimitry Andric template <size_t... Ns> 9630b57cec5SDimitry Andric bool test(const zip_longest_iterator<Iters...> &other, 9648bcb0991SDimitry Andric std::index_sequence<Ns...>) const { 965*bdd1243dSDimitry Andric return ((std::get<Ns>(this->iterators) != std::get<Ns>(other.iterators)) || 966*bdd1243dSDimitry Andric ...); 9670b57cec5SDimitry Andric } 9680b57cec5SDimitry Andric 9698bcb0991SDimitry Andric template <size_t... Ns> value_type deref(std::index_sequence<Ns...>) const { 9700b57cec5SDimitry Andric return value_type( 9710b57cec5SDimitry Andric deref_or_none(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...); 9720b57cec5SDimitry Andric } 9730b57cec5SDimitry Andric 9740b57cec5SDimitry Andric template <size_t... Ns> 9758bcb0991SDimitry Andric decltype(iterators) tup_inc(std::index_sequence<Ns...>) const { 9760b57cec5SDimitry Andric return std::tuple<Iters...>( 9770b57cec5SDimitry Andric next_or_end(std::get<Ns>(iterators), std::get<Ns>(end_iterators))...); 9780b57cec5SDimitry Andric } 9790b57cec5SDimitry Andric 9800b57cec5SDimitry Andric public: 9810b57cec5SDimitry Andric zip_longest_iterator(std::pair<Iters &&, Iters &&>... ts) 9820b57cec5SDimitry Andric : iterators(std::forward<Iters>(ts.first)...), 9830b57cec5SDimitry Andric end_iterators(std::forward<Iters>(ts.second)...) {} 9840b57cec5SDimitry Andric 9858bcb0991SDimitry Andric value_type operator*() const { 9868bcb0991SDimitry Andric return deref(std::index_sequence_for<Iters...>{}); 9878bcb0991SDimitry Andric } 9880b57cec5SDimitry Andric 9890b57cec5SDimitry Andric zip_longest_iterator<Iters...> &operator++() { 9908bcb0991SDimitry Andric iterators = tup_inc(std::index_sequence_for<Iters...>{}); 9910b57cec5SDimitry Andric return *this; 9920b57cec5SDimitry Andric } 9930b57cec5SDimitry Andric 9940b57cec5SDimitry Andric bool operator==(const zip_longest_iterator<Iters...> &other) const { 9958bcb0991SDimitry Andric return !test(other, std::index_sequence_for<Iters...>{}); 9960b57cec5SDimitry Andric } 9970b57cec5SDimitry Andric }; 9980b57cec5SDimitry Andric 9990b57cec5SDimitry Andric template <typename... Args> class zip_longest_range { 10000b57cec5SDimitry Andric public: 10010b57cec5SDimitry Andric using iterator = 10020b57cec5SDimitry Andric zip_longest_iterator<decltype(adl_begin(std::declval<Args>()))...>; 10030b57cec5SDimitry Andric using iterator_category = typename iterator::iterator_category; 10040b57cec5SDimitry Andric using value_type = typename iterator::value_type; 10050b57cec5SDimitry Andric using difference_type = typename iterator::difference_type; 10060b57cec5SDimitry Andric using pointer = typename iterator::pointer; 10070b57cec5SDimitry Andric using reference = typename iterator::reference; 10080b57cec5SDimitry Andric 10090b57cec5SDimitry Andric private: 10100b57cec5SDimitry Andric std::tuple<Args...> ts; 10110b57cec5SDimitry Andric 10128bcb0991SDimitry Andric template <size_t... Ns> 10138bcb0991SDimitry Andric iterator begin_impl(std::index_sequence<Ns...>) const { 10140b57cec5SDimitry Andric return iterator(std::make_pair(adl_begin(std::get<Ns>(ts)), 10150b57cec5SDimitry Andric adl_end(std::get<Ns>(ts)))...); 10160b57cec5SDimitry Andric } 10170b57cec5SDimitry Andric 10188bcb0991SDimitry Andric template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const { 10190b57cec5SDimitry Andric return iterator(std::make_pair(adl_end(std::get<Ns>(ts)), 10200b57cec5SDimitry Andric adl_end(std::get<Ns>(ts)))...); 10210b57cec5SDimitry Andric } 10220b57cec5SDimitry Andric 10230b57cec5SDimitry Andric public: 10240b57cec5SDimitry Andric zip_longest_range(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} 10250b57cec5SDimitry Andric 10268bcb0991SDimitry Andric iterator begin() const { 10278bcb0991SDimitry Andric return begin_impl(std::index_sequence_for<Args...>{}); 10288bcb0991SDimitry Andric } 10298bcb0991SDimitry Andric iterator end() const { return end_impl(std::index_sequence_for<Args...>{}); } 10300b57cec5SDimitry Andric }; 10310b57cec5SDimitry Andric } // namespace detail 10320b57cec5SDimitry Andric 10330b57cec5SDimitry Andric /// Iterate over two or more iterators at the same time. Iteration continues 1034*bdd1243dSDimitry Andric /// until all iterators reach the end. The std::optional only contains a value 10350b57cec5SDimitry Andric /// if the iterator has not reached the end. 10360b57cec5SDimitry Andric template <typename T, typename U, typename... Args> 10370b57cec5SDimitry Andric detail::zip_longest_range<T, U, Args...> zip_longest(T &&t, U &&u, 10380b57cec5SDimitry Andric Args &&... args) { 10390b57cec5SDimitry Andric return detail::zip_longest_range<T, U, Args...>( 10400b57cec5SDimitry Andric std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); 10410b57cec5SDimitry Andric } 10420b57cec5SDimitry Andric 10430b57cec5SDimitry Andric /// Iterator wrapper that concatenates sequences together. 10440b57cec5SDimitry Andric /// 10450b57cec5SDimitry Andric /// This can concatenate different iterators, even with different types, into 10460b57cec5SDimitry Andric /// a single iterator provided the value types of all the concatenated 10470b57cec5SDimitry Andric /// iterators expose `reference` and `pointer` types that can be converted to 10480b57cec5SDimitry Andric /// `ValueT &` and `ValueT *` respectively. It doesn't support more 10490b57cec5SDimitry Andric /// interesting/customized pointer or reference types. 10500b57cec5SDimitry Andric /// 10510b57cec5SDimitry Andric /// Currently this only supports forward or higher iterator categories as 10520b57cec5SDimitry Andric /// inputs and always exposes a forward iterator interface. 10530b57cec5SDimitry Andric template <typename ValueT, typename... IterTs> 10540b57cec5SDimitry Andric class concat_iterator 10550b57cec5SDimitry Andric : public iterator_facade_base<concat_iterator<ValueT, IterTs...>, 10560b57cec5SDimitry Andric std::forward_iterator_tag, ValueT> { 10570b57cec5SDimitry Andric using BaseT = typename concat_iterator::iterator_facade_base; 10580b57cec5SDimitry Andric 10590b57cec5SDimitry Andric /// We store both the current and end iterators for each concatenated 10600b57cec5SDimitry Andric /// sequence in a tuple of pairs. 10610b57cec5SDimitry Andric /// 10620b57cec5SDimitry Andric /// Note that something like iterator_range seems nice at first here, but the 10630b57cec5SDimitry Andric /// range properties are of little benefit and end up getting in the way 10640b57cec5SDimitry Andric /// because we need to do mutation on the current iterators. 10650b57cec5SDimitry Andric std::tuple<IterTs...> Begins; 10660b57cec5SDimitry Andric std::tuple<IterTs...> Ends; 10670b57cec5SDimitry Andric 10680b57cec5SDimitry Andric /// Attempts to increment a specific iterator. 10690b57cec5SDimitry Andric /// 10700b57cec5SDimitry Andric /// Returns true if it was able to increment the iterator. Returns false if 10710b57cec5SDimitry Andric /// the iterator is already at the end iterator. 10720b57cec5SDimitry Andric template <size_t Index> bool incrementHelper() { 10730b57cec5SDimitry Andric auto &Begin = std::get<Index>(Begins); 10740b57cec5SDimitry Andric auto &End = std::get<Index>(Ends); 10750b57cec5SDimitry Andric if (Begin == End) 10760b57cec5SDimitry Andric return false; 10770b57cec5SDimitry Andric 10780b57cec5SDimitry Andric ++Begin; 10790b57cec5SDimitry Andric return true; 10800b57cec5SDimitry Andric } 10810b57cec5SDimitry Andric 10820b57cec5SDimitry Andric /// Increments the first non-end iterator. 10830b57cec5SDimitry Andric /// 10840b57cec5SDimitry Andric /// It is an error to call this with all iterators at the end. 10858bcb0991SDimitry Andric template <size_t... Ns> void increment(std::index_sequence<Ns...>) { 10860b57cec5SDimitry Andric // Build a sequence of functions to increment each iterator if possible. 10870b57cec5SDimitry Andric bool (concat_iterator::*IncrementHelperFns[])() = { 10880b57cec5SDimitry Andric &concat_iterator::incrementHelper<Ns>...}; 10890b57cec5SDimitry Andric 10900b57cec5SDimitry Andric // Loop over them, and stop as soon as we succeed at incrementing one. 10910b57cec5SDimitry Andric for (auto &IncrementHelperFn : IncrementHelperFns) 10920b57cec5SDimitry Andric if ((this->*IncrementHelperFn)()) 10930b57cec5SDimitry Andric return; 10940b57cec5SDimitry Andric 10950b57cec5SDimitry Andric llvm_unreachable("Attempted to increment an end concat iterator!"); 10960b57cec5SDimitry Andric } 10970b57cec5SDimitry Andric 10980b57cec5SDimitry Andric /// Returns null if the specified iterator is at the end. Otherwise, 10990b57cec5SDimitry Andric /// dereferences the iterator and returns the address of the resulting 11000b57cec5SDimitry Andric /// reference. 11010b57cec5SDimitry Andric template <size_t Index> ValueT *getHelper() const { 11020b57cec5SDimitry Andric auto &Begin = std::get<Index>(Begins); 11030b57cec5SDimitry Andric auto &End = std::get<Index>(Ends); 11040b57cec5SDimitry Andric if (Begin == End) 11050b57cec5SDimitry Andric return nullptr; 11060b57cec5SDimitry Andric 11070b57cec5SDimitry Andric return &*Begin; 11080b57cec5SDimitry Andric } 11090b57cec5SDimitry Andric 11100b57cec5SDimitry Andric /// Finds the first non-end iterator, dereferences, and returns the resulting 11110b57cec5SDimitry Andric /// reference. 11120b57cec5SDimitry Andric /// 11130b57cec5SDimitry Andric /// It is an error to call this with all iterators at the end. 11148bcb0991SDimitry Andric template <size_t... Ns> ValueT &get(std::index_sequence<Ns...>) const { 11150b57cec5SDimitry Andric // Build a sequence of functions to get from iterator if possible. 11160b57cec5SDimitry Andric ValueT *(concat_iterator::*GetHelperFns[])() const = { 11170b57cec5SDimitry Andric &concat_iterator::getHelper<Ns>...}; 11180b57cec5SDimitry Andric 11190b57cec5SDimitry Andric // Loop over them, and return the first result we find. 11200b57cec5SDimitry Andric for (auto &GetHelperFn : GetHelperFns) 11210b57cec5SDimitry Andric if (ValueT *P = (this->*GetHelperFn)()) 11220b57cec5SDimitry Andric return *P; 11230b57cec5SDimitry Andric 11240b57cec5SDimitry Andric llvm_unreachable("Attempted to get a pointer from an end concat iterator!"); 11250b57cec5SDimitry Andric } 11260b57cec5SDimitry Andric 11270b57cec5SDimitry Andric public: 11285ffd83dbSDimitry Andric /// Constructs an iterator from a sequence of ranges. 11290b57cec5SDimitry Andric /// 11300b57cec5SDimitry Andric /// We need the full range to know how to switch between each of the 11310b57cec5SDimitry Andric /// iterators. 11320b57cec5SDimitry Andric template <typename... RangeTs> 11330b57cec5SDimitry Andric explicit concat_iterator(RangeTs &&... Ranges) 11340b57cec5SDimitry Andric : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {} 11350b57cec5SDimitry Andric 11360b57cec5SDimitry Andric using BaseT::operator++; 11370b57cec5SDimitry Andric 11380b57cec5SDimitry Andric concat_iterator &operator++() { 11398bcb0991SDimitry Andric increment(std::index_sequence_for<IterTs...>()); 11400b57cec5SDimitry Andric return *this; 11410b57cec5SDimitry Andric } 11420b57cec5SDimitry Andric 11438bcb0991SDimitry Andric ValueT &operator*() const { 11448bcb0991SDimitry Andric return get(std::index_sequence_for<IterTs...>()); 11458bcb0991SDimitry Andric } 11460b57cec5SDimitry Andric 11470b57cec5SDimitry Andric bool operator==(const concat_iterator &RHS) const { 11480b57cec5SDimitry Andric return Begins == RHS.Begins && Ends == RHS.Ends; 11490b57cec5SDimitry Andric } 11500b57cec5SDimitry Andric }; 11510b57cec5SDimitry Andric 11520b57cec5SDimitry Andric namespace detail { 11530b57cec5SDimitry Andric 11540b57cec5SDimitry Andric /// Helper to store a sequence of ranges being concatenated and access them. 11550b57cec5SDimitry Andric /// 11560b57cec5SDimitry Andric /// This is designed to facilitate providing actual storage when temporaries 11570b57cec5SDimitry Andric /// are passed into the constructor such that we can use it as part of range 11580b57cec5SDimitry Andric /// based for loops. 11590b57cec5SDimitry Andric template <typename ValueT, typename... RangeTs> class concat_range { 11600b57cec5SDimitry Andric public: 11610b57cec5SDimitry Andric using iterator = 11620b57cec5SDimitry Andric concat_iterator<ValueT, 11630b57cec5SDimitry Andric decltype(std::begin(std::declval<RangeTs &>()))...>; 11640b57cec5SDimitry Andric 11650b57cec5SDimitry Andric private: 11660b57cec5SDimitry Andric std::tuple<RangeTs...> Ranges; 11670b57cec5SDimitry Andric 11684824e7fdSDimitry Andric template <size_t... Ns> 11694824e7fdSDimitry Andric iterator begin_impl(std::index_sequence<Ns...>) { 11704824e7fdSDimitry Andric return iterator(std::get<Ns>(Ranges)...); 11714824e7fdSDimitry Andric } 11724824e7fdSDimitry Andric template <size_t... Ns> 11734824e7fdSDimitry Andric iterator begin_impl(std::index_sequence<Ns...>) const { 11740b57cec5SDimitry Andric return iterator(std::get<Ns>(Ranges)...); 11750b57cec5SDimitry Andric } 11768bcb0991SDimitry Andric template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) { 11770b57cec5SDimitry Andric return iterator(make_range(std::end(std::get<Ns>(Ranges)), 11780b57cec5SDimitry Andric std::end(std::get<Ns>(Ranges)))...); 11790b57cec5SDimitry Andric } 11804824e7fdSDimitry Andric template <size_t... Ns> iterator end_impl(std::index_sequence<Ns...>) const { 11814824e7fdSDimitry Andric return iterator(make_range(std::end(std::get<Ns>(Ranges)), 11824824e7fdSDimitry Andric std::end(std::get<Ns>(Ranges)))...); 11834824e7fdSDimitry Andric } 11840b57cec5SDimitry Andric 11850b57cec5SDimitry Andric public: 11860b57cec5SDimitry Andric concat_range(RangeTs &&... Ranges) 11870b57cec5SDimitry Andric : Ranges(std::forward<RangeTs>(Ranges)...) {} 11880b57cec5SDimitry Andric 11894824e7fdSDimitry Andric iterator begin() { 11904824e7fdSDimitry Andric return begin_impl(std::index_sequence_for<RangeTs...>{}); 11914824e7fdSDimitry Andric } 11924824e7fdSDimitry Andric iterator begin() const { 11934824e7fdSDimitry Andric return begin_impl(std::index_sequence_for<RangeTs...>{}); 11944824e7fdSDimitry Andric } 11954824e7fdSDimitry Andric iterator end() { 11964824e7fdSDimitry Andric return end_impl(std::index_sequence_for<RangeTs...>{}); 11974824e7fdSDimitry Andric } 11984824e7fdSDimitry Andric iterator end() const { 11994824e7fdSDimitry Andric return end_impl(std::index_sequence_for<RangeTs...>{}); 12004824e7fdSDimitry Andric } 12010b57cec5SDimitry Andric }; 12020b57cec5SDimitry Andric 12030b57cec5SDimitry Andric } // end namespace detail 12040b57cec5SDimitry Andric 12050b57cec5SDimitry Andric /// Concatenated range across two or more ranges. 12060b57cec5SDimitry Andric /// 12070b57cec5SDimitry Andric /// The desired value type must be explicitly specified. 12080b57cec5SDimitry Andric template <typename ValueT, typename... RangeTs> 12090b57cec5SDimitry Andric detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) { 12100b57cec5SDimitry Andric static_assert(sizeof...(RangeTs) > 1, 12110b57cec5SDimitry Andric "Need more than one range to concatenate!"); 12120b57cec5SDimitry Andric return detail::concat_range<ValueT, RangeTs...>( 12130b57cec5SDimitry Andric std::forward<RangeTs>(Ranges)...); 12140b57cec5SDimitry Andric } 12150b57cec5SDimitry Andric 12165ffd83dbSDimitry Andric /// A utility class used to implement an iterator that contains some base object 12175ffd83dbSDimitry Andric /// and an index. The iterator moves the index but keeps the base constant. 12185ffd83dbSDimitry Andric template <typename DerivedT, typename BaseT, typename T, 12195ffd83dbSDimitry Andric typename PointerT = T *, typename ReferenceT = T &> 12205ffd83dbSDimitry Andric class indexed_accessor_iterator 12215ffd83dbSDimitry Andric : public llvm::iterator_facade_base<DerivedT, 12225ffd83dbSDimitry Andric std::random_access_iterator_tag, T, 12235ffd83dbSDimitry Andric std::ptrdiff_t, PointerT, ReferenceT> { 12245ffd83dbSDimitry Andric public: 12255ffd83dbSDimitry Andric ptrdiff_t operator-(const indexed_accessor_iterator &rhs) const { 12265ffd83dbSDimitry Andric assert(base == rhs.base && "incompatible iterators"); 12275ffd83dbSDimitry Andric return index - rhs.index; 12285ffd83dbSDimitry Andric } 12295ffd83dbSDimitry Andric bool operator==(const indexed_accessor_iterator &rhs) const { 12305ffd83dbSDimitry Andric return base == rhs.base && index == rhs.index; 12315ffd83dbSDimitry Andric } 12325ffd83dbSDimitry Andric bool operator<(const indexed_accessor_iterator &rhs) const { 12335ffd83dbSDimitry Andric assert(base == rhs.base && "incompatible iterators"); 12345ffd83dbSDimitry Andric return index < rhs.index; 12355ffd83dbSDimitry Andric } 12365ffd83dbSDimitry Andric 12375ffd83dbSDimitry Andric DerivedT &operator+=(ptrdiff_t offset) { 12385ffd83dbSDimitry Andric this->index += offset; 12395ffd83dbSDimitry Andric return static_cast<DerivedT &>(*this); 12405ffd83dbSDimitry Andric } 12415ffd83dbSDimitry Andric DerivedT &operator-=(ptrdiff_t offset) { 12425ffd83dbSDimitry Andric this->index -= offset; 12435ffd83dbSDimitry Andric return static_cast<DerivedT &>(*this); 12445ffd83dbSDimitry Andric } 12455ffd83dbSDimitry Andric 12465ffd83dbSDimitry Andric /// Returns the current index of the iterator. 12475ffd83dbSDimitry Andric ptrdiff_t getIndex() const { return index; } 12485ffd83dbSDimitry Andric 12495ffd83dbSDimitry Andric /// Returns the current base of the iterator. 12505ffd83dbSDimitry Andric const BaseT &getBase() const { return base; } 12515ffd83dbSDimitry Andric 12525ffd83dbSDimitry Andric protected: 12535ffd83dbSDimitry Andric indexed_accessor_iterator(BaseT base, ptrdiff_t index) 12545ffd83dbSDimitry Andric : base(base), index(index) {} 12555ffd83dbSDimitry Andric BaseT base; 12565ffd83dbSDimitry Andric ptrdiff_t index; 12575ffd83dbSDimitry Andric }; 12585ffd83dbSDimitry Andric 12595ffd83dbSDimitry Andric namespace detail { 12605ffd83dbSDimitry Andric /// The class represents the base of a range of indexed_accessor_iterators. It 12615ffd83dbSDimitry Andric /// provides support for many different range functionalities, e.g. 12625ffd83dbSDimitry Andric /// drop_front/slice/etc.. Derived range classes must implement the following 12635ffd83dbSDimitry Andric /// static methods: 12645ffd83dbSDimitry Andric /// * ReferenceT dereference_iterator(const BaseT &base, ptrdiff_t index) 12655ffd83dbSDimitry Andric /// - Dereference an iterator pointing to the base object at the given 12665ffd83dbSDimitry Andric /// index. 12675ffd83dbSDimitry Andric /// * BaseT offset_base(const BaseT &base, ptrdiff_t index) 12685ffd83dbSDimitry Andric /// - Return a new base that is offset from the provide base by 'index' 12695ffd83dbSDimitry Andric /// elements. 12705ffd83dbSDimitry Andric template <typename DerivedT, typename BaseT, typename T, 12715ffd83dbSDimitry Andric typename PointerT = T *, typename ReferenceT = T &> 12725ffd83dbSDimitry Andric class indexed_accessor_range_base { 12735ffd83dbSDimitry Andric public: 1274349cc55cSDimitry Andric using RangeBaseT = indexed_accessor_range_base; 12755ffd83dbSDimitry Andric 12765ffd83dbSDimitry Andric /// An iterator element of this range. 12775ffd83dbSDimitry Andric class iterator : public indexed_accessor_iterator<iterator, BaseT, T, 12785ffd83dbSDimitry Andric PointerT, ReferenceT> { 12795ffd83dbSDimitry Andric public: 12805ffd83dbSDimitry Andric // Index into this iterator, invoking a static method on the derived type. 12815ffd83dbSDimitry Andric ReferenceT operator*() const { 12825ffd83dbSDimitry Andric return DerivedT::dereference_iterator(this->getBase(), this->getIndex()); 12835ffd83dbSDimitry Andric } 12845ffd83dbSDimitry Andric 12855ffd83dbSDimitry Andric private: 12865ffd83dbSDimitry Andric iterator(BaseT owner, ptrdiff_t curIndex) 1287349cc55cSDimitry Andric : iterator::indexed_accessor_iterator(owner, curIndex) {} 12885ffd83dbSDimitry Andric 12895ffd83dbSDimitry Andric /// Allow access to the constructor. 12905ffd83dbSDimitry Andric friend indexed_accessor_range_base<DerivedT, BaseT, T, PointerT, 12915ffd83dbSDimitry Andric ReferenceT>; 12925ffd83dbSDimitry Andric }; 12935ffd83dbSDimitry Andric 12945ffd83dbSDimitry Andric indexed_accessor_range_base(iterator begin, iterator end) 12955ffd83dbSDimitry Andric : base(offset_base(begin.getBase(), begin.getIndex())), 12965ffd83dbSDimitry Andric count(end.getIndex() - begin.getIndex()) {} 12975ffd83dbSDimitry Andric indexed_accessor_range_base(const iterator_range<iterator> &range) 12985ffd83dbSDimitry Andric : indexed_accessor_range_base(range.begin(), range.end()) {} 12995ffd83dbSDimitry Andric indexed_accessor_range_base(BaseT base, ptrdiff_t count) 13005ffd83dbSDimitry Andric : base(base), count(count) {} 13015ffd83dbSDimitry Andric 13025ffd83dbSDimitry Andric iterator begin() const { return iterator(base, 0); } 13035ffd83dbSDimitry Andric iterator end() const { return iterator(base, count); } 1304fe6060f1SDimitry Andric ReferenceT operator[](size_t Index) const { 1305fe6060f1SDimitry Andric assert(Index < size() && "invalid index for value range"); 1306fe6060f1SDimitry Andric return DerivedT::dereference_iterator(base, static_cast<ptrdiff_t>(Index)); 13075ffd83dbSDimitry Andric } 13085ffd83dbSDimitry Andric ReferenceT front() const { 13095ffd83dbSDimitry Andric assert(!empty() && "expected non-empty range"); 13105ffd83dbSDimitry Andric return (*this)[0]; 13115ffd83dbSDimitry Andric } 13125ffd83dbSDimitry Andric ReferenceT back() const { 13135ffd83dbSDimitry Andric assert(!empty() && "expected non-empty range"); 13145ffd83dbSDimitry Andric return (*this)[size() - 1]; 13155ffd83dbSDimitry Andric } 13165ffd83dbSDimitry Andric 13175ffd83dbSDimitry Andric /// Compare this range with another. 131881ad6265SDimitry Andric template <typename OtherT> 131981ad6265SDimitry Andric friend bool operator==(const indexed_accessor_range_base &lhs, 132081ad6265SDimitry Andric const OtherT &rhs) { 132181ad6265SDimitry Andric return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); 13225ffd83dbSDimitry Andric } 132381ad6265SDimitry Andric template <typename OtherT> 132481ad6265SDimitry Andric friend bool operator!=(const indexed_accessor_range_base &lhs, 132581ad6265SDimitry Andric const OtherT &rhs) { 132681ad6265SDimitry Andric return !(lhs == rhs); 13275ffd83dbSDimitry Andric } 13285ffd83dbSDimitry Andric 13295ffd83dbSDimitry Andric /// Return the size of this range. 13305ffd83dbSDimitry Andric size_t size() const { return count; } 13315ffd83dbSDimitry Andric 13325ffd83dbSDimitry Andric /// Return if the range is empty. 13335ffd83dbSDimitry Andric bool empty() const { return size() == 0; } 13345ffd83dbSDimitry Andric 13355ffd83dbSDimitry Andric /// Drop the first N elements, and keep M elements. 13365ffd83dbSDimitry Andric DerivedT slice(size_t n, size_t m) const { 13375ffd83dbSDimitry Andric assert(n + m <= size() && "invalid size specifiers"); 13385ffd83dbSDimitry Andric return DerivedT(offset_base(base, n), m); 13395ffd83dbSDimitry Andric } 13405ffd83dbSDimitry Andric 13415ffd83dbSDimitry Andric /// Drop the first n elements. 13425ffd83dbSDimitry Andric DerivedT drop_front(size_t n = 1) const { 13435ffd83dbSDimitry Andric assert(size() >= n && "Dropping more elements than exist"); 13445ffd83dbSDimitry Andric return slice(n, size() - n); 13455ffd83dbSDimitry Andric } 13465ffd83dbSDimitry Andric /// Drop the last n elements. 13475ffd83dbSDimitry Andric DerivedT drop_back(size_t n = 1) const { 13485ffd83dbSDimitry Andric assert(size() >= n && "Dropping more elements than exist"); 13495ffd83dbSDimitry Andric return DerivedT(base, size() - n); 13505ffd83dbSDimitry Andric } 13515ffd83dbSDimitry Andric 13525ffd83dbSDimitry Andric /// Take the first n elements. 13535ffd83dbSDimitry Andric DerivedT take_front(size_t n = 1) const { 13545ffd83dbSDimitry Andric return n < size() ? drop_back(size() - n) 13555ffd83dbSDimitry Andric : static_cast<const DerivedT &>(*this); 13565ffd83dbSDimitry Andric } 13575ffd83dbSDimitry Andric 13585ffd83dbSDimitry Andric /// Take the last n elements. 13595ffd83dbSDimitry Andric DerivedT take_back(size_t n = 1) const { 13605ffd83dbSDimitry Andric return n < size() ? drop_front(size() - n) 13615ffd83dbSDimitry Andric : static_cast<const DerivedT &>(*this); 13625ffd83dbSDimitry Andric } 13635ffd83dbSDimitry Andric 13645ffd83dbSDimitry Andric /// Allow conversion to any type accepting an iterator_range. 13655ffd83dbSDimitry Andric template <typename RangeT, typename = std::enable_if_t<std::is_constructible< 13665ffd83dbSDimitry Andric RangeT, iterator_range<iterator>>::value>> 13675ffd83dbSDimitry Andric operator RangeT() const { 13685ffd83dbSDimitry Andric return RangeT(iterator_range<iterator>(*this)); 13695ffd83dbSDimitry Andric } 13705ffd83dbSDimitry Andric 13715ffd83dbSDimitry Andric /// Returns the base of this range. 13725ffd83dbSDimitry Andric const BaseT &getBase() const { return base; } 13735ffd83dbSDimitry Andric 13745ffd83dbSDimitry Andric private: 13755ffd83dbSDimitry Andric /// Offset the given base by the given amount. 13765ffd83dbSDimitry Andric static BaseT offset_base(const BaseT &base, size_t n) { 13775ffd83dbSDimitry Andric return n == 0 ? base : DerivedT::offset_base(base, n); 13785ffd83dbSDimitry Andric } 13795ffd83dbSDimitry Andric 13805ffd83dbSDimitry Andric protected: 13815ffd83dbSDimitry Andric indexed_accessor_range_base(const indexed_accessor_range_base &) = default; 13825ffd83dbSDimitry Andric indexed_accessor_range_base(indexed_accessor_range_base &&) = default; 13835ffd83dbSDimitry Andric indexed_accessor_range_base & 13845ffd83dbSDimitry Andric operator=(const indexed_accessor_range_base &) = default; 13855ffd83dbSDimitry Andric 13865ffd83dbSDimitry Andric /// The base that owns the provided range of values. 13875ffd83dbSDimitry Andric BaseT base; 13885ffd83dbSDimitry Andric /// The size from the owning range. 13895ffd83dbSDimitry Andric ptrdiff_t count; 13905ffd83dbSDimitry Andric }; 13915ffd83dbSDimitry Andric } // end namespace detail 13925ffd83dbSDimitry Andric 13935ffd83dbSDimitry Andric /// This class provides an implementation of a range of 13945ffd83dbSDimitry Andric /// indexed_accessor_iterators where the base is not indexable. Ranges with 13955ffd83dbSDimitry Andric /// bases that are offsetable should derive from indexed_accessor_range_base 13965ffd83dbSDimitry Andric /// instead. Derived range classes are expected to implement the following 13975ffd83dbSDimitry Andric /// static method: 13985ffd83dbSDimitry Andric /// * ReferenceT dereference(const BaseT &base, ptrdiff_t index) 13995ffd83dbSDimitry Andric /// - Dereference an iterator pointing to a parent base at the given index. 14005ffd83dbSDimitry Andric template <typename DerivedT, typename BaseT, typename T, 14015ffd83dbSDimitry Andric typename PointerT = T *, typename ReferenceT = T &> 14025ffd83dbSDimitry Andric class indexed_accessor_range 14035ffd83dbSDimitry Andric : public detail::indexed_accessor_range_base< 14045ffd83dbSDimitry Andric DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT> { 14055ffd83dbSDimitry Andric public: 14065ffd83dbSDimitry Andric indexed_accessor_range(BaseT base, ptrdiff_t startIndex, ptrdiff_t count) 14075ffd83dbSDimitry Andric : detail::indexed_accessor_range_base< 14085ffd83dbSDimitry Andric DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, ReferenceT>( 14095ffd83dbSDimitry Andric std::make_pair(base, startIndex), count) {} 14105ffd83dbSDimitry Andric using detail::indexed_accessor_range_base< 14115ffd83dbSDimitry Andric DerivedT, std::pair<BaseT, ptrdiff_t>, T, PointerT, 14125ffd83dbSDimitry Andric ReferenceT>::indexed_accessor_range_base; 14135ffd83dbSDimitry Andric 14145ffd83dbSDimitry Andric /// Returns the current base of the range. 14155ffd83dbSDimitry Andric const BaseT &getBase() const { return this->base.first; } 14165ffd83dbSDimitry Andric 14175ffd83dbSDimitry Andric /// Returns the current start index of the range. 14185ffd83dbSDimitry Andric ptrdiff_t getStartIndex() const { return this->base.second; } 14195ffd83dbSDimitry Andric 14205ffd83dbSDimitry Andric /// See `detail::indexed_accessor_range_base` for details. 14215ffd83dbSDimitry Andric static std::pair<BaseT, ptrdiff_t> 14225ffd83dbSDimitry Andric offset_base(const std::pair<BaseT, ptrdiff_t> &base, ptrdiff_t index) { 14235ffd83dbSDimitry Andric // We encode the internal base as a pair of the derived base and a start 14245ffd83dbSDimitry Andric // index into the derived base. 14255ffd83dbSDimitry Andric return std::make_pair(base.first, base.second + index); 14265ffd83dbSDimitry Andric } 14275ffd83dbSDimitry Andric /// See `detail::indexed_accessor_range_base` for details. 14285ffd83dbSDimitry Andric static ReferenceT 14295ffd83dbSDimitry Andric dereference_iterator(const std::pair<BaseT, ptrdiff_t> &base, 14305ffd83dbSDimitry Andric ptrdiff_t index) { 14315ffd83dbSDimitry Andric return DerivedT::dereference(base.first, base.second + index); 14325ffd83dbSDimitry Andric } 14335ffd83dbSDimitry Andric }; 14345ffd83dbSDimitry Andric 1435349cc55cSDimitry Andric namespace detail { 1436349cc55cSDimitry Andric /// Return a reference to the first or second member of a reference. Otherwise, 1437349cc55cSDimitry Andric /// return a copy of the member of a temporary. 1438349cc55cSDimitry Andric /// 1439349cc55cSDimitry Andric /// When passing a range whose iterators return values instead of references, 1440349cc55cSDimitry Andric /// the reference must be dropped from `decltype((elt.first))`, which will 1441349cc55cSDimitry Andric /// always be a reference, to avoid returning a reference to a temporary. 1442349cc55cSDimitry Andric template <typename EltTy, typename FirstTy> class first_or_second_type { 1443349cc55cSDimitry Andric public: 1444*bdd1243dSDimitry Andric using type = std::conditional_t<std::is_reference<EltTy>::value, FirstTy, 1445349cc55cSDimitry Andric std::remove_reference_t<FirstTy>>; 1446349cc55cSDimitry Andric }; 1447349cc55cSDimitry Andric } // end namespace detail 1448349cc55cSDimitry Andric 1449e8d8bef9SDimitry Andric /// Given a container of pairs, return a range over the first elements. 1450e8d8bef9SDimitry Andric template <typename ContainerTy> auto make_first_range(ContainerTy &&c) { 1451349cc55cSDimitry Andric using EltTy = decltype((*std::begin(c))); 1452349cc55cSDimitry Andric return llvm::map_range(std::forward<ContainerTy>(c), 1453349cc55cSDimitry Andric [](EltTy elt) -> typename detail::first_or_second_type< 1454349cc55cSDimitry Andric EltTy, decltype((elt.first))>::type { 1455e8d8bef9SDimitry Andric return elt.first; 1456e8d8bef9SDimitry Andric }); 1457e8d8bef9SDimitry Andric } 1458e8d8bef9SDimitry Andric 14595ffd83dbSDimitry Andric /// Given a container of pairs, return a range over the second elements. 14605ffd83dbSDimitry Andric template <typename ContainerTy> auto make_second_range(ContainerTy &&c) { 1461349cc55cSDimitry Andric using EltTy = decltype((*std::begin(c))); 14625ffd83dbSDimitry Andric return llvm::map_range( 14635ffd83dbSDimitry Andric std::forward<ContainerTy>(c), 1464349cc55cSDimitry Andric [](EltTy elt) -> 1465349cc55cSDimitry Andric typename detail::first_or_second_type<EltTy, 1466349cc55cSDimitry Andric decltype((elt.second))>::type { 14675ffd83dbSDimitry Andric return elt.second; 14685ffd83dbSDimitry Andric }); 14695ffd83dbSDimitry Andric } 14705ffd83dbSDimitry Andric 14710b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 14720b57cec5SDimitry Andric // Extra additions to <utility> 14730b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 14740b57cec5SDimitry Andric 14750b57cec5SDimitry Andric /// Function object to check whether the first component of a std::pair 14760b57cec5SDimitry Andric /// compares less than the first component of another std::pair. 14770b57cec5SDimitry Andric struct less_first { 14780b57cec5SDimitry Andric template <typename T> bool operator()(const T &lhs, const T &rhs) const { 1479349cc55cSDimitry Andric return std::less<>()(lhs.first, rhs.first); 14800b57cec5SDimitry Andric } 14810b57cec5SDimitry Andric }; 14820b57cec5SDimitry Andric 14830b57cec5SDimitry Andric /// Function object to check whether the second component of a std::pair 14840b57cec5SDimitry Andric /// compares less than the second component of another std::pair. 14850b57cec5SDimitry Andric struct less_second { 14860b57cec5SDimitry Andric template <typename T> bool operator()(const T &lhs, const T &rhs) const { 1487349cc55cSDimitry Andric return std::less<>()(lhs.second, rhs.second); 14880b57cec5SDimitry Andric } 14890b57cec5SDimitry Andric }; 14900b57cec5SDimitry Andric 14910b57cec5SDimitry Andric /// \brief Function object to apply a binary function to the first component of 14920b57cec5SDimitry Andric /// a std::pair. 14930b57cec5SDimitry Andric template<typename FuncTy> 14940b57cec5SDimitry Andric struct on_first { 14950b57cec5SDimitry Andric FuncTy func; 14960b57cec5SDimitry Andric 14970b57cec5SDimitry Andric template <typename T> 14985ffd83dbSDimitry Andric decltype(auto) operator()(const T &lhs, const T &rhs) const { 14990b57cec5SDimitry Andric return func(lhs.first, rhs.first); 15000b57cec5SDimitry Andric } 15010b57cec5SDimitry Andric }; 15020b57cec5SDimitry Andric 15030b57cec5SDimitry Andric /// Utility type to build an inheritance chain that makes it easy to rank 15040b57cec5SDimitry Andric /// overload candidates. 15050b57cec5SDimitry Andric template <int N> struct rank : rank<N - 1> {}; 15060b57cec5SDimitry Andric template <> struct rank<0> {}; 15070b57cec5SDimitry Andric 15080b57cec5SDimitry Andric /// traits class for checking whether type T is one of any of the given 15090b57cec5SDimitry Andric /// types in the variadic list. 1510fe6060f1SDimitry Andric template <typename T, typename... Ts> 1511*bdd1243dSDimitry Andric using is_one_of = std::disjunction<std::is_same<T, Ts>...>; 15120b57cec5SDimitry Andric 15130b57cec5SDimitry Andric /// traits class for checking whether type T is a base class for all 15140b57cec5SDimitry Andric /// the given types in the variadic list. 1515fe6060f1SDimitry Andric template <typename T, typename... Ts> 1516*bdd1243dSDimitry Andric using are_base_of = std::conjunction<std::is_base_of<T, Ts>...>; 1517fe6060f1SDimitry Andric 1518fe6060f1SDimitry Andric namespace detail { 1519fe6060f1SDimitry Andric template <typename... Ts> struct Visitor; 1520fe6060f1SDimitry Andric 1521fe6060f1SDimitry Andric template <typename HeadT, typename... TailTs> 1522fe6060f1SDimitry Andric struct Visitor<HeadT, TailTs...> : remove_cvref_t<HeadT>, Visitor<TailTs...> { 1523fe6060f1SDimitry Andric explicit constexpr Visitor(HeadT &&Head, TailTs &&...Tail) 1524fe6060f1SDimitry Andric : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)), 1525fe6060f1SDimitry Andric Visitor<TailTs...>(std::forward<TailTs>(Tail)...) {} 1526fe6060f1SDimitry Andric using remove_cvref_t<HeadT>::operator(); 1527fe6060f1SDimitry Andric using Visitor<TailTs...>::operator(); 15280b57cec5SDimitry Andric }; 15290b57cec5SDimitry Andric 1530fe6060f1SDimitry Andric template <typename HeadT> struct Visitor<HeadT> : remove_cvref_t<HeadT> { 1531fe6060f1SDimitry Andric explicit constexpr Visitor(HeadT &&Head) 1532fe6060f1SDimitry Andric : remove_cvref_t<HeadT>(std::forward<HeadT>(Head)) {} 1533fe6060f1SDimitry Andric using remove_cvref_t<HeadT>::operator(); 15340b57cec5SDimitry Andric }; 1535fe6060f1SDimitry Andric } // namespace detail 1536fe6060f1SDimitry Andric 1537fe6060f1SDimitry Andric /// Returns an opaquely-typed Callable object whose operator() overload set is 1538fe6060f1SDimitry Andric /// the sum of the operator() overload sets of each CallableT in CallableTs. 1539fe6060f1SDimitry Andric /// 1540fe6060f1SDimitry Andric /// The type of the returned object derives from each CallableT in CallableTs. 1541fe6060f1SDimitry Andric /// The returned object is constructed by invoking the appropriate copy or move 1542fe6060f1SDimitry Andric /// constructor of each CallableT, as selected by overload resolution on the 1543fe6060f1SDimitry Andric /// corresponding argument to makeVisitor. 1544fe6060f1SDimitry Andric /// 1545fe6060f1SDimitry Andric /// Example: 1546fe6060f1SDimitry Andric /// 1547fe6060f1SDimitry Andric /// \code 1548fe6060f1SDimitry Andric /// auto visitor = makeVisitor([](auto) { return "unhandled type"; }, 1549fe6060f1SDimitry Andric /// [](int i) { return "int"; }, 1550fe6060f1SDimitry Andric /// [](std::string s) { return "str"; }); 1551fe6060f1SDimitry Andric /// auto a = visitor(42); // `a` is now "int". 1552fe6060f1SDimitry Andric /// auto b = visitor("foo"); // `b` is now "str". 1553fe6060f1SDimitry Andric /// auto c = visitor(3.14f); // `c` is now "unhandled type". 1554fe6060f1SDimitry Andric /// \endcode 1555fe6060f1SDimitry Andric /// 1556fe6060f1SDimitry Andric /// Example of making a visitor with a lambda which captures a move-only type: 1557fe6060f1SDimitry Andric /// 1558fe6060f1SDimitry Andric /// \code 1559fe6060f1SDimitry Andric /// std::unique_ptr<FooHandler> FH = /* ... */; 1560fe6060f1SDimitry Andric /// auto visitor = makeVisitor( 1561fe6060f1SDimitry Andric /// [FH{std::move(FH)}](Foo F) { return FH->handle(F); }, 1562fe6060f1SDimitry Andric /// [](int i) { return i; }, 1563fe6060f1SDimitry Andric /// [](std::string s) { return atoi(s); }); 1564fe6060f1SDimitry Andric /// \endcode 1565fe6060f1SDimitry Andric template <typename... CallableTs> 1566fe6060f1SDimitry Andric constexpr decltype(auto) makeVisitor(CallableTs &&...Callables) { 1567fe6060f1SDimitry Andric return detail::Visitor<CallableTs...>(std::forward<CallableTs>(Callables)...); 1568fe6060f1SDimitry Andric } 15690b57cec5SDimitry Andric 15700b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 15711fd87a68SDimitry Andric // Extra additions to <algorithm> 15720b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 15730b57cec5SDimitry Andric 15745ffd83dbSDimitry Andric // We have a copy here so that LLVM behaves the same when using different 15755ffd83dbSDimitry Andric // standard libraries. 15765ffd83dbSDimitry Andric template <class Iterator, class RNG> 15775ffd83dbSDimitry Andric void shuffle(Iterator first, Iterator last, RNG &&g) { 15785ffd83dbSDimitry Andric // It would be better to use a std::uniform_int_distribution, 15795ffd83dbSDimitry Andric // but that would be stdlib dependent. 1580fe6060f1SDimitry Andric typedef 1581fe6060f1SDimitry Andric typename std::iterator_traits<Iterator>::difference_type difference_type; 1582fe6060f1SDimitry Andric for (auto size = last - first; size > 1; ++first, (void)--size) { 1583fe6060f1SDimitry Andric difference_type offset = g() % size; 1584fe6060f1SDimitry Andric // Avoid self-assignment due to incorrect assertions in libstdc++ 1585fe6060f1SDimitry Andric // containers (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85828). 1586fe6060f1SDimitry Andric if (offset != difference_type(0)) 1587fe6060f1SDimitry Andric std::iter_swap(first, first + offset); 1588fe6060f1SDimitry Andric } 15895ffd83dbSDimitry Andric } 15905ffd83dbSDimitry Andric 15910b57cec5SDimitry Andric /// Adapt std::less<T> for array_pod_sort. 15920b57cec5SDimitry Andric template<typename T> 15930b57cec5SDimitry Andric inline int array_pod_sort_comparator(const void *P1, const void *P2) { 15940b57cec5SDimitry Andric if (std::less<T>()(*reinterpret_cast<const T*>(P1), 15950b57cec5SDimitry Andric *reinterpret_cast<const T*>(P2))) 15960b57cec5SDimitry Andric return -1; 15970b57cec5SDimitry Andric if (std::less<T>()(*reinterpret_cast<const T*>(P2), 15980b57cec5SDimitry Andric *reinterpret_cast<const T*>(P1))) 15990b57cec5SDimitry Andric return 1; 16000b57cec5SDimitry Andric return 0; 16010b57cec5SDimitry Andric } 16020b57cec5SDimitry Andric 16030b57cec5SDimitry Andric /// get_array_pod_sort_comparator - This is an internal helper function used to 16040b57cec5SDimitry Andric /// get type deduction of T right. 16050b57cec5SDimitry Andric template<typename T> 16060b57cec5SDimitry Andric inline int (*get_array_pod_sort_comparator(const T &)) 16070b57cec5SDimitry Andric (const void*, const void*) { 16080b57cec5SDimitry Andric return array_pod_sort_comparator<T>; 16090b57cec5SDimitry Andric } 16100b57cec5SDimitry Andric 1611480093f4SDimitry Andric #ifdef EXPENSIVE_CHECKS 1612480093f4SDimitry Andric namespace detail { 1613480093f4SDimitry Andric 1614480093f4SDimitry Andric inline unsigned presortShuffleEntropy() { 1615480093f4SDimitry Andric static unsigned Result(std::random_device{}()); 1616480093f4SDimitry Andric return Result; 1617480093f4SDimitry Andric } 1618480093f4SDimitry Andric 1619480093f4SDimitry Andric template <class IteratorTy> 1620480093f4SDimitry Andric inline void presortShuffle(IteratorTy Start, IteratorTy End) { 1621480093f4SDimitry Andric std::mt19937 Generator(presortShuffleEntropy()); 1622fe6060f1SDimitry Andric llvm::shuffle(Start, End, Generator); 1623480093f4SDimitry Andric } 1624480093f4SDimitry Andric 1625480093f4SDimitry Andric } // end namespace detail 1626480093f4SDimitry Andric #endif 1627480093f4SDimitry Andric 16280b57cec5SDimitry Andric /// array_pod_sort - This sorts an array with the specified start and end 16290b57cec5SDimitry Andric /// extent. This is just like std::sort, except that it calls qsort instead of 16300b57cec5SDimitry Andric /// using an inlined template. qsort is slightly slower than std::sort, but 16310b57cec5SDimitry Andric /// most sorts are not performance critical in LLVM and std::sort has to be 16320b57cec5SDimitry Andric /// template instantiated for each type, leading to significant measured code 16330b57cec5SDimitry Andric /// bloat. This function should generally be used instead of std::sort where 16340b57cec5SDimitry Andric /// possible. 16350b57cec5SDimitry Andric /// 16360b57cec5SDimitry Andric /// This function assumes that you have simple POD-like types that can be 16370b57cec5SDimitry Andric /// compared with std::less and can be moved with memcpy. If this isn't true, 16380b57cec5SDimitry Andric /// you should use std::sort. 16390b57cec5SDimitry Andric /// 16400b57cec5SDimitry Andric /// NOTE: If qsort_r were portable, we could allow a custom comparator and 16410b57cec5SDimitry Andric /// default to std::less. 16420b57cec5SDimitry Andric template<class IteratorTy> 16430b57cec5SDimitry Andric inline void array_pod_sort(IteratorTy Start, IteratorTy End) { 16440b57cec5SDimitry Andric // Don't inefficiently call qsort with one element or trigger undefined 16450b57cec5SDimitry Andric // behavior with an empty sequence. 16460b57cec5SDimitry Andric auto NElts = End - Start; 16470b57cec5SDimitry Andric if (NElts <= 1) return; 16480b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 1649480093f4SDimitry Andric detail::presortShuffle<IteratorTy>(Start, End); 16500b57cec5SDimitry Andric #endif 16510b57cec5SDimitry Andric qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start)); 16520b57cec5SDimitry Andric } 16530b57cec5SDimitry Andric 16540b57cec5SDimitry Andric template <class IteratorTy> 16550b57cec5SDimitry Andric inline void array_pod_sort( 16560b57cec5SDimitry Andric IteratorTy Start, IteratorTy End, 16570b57cec5SDimitry Andric int (*Compare)( 16580b57cec5SDimitry Andric const typename std::iterator_traits<IteratorTy>::value_type *, 16590b57cec5SDimitry Andric const typename std::iterator_traits<IteratorTy>::value_type *)) { 16600b57cec5SDimitry Andric // Don't inefficiently call qsort with one element or trigger undefined 16610b57cec5SDimitry Andric // behavior with an empty sequence. 16620b57cec5SDimitry Andric auto NElts = End - Start; 16630b57cec5SDimitry Andric if (NElts <= 1) return; 16640b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 1665480093f4SDimitry Andric detail::presortShuffle<IteratorTy>(Start, End); 16660b57cec5SDimitry Andric #endif 16670b57cec5SDimitry Andric qsort(&*Start, NElts, sizeof(*Start), 16680b57cec5SDimitry Andric reinterpret_cast<int (*)(const void *, const void *)>(Compare)); 16690b57cec5SDimitry Andric } 16700b57cec5SDimitry Andric 16715ffd83dbSDimitry Andric namespace detail { 16725ffd83dbSDimitry Andric template <typename T> 16735ffd83dbSDimitry Andric // We can use qsort if the iterator type is a pointer and the underlying value 16745ffd83dbSDimitry Andric // is trivially copyable. 1675*bdd1243dSDimitry Andric using sort_trivially_copyable = std::conjunction< 16765ffd83dbSDimitry Andric std::is_pointer<T>, 1677e8d8bef9SDimitry Andric std::is_trivially_copyable<typename std::iterator_traits<T>::value_type>>; 16785ffd83dbSDimitry Andric } // namespace detail 16795ffd83dbSDimitry Andric 16800b57cec5SDimitry Andric // Provide wrappers to std::sort which shuffle the elements before sorting 16810b57cec5SDimitry Andric // to help uncover non-deterministic behavior (PR35135). 1682*bdd1243dSDimitry Andric template <typename IteratorTy> 16830b57cec5SDimitry Andric inline void sort(IteratorTy Start, IteratorTy End) { 1684*bdd1243dSDimitry Andric if constexpr (detail::sort_trivially_copyable<IteratorTy>::value) { 1685*bdd1243dSDimitry Andric // Forward trivially copyable types to array_pod_sort. This avoids a large 1686*bdd1243dSDimitry Andric // amount of code bloat for a minor performance hit. 1687*bdd1243dSDimitry Andric array_pod_sort(Start, End); 1688*bdd1243dSDimitry Andric } else { 16890b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 1690480093f4SDimitry Andric detail::presortShuffle<IteratorTy>(Start, End); 16910b57cec5SDimitry Andric #endif 16920b57cec5SDimitry Andric std::sort(Start, End); 16930b57cec5SDimitry Andric } 16945ffd83dbSDimitry Andric } 16955ffd83dbSDimitry Andric 16960b57cec5SDimitry Andric template <typename Container> inline void sort(Container &&C) { 16970b57cec5SDimitry Andric llvm::sort(adl_begin(C), adl_end(C)); 16980b57cec5SDimitry Andric } 16990b57cec5SDimitry Andric 17000b57cec5SDimitry Andric template <typename IteratorTy, typename Compare> 17010b57cec5SDimitry Andric inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) { 17020b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS 1703480093f4SDimitry Andric detail::presortShuffle<IteratorTy>(Start, End); 17040b57cec5SDimitry Andric #endif 17050b57cec5SDimitry Andric std::sort(Start, End, Comp); 17060b57cec5SDimitry Andric } 17070b57cec5SDimitry Andric 17080b57cec5SDimitry Andric template <typename Container, typename Compare> 17090b57cec5SDimitry Andric inline void sort(Container &&C, Compare Comp) { 17100b57cec5SDimitry Andric llvm::sort(adl_begin(C), adl_end(C), Comp); 17110b57cec5SDimitry Andric } 17120b57cec5SDimitry Andric 17130b57cec5SDimitry Andric /// Get the size of a range. This is a wrapper function around std::distance 17140b57cec5SDimitry Andric /// which is only enabled when the operation is O(1). 17150b57cec5SDimitry Andric template <typename R> 17165ffd83dbSDimitry Andric auto size(R &&Range, 1717e8d8bef9SDimitry Andric std::enable_if_t< 1718e8d8bef9SDimitry Andric std::is_base_of<std::random_access_iterator_tag, 1719e8d8bef9SDimitry Andric typename std::iterator_traits<decltype( 1720e8d8bef9SDimitry Andric Range.begin())>::iterator_category>::value, 17215ffd83dbSDimitry Andric void> * = nullptr) { 17220b57cec5SDimitry Andric return std::distance(Range.begin(), Range.end()); 17230b57cec5SDimitry Andric } 17240b57cec5SDimitry Andric 17250b57cec5SDimitry Andric /// Provide wrappers to std::for_each which take ranges instead of having to 17260b57cec5SDimitry Andric /// pass begin/end explicitly. 1727e8d8bef9SDimitry Andric template <typename R, typename UnaryFunction> 1728e8d8bef9SDimitry Andric UnaryFunction for_each(R &&Range, UnaryFunction F) { 1729e8d8bef9SDimitry Andric return std::for_each(adl_begin(Range), adl_end(Range), F); 17300b57cec5SDimitry Andric } 17310b57cec5SDimitry Andric 17320b57cec5SDimitry Andric /// Provide wrappers to std::all_of which take ranges instead of having to pass 17330b57cec5SDimitry Andric /// begin/end explicitly. 17340b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17350b57cec5SDimitry Andric bool all_of(R &&Range, UnaryPredicate P) { 17360b57cec5SDimitry Andric return std::all_of(adl_begin(Range), adl_end(Range), P); 17370b57cec5SDimitry Andric } 17380b57cec5SDimitry Andric 17390b57cec5SDimitry Andric /// Provide wrappers to std::any_of which take ranges instead of having to pass 17400b57cec5SDimitry Andric /// begin/end explicitly. 17410b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17420b57cec5SDimitry Andric bool any_of(R &&Range, UnaryPredicate P) { 17430b57cec5SDimitry Andric return std::any_of(adl_begin(Range), adl_end(Range), P); 17440b57cec5SDimitry Andric } 17450b57cec5SDimitry Andric 17460b57cec5SDimitry Andric /// Provide wrappers to std::none_of which take ranges instead of having to pass 17470b57cec5SDimitry Andric /// begin/end explicitly. 17480b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17490b57cec5SDimitry Andric bool none_of(R &&Range, UnaryPredicate P) { 17500b57cec5SDimitry Andric return std::none_of(adl_begin(Range), adl_end(Range), P); 17510b57cec5SDimitry Andric } 17520b57cec5SDimitry Andric 17530b57cec5SDimitry Andric /// Provide wrappers to std::find which take ranges instead of having to pass 17540b57cec5SDimitry Andric /// begin/end explicitly. 17555ffd83dbSDimitry Andric template <typename R, typename T> auto find(R &&Range, const T &Val) { 17560b57cec5SDimitry Andric return std::find(adl_begin(Range), adl_end(Range), Val); 17570b57cec5SDimitry Andric } 17580b57cec5SDimitry Andric 17590b57cec5SDimitry Andric /// Provide wrappers to std::find_if which take ranges instead of having to pass 17600b57cec5SDimitry Andric /// begin/end explicitly. 17610b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17625ffd83dbSDimitry Andric auto find_if(R &&Range, UnaryPredicate P) { 17630b57cec5SDimitry Andric return std::find_if(adl_begin(Range), adl_end(Range), P); 17640b57cec5SDimitry Andric } 17650b57cec5SDimitry Andric 17660b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17675ffd83dbSDimitry Andric auto find_if_not(R &&Range, UnaryPredicate P) { 17680b57cec5SDimitry Andric return std::find_if_not(adl_begin(Range), adl_end(Range), P); 17690b57cec5SDimitry Andric } 17700b57cec5SDimitry Andric 17710b57cec5SDimitry Andric /// Provide wrappers to std::remove_if which take ranges instead of having to 17720b57cec5SDimitry Andric /// pass begin/end explicitly. 17730b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 17745ffd83dbSDimitry Andric auto remove_if(R &&Range, UnaryPredicate P) { 17750b57cec5SDimitry Andric return std::remove_if(adl_begin(Range), adl_end(Range), P); 17760b57cec5SDimitry Andric } 17770b57cec5SDimitry Andric 17780b57cec5SDimitry Andric /// Provide wrappers to std::copy_if which take ranges instead of having to 17790b57cec5SDimitry Andric /// pass begin/end explicitly. 17800b57cec5SDimitry Andric template <typename R, typename OutputIt, typename UnaryPredicate> 17810b57cec5SDimitry Andric OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) { 17820b57cec5SDimitry Andric return std::copy_if(adl_begin(Range), adl_end(Range), Out, P); 17830b57cec5SDimitry Andric } 17840b57cec5SDimitry Andric 1785*bdd1243dSDimitry Andric /// Return the single value in \p Range that satisfies 1786*bdd1243dSDimitry Andric /// \p P(<member of \p Range> *, AllowRepeats)->T * returning nullptr 1787*bdd1243dSDimitry Andric /// when no values or multiple values were found. 1788*bdd1243dSDimitry Andric /// When \p AllowRepeats is true, multiple values that compare equal 1789*bdd1243dSDimitry Andric /// are allowed. 1790*bdd1243dSDimitry Andric template <typename T, typename R, typename Predicate> 1791*bdd1243dSDimitry Andric T *find_singleton(R &&Range, Predicate P, bool AllowRepeats = false) { 1792*bdd1243dSDimitry Andric T *RC = nullptr; 1793*bdd1243dSDimitry Andric for (auto *A : Range) { 1794*bdd1243dSDimitry Andric if (T *PRC = P(A, AllowRepeats)) { 1795*bdd1243dSDimitry Andric if (RC) { 1796*bdd1243dSDimitry Andric if (!AllowRepeats || PRC != RC) 1797*bdd1243dSDimitry Andric return nullptr; 1798*bdd1243dSDimitry Andric } else 1799*bdd1243dSDimitry Andric RC = PRC; 1800*bdd1243dSDimitry Andric } 1801*bdd1243dSDimitry Andric } 1802*bdd1243dSDimitry Andric return RC; 1803*bdd1243dSDimitry Andric } 1804*bdd1243dSDimitry Andric 1805*bdd1243dSDimitry Andric /// Return a pair consisting of the single value in \p Range that satisfies 1806*bdd1243dSDimitry Andric /// \p P(<member of \p Range> *, AllowRepeats)->std::pair<T*, bool> returning 1807*bdd1243dSDimitry Andric /// nullptr when no values or multiple values were found, and a bool indicating 1808*bdd1243dSDimitry Andric /// whether multiple values were found to cause the nullptr. 1809*bdd1243dSDimitry Andric /// When \p AllowRepeats is true, multiple values that compare equal are 1810*bdd1243dSDimitry Andric /// allowed. The predicate \p P returns a pair<T *, bool> where T is the 1811*bdd1243dSDimitry Andric /// singleton while the bool indicates whether multiples have already been 1812*bdd1243dSDimitry Andric /// found. It is expected that first will be nullptr when second is true. 1813*bdd1243dSDimitry Andric /// This allows using find_singleton_nested within the predicate \P. 1814*bdd1243dSDimitry Andric template <typename T, typename R, typename Predicate> 1815*bdd1243dSDimitry Andric std::pair<T *, bool> find_singleton_nested(R &&Range, Predicate P, 1816*bdd1243dSDimitry Andric bool AllowRepeats = false) { 1817*bdd1243dSDimitry Andric T *RC = nullptr; 1818*bdd1243dSDimitry Andric for (auto *A : Range) { 1819*bdd1243dSDimitry Andric std::pair<T *, bool> PRC = P(A, AllowRepeats); 1820*bdd1243dSDimitry Andric if (PRC.second) { 1821*bdd1243dSDimitry Andric assert(PRC.first == nullptr && 1822*bdd1243dSDimitry Andric "Inconsistent return values in find_singleton_nested."); 1823*bdd1243dSDimitry Andric return PRC; 1824*bdd1243dSDimitry Andric } 1825*bdd1243dSDimitry Andric if (PRC.first) { 1826*bdd1243dSDimitry Andric if (RC) { 1827*bdd1243dSDimitry Andric if (!AllowRepeats || PRC.first != RC) 1828*bdd1243dSDimitry Andric return {nullptr, true}; 1829*bdd1243dSDimitry Andric } else 1830*bdd1243dSDimitry Andric RC = PRC.first; 1831*bdd1243dSDimitry Andric } 1832*bdd1243dSDimitry Andric } 1833*bdd1243dSDimitry Andric return {RC, false}; 1834*bdd1243dSDimitry Andric } 1835*bdd1243dSDimitry Andric 18360b57cec5SDimitry Andric template <typename R, typename OutputIt> 18370b57cec5SDimitry Andric OutputIt copy(R &&Range, OutputIt Out) { 18380b57cec5SDimitry Andric return std::copy(adl_begin(Range), adl_end(Range), Out); 18390b57cec5SDimitry Andric } 18400b57cec5SDimitry Andric 1841*bdd1243dSDimitry Andric /// Provide wrappers to std::replace_copy_if which take ranges instead of having 1842*bdd1243dSDimitry Andric /// to pass begin/end explicitly. 1843*bdd1243dSDimitry Andric template <typename R, typename OutputIt, typename UnaryPredicate, typename T> 1844*bdd1243dSDimitry Andric OutputIt replace_copy_if(R &&Range, OutputIt Out, UnaryPredicate P, 1845*bdd1243dSDimitry Andric const T &NewValue) { 1846*bdd1243dSDimitry Andric return std::replace_copy_if(adl_begin(Range), adl_end(Range), Out, P, 1847*bdd1243dSDimitry Andric NewValue); 1848*bdd1243dSDimitry Andric } 1849*bdd1243dSDimitry Andric 1850*bdd1243dSDimitry Andric /// Provide wrappers to std::replace_copy which take ranges instead of having to 1851*bdd1243dSDimitry Andric /// pass begin/end explicitly. 1852*bdd1243dSDimitry Andric template <typename R, typename OutputIt, typename T> 1853*bdd1243dSDimitry Andric OutputIt replace_copy(R &&Range, OutputIt Out, const T &OldValue, 1854*bdd1243dSDimitry Andric const T &NewValue) { 1855*bdd1243dSDimitry Andric return std::replace_copy(adl_begin(Range), adl_end(Range), Out, OldValue, 1856*bdd1243dSDimitry Andric NewValue); 1857*bdd1243dSDimitry Andric } 1858*bdd1243dSDimitry Andric 1859e8d8bef9SDimitry Andric /// Provide wrappers to std::move which take ranges instead of having to 1860e8d8bef9SDimitry Andric /// pass begin/end explicitly. 1861e8d8bef9SDimitry Andric template <typename R, typename OutputIt> 1862e8d8bef9SDimitry Andric OutputIt move(R &&Range, OutputIt Out) { 1863e8d8bef9SDimitry Andric return std::move(adl_begin(Range), adl_end(Range), Out); 1864e8d8bef9SDimitry Andric } 1865e8d8bef9SDimitry Andric 18660b57cec5SDimitry Andric /// Wrapper function around std::find to detect if an element exists 18670b57cec5SDimitry Andric /// in a container. 18680b57cec5SDimitry Andric template <typename R, typename E> 18690b57cec5SDimitry Andric bool is_contained(R &&Range, const E &Element) { 18700b57cec5SDimitry Andric return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range); 18710b57cec5SDimitry Andric } 18720b57cec5SDimitry Andric 187381ad6265SDimitry Andric template <typename T> 187481ad6265SDimitry Andric constexpr bool is_contained(std::initializer_list<T> Set, T Value) { 187581ad6265SDimitry Andric // TODO: Use std::find when we switch to C++20. 187681ad6265SDimitry Andric for (T V : Set) 187781ad6265SDimitry Andric if (V == Value) 187881ad6265SDimitry Andric return true; 187981ad6265SDimitry Andric return false; 188081ad6265SDimitry Andric } 188181ad6265SDimitry Andric 18825ffd83dbSDimitry Andric /// Wrapper function around std::is_sorted to check if elements in a range \p R 18835ffd83dbSDimitry Andric /// are sorted with respect to a comparator \p C. 18845ffd83dbSDimitry Andric template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) { 18855ffd83dbSDimitry Andric return std::is_sorted(adl_begin(Range), adl_end(Range), C); 18865ffd83dbSDimitry Andric } 18875ffd83dbSDimitry Andric 18885ffd83dbSDimitry Andric /// Wrapper function around std::is_sorted to check if elements in a range \p R 18895ffd83dbSDimitry Andric /// are sorted in non-descending order. 18905ffd83dbSDimitry Andric template <typename R> bool is_sorted(R &&Range) { 18915ffd83dbSDimitry Andric return std::is_sorted(adl_begin(Range), adl_end(Range)); 18925ffd83dbSDimitry Andric } 18935ffd83dbSDimitry Andric 18940b57cec5SDimitry Andric /// Wrapper function around std::count to count the number of times an element 18950b57cec5SDimitry Andric /// \p Element occurs in the given range \p Range. 18965ffd83dbSDimitry Andric template <typename R, typename E> auto count(R &&Range, const E &Element) { 18970b57cec5SDimitry Andric return std::count(adl_begin(Range), adl_end(Range), Element); 18980b57cec5SDimitry Andric } 18990b57cec5SDimitry Andric 19000b57cec5SDimitry Andric /// Wrapper function around std::count_if to count the number of times an 19010b57cec5SDimitry Andric /// element satisfying a given predicate occurs in a range. 19020b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 19035ffd83dbSDimitry Andric auto count_if(R &&Range, UnaryPredicate P) { 19040b57cec5SDimitry Andric return std::count_if(adl_begin(Range), adl_end(Range), P); 19050b57cec5SDimitry Andric } 19060b57cec5SDimitry Andric 19070b57cec5SDimitry Andric /// Wrapper function around std::transform to apply a function to a range and 19080b57cec5SDimitry Andric /// store the result elsewhere. 1909e8d8bef9SDimitry Andric template <typename R, typename OutputIt, typename UnaryFunction> 1910e8d8bef9SDimitry Andric OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F) { 1911e8d8bef9SDimitry Andric return std::transform(adl_begin(Range), adl_end(Range), d_first, F); 19120b57cec5SDimitry Andric } 19130b57cec5SDimitry Andric 19140b57cec5SDimitry Andric /// Provide wrappers to std::partition which take ranges instead of having to 19150b57cec5SDimitry Andric /// pass begin/end explicitly. 19160b57cec5SDimitry Andric template <typename R, typename UnaryPredicate> 19175ffd83dbSDimitry Andric auto partition(R &&Range, UnaryPredicate P) { 19180b57cec5SDimitry Andric return std::partition(adl_begin(Range), adl_end(Range), P); 19190b57cec5SDimitry Andric } 19200b57cec5SDimitry Andric 19210b57cec5SDimitry Andric /// Provide wrappers to std::lower_bound which take ranges instead of having to 19220b57cec5SDimitry Andric /// pass begin/end explicitly. 19235ffd83dbSDimitry Andric template <typename R, typename T> auto lower_bound(R &&Range, T &&Value) { 19240b57cec5SDimitry Andric return std::lower_bound(adl_begin(Range), adl_end(Range), 19250b57cec5SDimitry Andric std::forward<T>(Value)); 19260b57cec5SDimitry Andric } 19270b57cec5SDimitry Andric 19280b57cec5SDimitry Andric template <typename R, typename T, typename Compare> 19295ffd83dbSDimitry Andric auto lower_bound(R &&Range, T &&Value, Compare C) { 19300b57cec5SDimitry Andric return std::lower_bound(adl_begin(Range), adl_end(Range), 19310b57cec5SDimitry Andric std::forward<T>(Value), C); 19320b57cec5SDimitry Andric } 19330b57cec5SDimitry Andric 19340b57cec5SDimitry Andric /// Provide wrappers to std::upper_bound which take ranges instead of having to 19350b57cec5SDimitry Andric /// pass begin/end explicitly. 19365ffd83dbSDimitry Andric template <typename R, typename T> auto upper_bound(R &&Range, T &&Value) { 19370b57cec5SDimitry Andric return std::upper_bound(adl_begin(Range), adl_end(Range), 19380b57cec5SDimitry Andric std::forward<T>(Value)); 19390b57cec5SDimitry Andric } 19400b57cec5SDimitry Andric 19410b57cec5SDimitry Andric template <typename R, typename T, typename Compare> 19425ffd83dbSDimitry Andric auto upper_bound(R &&Range, T &&Value, Compare C) { 19430b57cec5SDimitry Andric return std::upper_bound(adl_begin(Range), adl_end(Range), 19440b57cec5SDimitry Andric std::forward<T>(Value), C); 19450b57cec5SDimitry Andric } 19460b57cec5SDimitry Andric 19470b57cec5SDimitry Andric template <typename R> 19480b57cec5SDimitry Andric void stable_sort(R &&Range) { 19490b57cec5SDimitry Andric std::stable_sort(adl_begin(Range), adl_end(Range)); 19500b57cec5SDimitry Andric } 19510b57cec5SDimitry Andric 19520b57cec5SDimitry Andric template <typename R, typename Compare> 19530b57cec5SDimitry Andric void stable_sort(R &&Range, Compare C) { 19540b57cec5SDimitry Andric std::stable_sort(adl_begin(Range), adl_end(Range), C); 19550b57cec5SDimitry Andric } 19560b57cec5SDimitry Andric 19570b57cec5SDimitry Andric /// Binary search for the first iterator in a range where a predicate is false. 19580b57cec5SDimitry Andric /// Requires that C is always true below some limit, and always false above it. 19590b57cec5SDimitry Andric template <typename R, typename Predicate, 19600b57cec5SDimitry Andric typename Val = decltype(*adl_begin(std::declval<R>()))> 19615ffd83dbSDimitry Andric auto partition_point(R &&Range, Predicate P) { 19620b57cec5SDimitry Andric return std::partition_point(adl_begin(Range), adl_end(Range), P); 19630b57cec5SDimitry Andric } 19640b57cec5SDimitry Andric 1965fe6060f1SDimitry Andric template<typename Range, typename Predicate> 1966fe6060f1SDimitry Andric auto unique(Range &&R, Predicate P) { 1967fe6060f1SDimitry Andric return std::unique(adl_begin(R), adl_end(R), P); 1968fe6060f1SDimitry Andric } 1969fe6060f1SDimitry Andric 1970fe6060f1SDimitry Andric /// Wrapper function around std::equal to detect if pair-wise elements between 1971fe6060f1SDimitry Andric /// two ranges are the same. 1972fe6060f1SDimitry Andric template <typename L, typename R> bool equal(L &&LRange, R &&RRange) { 1973fe6060f1SDimitry Andric return std::equal(adl_begin(LRange), adl_end(LRange), adl_begin(RRange), 1974fe6060f1SDimitry Andric adl_end(RRange)); 1975fe6060f1SDimitry Andric } 1976fe6060f1SDimitry Andric 1977*bdd1243dSDimitry Andric /// Returns true if all elements in Range are equal or when the Range is empty. 1978*bdd1243dSDimitry Andric template <typename R> bool all_equal(R &&Range) { 1979*bdd1243dSDimitry Andric auto Begin = adl_begin(Range); 1980*bdd1243dSDimitry Andric auto End = adl_end(Range); 1981*bdd1243dSDimitry Andric return Begin == End || std::equal(Begin + 1, End, Begin); 1982*bdd1243dSDimitry Andric } 1983*bdd1243dSDimitry Andric 1984*bdd1243dSDimitry Andric /// Returns true if all Values in the initializer lists are equal or the list 1985*bdd1243dSDimitry Andric // is empty. 1986*bdd1243dSDimitry Andric template <typename T> bool all_equal(std::initializer_list<T> Values) { 1987*bdd1243dSDimitry Andric return all_equal<std::initializer_list<T>>(std::move(Values)); 19880b57cec5SDimitry Andric } 19890b57cec5SDimitry Andric 19900b57cec5SDimitry Andric /// Provide a container algorithm similar to C++ Library Fundamentals v2's 19910b57cec5SDimitry Andric /// `erase_if` which is equivalent to: 19920b57cec5SDimitry Andric /// 19930b57cec5SDimitry Andric /// C.erase(remove_if(C, pred), C.end()); 19940b57cec5SDimitry Andric /// 19950b57cec5SDimitry Andric /// This version works for any container with an erase method call accepting 19960b57cec5SDimitry Andric /// two iterators. 19970b57cec5SDimitry Andric template <typename Container, typename UnaryPredicate> 19980b57cec5SDimitry Andric void erase_if(Container &C, UnaryPredicate P) { 19990b57cec5SDimitry Andric C.erase(remove_if(C, P), C.end()); 20000b57cec5SDimitry Andric } 20010b57cec5SDimitry Andric 2002e8d8bef9SDimitry Andric /// Wrapper function to remove a value from a container: 2003e8d8bef9SDimitry Andric /// 2004e8d8bef9SDimitry Andric /// C.erase(remove(C.begin(), C.end(), V), C.end()); 2005e8d8bef9SDimitry Andric template <typename Container, typename ValueType> 2006e8d8bef9SDimitry Andric void erase_value(Container &C, ValueType V) { 2007e8d8bef9SDimitry Andric C.erase(std::remove(C.begin(), C.end(), V), C.end()); 2008e8d8bef9SDimitry Andric } 2009e8d8bef9SDimitry Andric 2010e8d8bef9SDimitry Andric /// Wrapper function to append a range to a container. 2011e8d8bef9SDimitry Andric /// 2012e8d8bef9SDimitry Andric /// C.insert(C.end(), R.begin(), R.end()); 2013e8d8bef9SDimitry Andric template <typename Container, typename Range> 2014e8d8bef9SDimitry Andric inline void append_range(Container &C, Range &&R) { 2015e8d8bef9SDimitry Andric C.insert(C.end(), R.begin(), R.end()); 2016e8d8bef9SDimitry Andric } 2017e8d8bef9SDimitry Andric 20180b57cec5SDimitry Andric /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with 20190b57cec5SDimitry Andric /// the range [ValIt, ValEnd) (which is not from the same container). 20200b57cec5SDimitry Andric template<typename Container, typename RandomAccessIterator> 20210b57cec5SDimitry Andric void replace(Container &Cont, typename Container::iterator ContIt, 20220b57cec5SDimitry Andric typename Container::iterator ContEnd, RandomAccessIterator ValIt, 20230b57cec5SDimitry Andric RandomAccessIterator ValEnd) { 20240b57cec5SDimitry Andric while (true) { 20250b57cec5SDimitry Andric if (ValIt == ValEnd) { 20260b57cec5SDimitry Andric Cont.erase(ContIt, ContEnd); 20270b57cec5SDimitry Andric return; 20280b57cec5SDimitry Andric } else if (ContIt == ContEnd) { 20290b57cec5SDimitry Andric Cont.insert(ContIt, ValIt, ValEnd); 20300b57cec5SDimitry Andric return; 20310b57cec5SDimitry Andric } 20320b57cec5SDimitry Andric *ContIt++ = *ValIt++; 20330b57cec5SDimitry Andric } 20340b57cec5SDimitry Andric } 20350b57cec5SDimitry Andric 20360b57cec5SDimitry Andric /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with 20370b57cec5SDimitry Andric /// the range R. 20380b57cec5SDimitry Andric template<typename Container, typename Range = std::initializer_list< 20390b57cec5SDimitry Andric typename Container::value_type>> 20400b57cec5SDimitry Andric void replace(Container &Cont, typename Container::iterator ContIt, 20410b57cec5SDimitry Andric typename Container::iterator ContEnd, Range R) { 20420b57cec5SDimitry Andric replace(Cont, ContIt, ContEnd, R.begin(), R.end()); 20430b57cec5SDimitry Andric } 20440b57cec5SDimitry Andric 20455ffd83dbSDimitry Andric /// An STL-style algorithm similar to std::for_each that applies a second 20465ffd83dbSDimitry Andric /// functor between every pair of elements. 20475ffd83dbSDimitry Andric /// 20485ffd83dbSDimitry Andric /// This provides the control flow logic to, for example, print a 20495ffd83dbSDimitry Andric /// comma-separated list: 20505ffd83dbSDimitry Andric /// \code 20515ffd83dbSDimitry Andric /// interleave(names.begin(), names.end(), 20525ffd83dbSDimitry Andric /// [&](StringRef name) { os << name; }, 20535ffd83dbSDimitry Andric /// [&] { os << ", "; }); 20545ffd83dbSDimitry Andric /// \endcode 20555ffd83dbSDimitry Andric template <typename ForwardIterator, typename UnaryFunctor, 20565ffd83dbSDimitry Andric typename NullaryFunctor, 2057*bdd1243dSDimitry Andric typename = std::enable_if_t< 20585ffd83dbSDimitry Andric !std::is_constructible<StringRef, UnaryFunctor>::value && 2059*bdd1243dSDimitry Andric !std::is_constructible<StringRef, NullaryFunctor>::value>> 20605ffd83dbSDimitry Andric inline void interleave(ForwardIterator begin, ForwardIterator end, 20615ffd83dbSDimitry Andric UnaryFunctor each_fn, NullaryFunctor between_fn) { 20625ffd83dbSDimitry Andric if (begin == end) 20635ffd83dbSDimitry Andric return; 20645ffd83dbSDimitry Andric each_fn(*begin); 20655ffd83dbSDimitry Andric ++begin; 20665ffd83dbSDimitry Andric for (; begin != end; ++begin) { 20675ffd83dbSDimitry Andric between_fn(); 20685ffd83dbSDimitry Andric each_fn(*begin); 20695ffd83dbSDimitry Andric } 20705ffd83dbSDimitry Andric } 20715ffd83dbSDimitry Andric 20725ffd83dbSDimitry Andric template <typename Container, typename UnaryFunctor, typename NullaryFunctor, 2073*bdd1243dSDimitry Andric typename = std::enable_if_t< 20745ffd83dbSDimitry Andric !std::is_constructible<StringRef, UnaryFunctor>::value && 2075*bdd1243dSDimitry Andric !std::is_constructible<StringRef, NullaryFunctor>::value>> 20765ffd83dbSDimitry Andric inline void interleave(const Container &c, UnaryFunctor each_fn, 20775ffd83dbSDimitry Andric NullaryFunctor between_fn) { 20785ffd83dbSDimitry Andric interleave(c.begin(), c.end(), each_fn, between_fn); 20795ffd83dbSDimitry Andric } 20805ffd83dbSDimitry Andric 20815ffd83dbSDimitry Andric /// Overload of interleave for the common case of string separator. 20825ffd83dbSDimitry Andric template <typename Container, typename UnaryFunctor, typename StreamT, 20835ffd83dbSDimitry Andric typename T = detail::ValueOfRange<Container>> 20845ffd83dbSDimitry Andric inline void interleave(const Container &c, StreamT &os, UnaryFunctor each_fn, 20855ffd83dbSDimitry Andric const StringRef &separator) { 20865ffd83dbSDimitry Andric interleave(c.begin(), c.end(), each_fn, [&] { os << separator; }); 20875ffd83dbSDimitry Andric } 20885ffd83dbSDimitry Andric template <typename Container, typename StreamT, 20895ffd83dbSDimitry Andric typename T = detail::ValueOfRange<Container>> 20905ffd83dbSDimitry Andric inline void interleave(const Container &c, StreamT &os, 20915ffd83dbSDimitry Andric const StringRef &separator) { 20925ffd83dbSDimitry Andric interleave( 20935ffd83dbSDimitry Andric c, os, [&](const T &a) { os << a; }, separator); 20945ffd83dbSDimitry Andric } 20955ffd83dbSDimitry Andric 20965ffd83dbSDimitry Andric template <typename Container, typename UnaryFunctor, typename StreamT, 20975ffd83dbSDimitry Andric typename T = detail::ValueOfRange<Container>> 20985ffd83dbSDimitry Andric inline void interleaveComma(const Container &c, StreamT &os, 20995ffd83dbSDimitry Andric UnaryFunctor each_fn) { 21005ffd83dbSDimitry Andric interleave(c, os, each_fn, ", "); 21015ffd83dbSDimitry Andric } 21025ffd83dbSDimitry Andric template <typename Container, typename StreamT, 21035ffd83dbSDimitry Andric typename T = detail::ValueOfRange<Container>> 21045ffd83dbSDimitry Andric inline void interleaveComma(const Container &c, StreamT &os) { 21055ffd83dbSDimitry Andric interleaveComma(c, os, [&](const T &a) { os << a; }); 21065ffd83dbSDimitry Andric } 21075ffd83dbSDimitry Andric 21080b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 21090b57cec5SDimitry Andric // Extra additions to <memory> 21100b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 21110b57cec5SDimitry Andric 21120b57cec5SDimitry Andric struct FreeDeleter { 21130b57cec5SDimitry Andric void operator()(void* v) { 21140b57cec5SDimitry Andric ::free(v); 21150b57cec5SDimitry Andric } 21160b57cec5SDimitry Andric }; 21170b57cec5SDimitry Andric 21180b57cec5SDimitry Andric template<typename First, typename Second> 21190b57cec5SDimitry Andric struct pair_hash { 21200b57cec5SDimitry Andric size_t operator()(const std::pair<First, Second> &P) const { 21210b57cec5SDimitry Andric return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second); 21220b57cec5SDimitry Andric } 21230b57cec5SDimitry Andric }; 21240b57cec5SDimitry Andric 21250b57cec5SDimitry Andric /// Binary functor that adapts to any other binary functor after dereferencing 21260b57cec5SDimitry Andric /// operands. 21270b57cec5SDimitry Andric template <typename T> struct deref { 21280b57cec5SDimitry Andric T func; 21290b57cec5SDimitry Andric 21300b57cec5SDimitry Andric // Could be further improved to cope with non-derivable functors and 21310b57cec5SDimitry Andric // non-binary functors (should be a variadic template member function 21320b57cec5SDimitry Andric // operator()). 21335ffd83dbSDimitry Andric template <typename A, typename B> auto operator()(A &lhs, B &rhs) const { 21340b57cec5SDimitry Andric assert(lhs); 21350b57cec5SDimitry Andric assert(rhs); 21360b57cec5SDimitry Andric return func(*lhs, *rhs); 21370b57cec5SDimitry Andric } 21380b57cec5SDimitry Andric }; 21390b57cec5SDimitry Andric 21400b57cec5SDimitry Andric namespace detail { 21410b57cec5SDimitry Andric 21420b57cec5SDimitry Andric template <typename R> class enumerator_iter; 21430b57cec5SDimitry Andric 21440b57cec5SDimitry Andric template <typename R> struct result_pair { 21450b57cec5SDimitry Andric using value_reference = 21460b57cec5SDimitry Andric typename std::iterator_traits<IterOfRange<R>>::reference; 21470b57cec5SDimitry Andric 21480b57cec5SDimitry Andric friend class enumerator_iter<R>; 21490b57cec5SDimitry Andric 21500b57cec5SDimitry Andric result_pair() = default; 21510b57cec5SDimitry Andric result_pair(std::size_t Index, IterOfRange<R> Iter) 21520b57cec5SDimitry Andric : Index(Index), Iter(Iter) {} 21530b57cec5SDimitry Andric 2154fe6060f1SDimitry Andric result_pair(const result_pair<R> &Other) 2155480093f4SDimitry Andric : Index(Other.Index), Iter(Other.Iter) {} 2156fe6060f1SDimitry Andric result_pair &operator=(const result_pair &Other) { 21570b57cec5SDimitry Andric Index = Other.Index; 21580b57cec5SDimitry Andric Iter = Other.Iter; 21590b57cec5SDimitry Andric return *this; 21600b57cec5SDimitry Andric } 21610b57cec5SDimitry Andric 21620b57cec5SDimitry Andric std::size_t index() const { return Index; } 2163349cc55cSDimitry Andric value_reference value() const { return *Iter; } 21640b57cec5SDimitry Andric 21650b57cec5SDimitry Andric private: 21660b57cec5SDimitry Andric std::size_t Index = std::numeric_limits<std::size_t>::max(); 21670b57cec5SDimitry Andric IterOfRange<R> Iter; 21680b57cec5SDimitry Andric }; 21690b57cec5SDimitry Andric 2170*bdd1243dSDimitry Andric template <std::size_t i, typename R> 2171*bdd1243dSDimitry Andric decltype(auto) get(const result_pair<R> &Pair) { 2172*bdd1243dSDimitry Andric static_assert(i < 2); 2173*bdd1243dSDimitry Andric if constexpr (i == 0) { 2174*bdd1243dSDimitry Andric return Pair.index(); 2175*bdd1243dSDimitry Andric } else { 2176*bdd1243dSDimitry Andric return Pair.value(); 2177*bdd1243dSDimitry Andric } 2178*bdd1243dSDimitry Andric } 2179*bdd1243dSDimitry Andric 21800b57cec5SDimitry Andric template <typename R> 21810b57cec5SDimitry Andric class enumerator_iter 2182349cc55cSDimitry Andric : public iterator_facade_base<enumerator_iter<R>, std::forward_iterator_tag, 2183349cc55cSDimitry Andric const result_pair<R>> { 21840b57cec5SDimitry Andric using result_type = result_pair<R>; 21850b57cec5SDimitry Andric 21860b57cec5SDimitry Andric public: 21870b57cec5SDimitry Andric explicit enumerator_iter(IterOfRange<R> EndIter) 21880b57cec5SDimitry Andric : Result(std::numeric_limits<size_t>::max(), EndIter) {} 21890b57cec5SDimitry Andric 21900b57cec5SDimitry Andric enumerator_iter(std::size_t Index, IterOfRange<R> Iter) 21910b57cec5SDimitry Andric : Result(Index, Iter) {} 21920b57cec5SDimitry Andric 21930b57cec5SDimitry Andric const result_type &operator*() const { return Result; } 21940b57cec5SDimitry Andric 2195fe6060f1SDimitry Andric enumerator_iter &operator++() { 21960b57cec5SDimitry Andric assert(Result.Index != std::numeric_limits<size_t>::max()); 21970b57cec5SDimitry Andric ++Result.Iter; 21980b57cec5SDimitry Andric ++Result.Index; 21990b57cec5SDimitry Andric return *this; 22000b57cec5SDimitry Andric } 22010b57cec5SDimitry Andric 2202fe6060f1SDimitry Andric bool operator==(const enumerator_iter &RHS) const { 22030b57cec5SDimitry Andric // Don't compare indices here, only iterators. It's possible for an end 22040b57cec5SDimitry Andric // iterator to have different indices depending on whether it was created 22050b57cec5SDimitry Andric // by calling std::end() versus incrementing a valid iterator. 22060b57cec5SDimitry Andric return Result.Iter == RHS.Result.Iter; 22070b57cec5SDimitry Andric } 22080b57cec5SDimitry Andric 2209fe6060f1SDimitry Andric enumerator_iter(const enumerator_iter &Other) : Result(Other.Result) {} 2210fe6060f1SDimitry Andric enumerator_iter &operator=(const enumerator_iter &Other) { 22110b57cec5SDimitry Andric Result = Other.Result; 22120b57cec5SDimitry Andric return *this; 22130b57cec5SDimitry Andric } 22140b57cec5SDimitry Andric 22150b57cec5SDimitry Andric private: 22160b57cec5SDimitry Andric result_type Result; 22170b57cec5SDimitry Andric }; 22180b57cec5SDimitry Andric 22190b57cec5SDimitry Andric template <typename R> class enumerator { 22200b57cec5SDimitry Andric public: 22210b57cec5SDimitry Andric explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {} 22220b57cec5SDimitry Andric 22230b57cec5SDimitry Andric enumerator_iter<R> begin() { 22240b57cec5SDimitry Andric return enumerator_iter<R>(0, std::begin(TheRange)); 22250b57cec5SDimitry Andric } 22264824e7fdSDimitry Andric enumerator_iter<R> begin() const { 22274824e7fdSDimitry Andric return enumerator_iter<R>(0, std::begin(TheRange)); 22284824e7fdSDimitry Andric } 22290b57cec5SDimitry Andric 22300b57cec5SDimitry Andric enumerator_iter<R> end() { 22310b57cec5SDimitry Andric return enumerator_iter<R>(std::end(TheRange)); 22320b57cec5SDimitry Andric } 22334824e7fdSDimitry Andric enumerator_iter<R> end() const { 22344824e7fdSDimitry Andric return enumerator_iter<R>(std::end(TheRange)); 22354824e7fdSDimitry Andric } 22360b57cec5SDimitry Andric 22370b57cec5SDimitry Andric private: 22380b57cec5SDimitry Andric R TheRange; 22390b57cec5SDimitry Andric }; 22400b57cec5SDimitry Andric 22410b57cec5SDimitry Andric } // end namespace detail 22420b57cec5SDimitry Andric 22430b57cec5SDimitry Andric /// Given an input range, returns a new range whose values are are pair (A,B) 22440b57cec5SDimitry Andric /// such that A is the 0-based index of the item in the sequence, and B is 22450b57cec5SDimitry Andric /// the value from the original sequence. Example: 22460b57cec5SDimitry Andric /// 22470b57cec5SDimitry Andric /// std::vector<char> Items = {'A', 'B', 'C', 'D'}; 22480b57cec5SDimitry Andric /// for (auto X : enumerate(Items)) { 22490b57cec5SDimitry Andric /// printf("Item %d - %c\n", X.index(), X.value()); 22500b57cec5SDimitry Andric /// } 22510b57cec5SDimitry Andric /// 2252*bdd1243dSDimitry Andric /// or using structured bindings: 2253*bdd1243dSDimitry Andric /// 2254*bdd1243dSDimitry Andric /// for (auto [Index, Value] : enumerate(Items)) { 2255*bdd1243dSDimitry Andric /// printf("Item %d - %c\n", Index, Value); 2256*bdd1243dSDimitry Andric /// } 2257*bdd1243dSDimitry Andric /// 22580b57cec5SDimitry Andric /// Output: 22590b57cec5SDimitry Andric /// Item 0 - A 22600b57cec5SDimitry Andric /// Item 1 - B 22610b57cec5SDimitry Andric /// Item 2 - C 22620b57cec5SDimitry Andric /// Item 3 - D 22630b57cec5SDimitry Andric /// 22640b57cec5SDimitry Andric template <typename R> detail::enumerator<R> enumerate(R &&TheRange) { 22650b57cec5SDimitry Andric return detail::enumerator<R>(std::forward<R>(TheRange)); 22660b57cec5SDimitry Andric } 22670b57cec5SDimitry Andric 22680b57cec5SDimitry Andric namespace detail { 22690b57cec5SDimitry Andric 2270349cc55cSDimitry Andric template <typename Predicate, typename... Args> 2271349cc55cSDimitry Andric bool all_of_zip_predicate_first(Predicate &&P, Args &&...args) { 2272349cc55cSDimitry Andric auto z = zip(args...); 2273349cc55cSDimitry Andric auto it = z.begin(); 2274349cc55cSDimitry Andric auto end = z.end(); 2275349cc55cSDimitry Andric while (it != end) { 2276*bdd1243dSDimitry Andric if (!std::apply([&](auto &&...args) { return P(args...); }, *it)) 2277349cc55cSDimitry Andric return false; 2278349cc55cSDimitry Andric ++it; 2279349cc55cSDimitry Andric } 2280349cc55cSDimitry Andric return it.all_equals(end); 2281349cc55cSDimitry Andric } 2282349cc55cSDimitry Andric 2283349cc55cSDimitry Andric // Just an adaptor to switch the order of argument and have the predicate before 2284349cc55cSDimitry Andric // the zipped inputs. 2285349cc55cSDimitry Andric template <typename... ArgsThenPredicate, size_t... InputIndexes> 2286349cc55cSDimitry Andric bool all_of_zip_predicate_last( 2287349cc55cSDimitry Andric std::tuple<ArgsThenPredicate...> argsThenPredicate, 2288349cc55cSDimitry Andric std::index_sequence<InputIndexes...>) { 2289349cc55cSDimitry Andric auto constexpr OutputIndex = 2290349cc55cSDimitry Andric std::tuple_size<decltype(argsThenPredicate)>::value - 1; 2291349cc55cSDimitry Andric return all_of_zip_predicate_first(std::get<OutputIndex>(argsThenPredicate), 2292349cc55cSDimitry Andric std::get<InputIndexes>(argsThenPredicate)...); 2293349cc55cSDimitry Andric } 2294349cc55cSDimitry Andric 2295349cc55cSDimitry Andric } // end namespace detail 2296349cc55cSDimitry Andric 2297349cc55cSDimitry Andric /// Compare two zipped ranges using the provided predicate (as last argument). 2298349cc55cSDimitry Andric /// Return true if all elements satisfy the predicate and false otherwise. 2299349cc55cSDimitry Andric // Return false if the zipped iterator aren't all at end (size mismatch). 2300349cc55cSDimitry Andric template <typename... ArgsAndPredicate> 2301349cc55cSDimitry Andric bool all_of_zip(ArgsAndPredicate &&...argsAndPredicate) { 2302349cc55cSDimitry Andric return detail::all_of_zip_predicate_last( 2303349cc55cSDimitry Andric std::forward_as_tuple(argsAndPredicate...), 2304349cc55cSDimitry Andric std::make_index_sequence<sizeof...(argsAndPredicate) - 1>{}); 2305349cc55cSDimitry Andric } 2306349cc55cSDimitry Andric 23070b57cec5SDimitry Andric /// Return true if the sequence [Begin, End) has exactly N items. Runs in O(N) 23080b57cec5SDimitry Andric /// time. Not meant for use with random-access iterators. 23095ffd83dbSDimitry Andric /// Can optionally take a predicate to filter lazily some items. 23105ffd83dbSDimitry Andric template <typename IterTy, 23115ffd83dbSDimitry Andric typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 23120b57cec5SDimitry Andric bool hasNItems( 23130b57cec5SDimitry Andric IterTy &&Begin, IterTy &&End, unsigned N, 23145ffd83dbSDimitry Andric Pred &&ShouldBeCounted = 23155ffd83dbSDimitry Andric [](const decltype(*std::declval<IterTy>()) &) { return true; }, 23165ffd83dbSDimitry Andric std::enable_if_t< 2317e8d8bef9SDimitry Andric !std::is_base_of<std::random_access_iterator_tag, 2318e8d8bef9SDimitry Andric typename std::iterator_traits<std::remove_reference_t< 2319e8d8bef9SDimitry Andric decltype(Begin)>>::iterator_category>::value, 23205ffd83dbSDimitry Andric void> * = nullptr) { 23215ffd83dbSDimitry Andric for (; N; ++Begin) { 23220b57cec5SDimitry Andric if (Begin == End) 23230b57cec5SDimitry Andric return false; // Too few. 23245ffd83dbSDimitry Andric N -= ShouldBeCounted(*Begin); 23255ffd83dbSDimitry Andric } 23265ffd83dbSDimitry Andric for (; Begin != End; ++Begin) 23275ffd83dbSDimitry Andric if (ShouldBeCounted(*Begin)) 23285ffd83dbSDimitry Andric return false; // Too many. 23295ffd83dbSDimitry Andric return true; 23300b57cec5SDimitry Andric } 23310b57cec5SDimitry Andric 23320b57cec5SDimitry Andric /// Return true if the sequence [Begin, End) has N or more items. Runs in O(N) 23330b57cec5SDimitry Andric /// time. Not meant for use with random-access iterators. 23345ffd83dbSDimitry Andric /// Can optionally take a predicate to lazily filter some items. 23355ffd83dbSDimitry Andric template <typename IterTy, 23365ffd83dbSDimitry Andric typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 23370b57cec5SDimitry Andric bool hasNItemsOrMore( 23380b57cec5SDimitry Andric IterTy &&Begin, IterTy &&End, unsigned N, 23395ffd83dbSDimitry Andric Pred &&ShouldBeCounted = 23405ffd83dbSDimitry Andric [](const decltype(*std::declval<IterTy>()) &) { return true; }, 23415ffd83dbSDimitry Andric std::enable_if_t< 2342e8d8bef9SDimitry Andric !std::is_base_of<std::random_access_iterator_tag, 2343e8d8bef9SDimitry Andric typename std::iterator_traits<std::remove_reference_t< 2344e8d8bef9SDimitry Andric decltype(Begin)>>::iterator_category>::value, 23455ffd83dbSDimitry Andric void> * = nullptr) { 23465ffd83dbSDimitry Andric for (; N; ++Begin) { 23470b57cec5SDimitry Andric if (Begin == End) 23480b57cec5SDimitry Andric return false; // Too few. 23495ffd83dbSDimitry Andric N -= ShouldBeCounted(*Begin); 23505ffd83dbSDimitry Andric } 23510b57cec5SDimitry Andric return true; 23520b57cec5SDimitry Andric } 23530b57cec5SDimitry Andric 23545ffd83dbSDimitry Andric /// Returns true if the sequence [Begin, End) has N or less items. Can 23555ffd83dbSDimitry Andric /// optionally take a predicate to lazily filter some items. 23565ffd83dbSDimitry Andric template <typename IterTy, 23575ffd83dbSDimitry Andric typename Pred = bool (*)(const decltype(*std::declval<IterTy>()) &)> 23585ffd83dbSDimitry Andric bool hasNItemsOrLess( 23595ffd83dbSDimitry Andric IterTy &&Begin, IterTy &&End, unsigned N, 23605ffd83dbSDimitry Andric Pred &&ShouldBeCounted = [](const decltype(*std::declval<IterTy>()) &) { 23615ffd83dbSDimitry Andric return true; 23625ffd83dbSDimitry Andric }) { 23635ffd83dbSDimitry Andric assert(N != std::numeric_limits<unsigned>::max()); 23645ffd83dbSDimitry Andric return !hasNItemsOrMore(Begin, End, N + 1, ShouldBeCounted); 23655ffd83dbSDimitry Andric } 23665ffd83dbSDimitry Andric 23675ffd83dbSDimitry Andric /// Returns true if the given container has exactly N items 23685ffd83dbSDimitry Andric template <typename ContainerTy> bool hasNItems(ContainerTy &&C, unsigned N) { 23695ffd83dbSDimitry Andric return hasNItems(std::begin(C), std::end(C), N); 23705ffd83dbSDimitry Andric } 23715ffd83dbSDimitry Andric 23725ffd83dbSDimitry Andric /// Returns true if the given container has N or more items 23735ffd83dbSDimitry Andric template <typename ContainerTy> 23745ffd83dbSDimitry Andric bool hasNItemsOrMore(ContainerTy &&C, unsigned N) { 23755ffd83dbSDimitry Andric return hasNItemsOrMore(std::begin(C), std::end(C), N); 23765ffd83dbSDimitry Andric } 23775ffd83dbSDimitry Andric 23785ffd83dbSDimitry Andric /// Returns true if the given container has N or less items 23795ffd83dbSDimitry Andric template <typename ContainerTy> 23805ffd83dbSDimitry Andric bool hasNItemsOrLess(ContainerTy &&C, unsigned N) { 23815ffd83dbSDimitry Andric return hasNItemsOrLess(std::begin(C), std::end(C), N); 23825ffd83dbSDimitry Andric } 23835ffd83dbSDimitry Andric 23840b57cec5SDimitry Andric /// Returns a raw pointer that represents the same address as the argument. 23850b57cec5SDimitry Andric /// 23865ffd83dbSDimitry Andric /// This implementation can be removed once we move to C++20 where it's defined 23875ffd83dbSDimitry Andric /// as std::to_address(). 23880b57cec5SDimitry Andric /// 23890b57cec5SDimitry Andric /// The std::pointer_traits<>::to_address(p) variations of these overloads has 23900b57cec5SDimitry Andric /// not been implemented. 23915ffd83dbSDimitry Andric template <class Ptr> auto to_address(const Ptr &P) { return P.operator->(); } 23920b57cec5SDimitry Andric template <class T> constexpr T *to_address(T *P) { return P; } 23930b57cec5SDimitry Andric 23940b57cec5SDimitry Andric } // end namespace llvm 23950b57cec5SDimitry Andric 2396*bdd1243dSDimitry Andric namespace std { 2397*bdd1243dSDimitry Andric template <typename R> 2398*bdd1243dSDimitry Andric struct tuple_size<llvm::detail::result_pair<R>> 2399*bdd1243dSDimitry Andric : std::integral_constant<std::size_t, 2> {}; 2400*bdd1243dSDimitry Andric 2401*bdd1243dSDimitry Andric template <std::size_t i, typename R> 2402*bdd1243dSDimitry Andric struct tuple_element<i, llvm::detail::result_pair<R>> 2403*bdd1243dSDimitry Andric : std::conditional<i == 0, std::size_t, 2404*bdd1243dSDimitry Andric typename llvm::detail::result_pair<R>::value_reference> { 2405*bdd1243dSDimitry Andric }; 2406*bdd1243dSDimitry Andric 2407*bdd1243dSDimitry Andric } // namespace std 2408*bdd1243dSDimitry Andric 24090b57cec5SDimitry Andric #endif // LLVM_ADT_STLEXTRAS_H 2410