1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef _LIBCPP___ALGORITHM_UNWRAP_ITER_H 10 #define _LIBCPP___ALGORITHM_UNWRAP_ITER_H 11 12 #include <__config> 13 #include <iterator> 14 #include <__memory/pointer_traits.h> 15 #include <type_traits> 16 17 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) 18 #pragma GCC system_header 19 #endif 20 21 _LIBCPP_PUSH_MACROS 22 #include <__undef_macros> 23 24 _LIBCPP_BEGIN_NAMESPACE_STD 25 26 // The job of __unwrap_iter is to lower contiguous iterators (such as 27 // vector<T>::iterator) into pointers, to reduce the number of template 28 // instantiations and to enable pointer-based optimizations e.g. in std::copy. 29 // For iterators that are not contiguous, it must be a no-op. 30 // In debug mode, we don't do this. 31 // 32 // __unwrap_iter is non-constexpr for user-defined iterators whose 33 // `to_address` and/or `operator->` is non-constexpr. This is okay; but we 34 // try to avoid doing __unwrap_iter in constant-evaluated contexts anyway. 35 // 36 // Some algorithms (e.g. std::copy, but not std::sort) need to convert an 37 // "unwrapped" result back into a contiguous iterator. Since contiguous iterators 38 // are random-access, we can do this portably using iterator arithmetic; this 39 // is the job of __rewrap_iter. 40 41 template <class _Iter, bool = __is_cpp17_contiguous_iterator<_Iter>::value> 42 struct __unwrap_iter_impl { 43 static _LIBCPP_CONSTEXPR _Iter 44 __apply(_Iter __i) _NOEXCEPT { 45 return __i; 46 } 47 }; 48 49 #if _LIBCPP_DEBUG_LEVEL < 2 50 51 template <class _Iter> 52 struct __unwrap_iter_impl<_Iter, true> { 53 static _LIBCPP_CONSTEXPR decltype(_VSTD::__to_address(declval<_Iter>())) 54 __apply(_Iter __i) _NOEXCEPT { 55 return _VSTD::__to_address(__i); 56 } 57 }; 58 59 #endif // _LIBCPP_DEBUG_LEVEL < 2 60 61 template<class _Iter, class _Impl = __unwrap_iter_impl<_Iter> > 62 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR 63 decltype(_Impl::__apply(declval<_Iter>())) 64 __unwrap_iter(_Iter __i) _NOEXCEPT 65 { 66 return _Impl::__apply(__i); 67 } 68 69 template<class _OrigIter> 70 _OrigIter __rewrap_iter(_OrigIter, _OrigIter __result) 71 { 72 return __result; 73 } 74 75 template<class _OrigIter, class _UnwrappedIter> 76 _OrigIter __rewrap_iter(_OrigIter __first, _UnwrappedIter __result) 77 { 78 // Precondition: __result is reachable from __first 79 // Precondition: _OrigIter is a contiguous iterator 80 return __first + (__result - _VSTD::__unwrap_iter(__first)); 81 } 82 83 _LIBCPP_END_NAMESPACE_STD 84 85 _LIBCPP_POP_MACROS 86 87 #endif // _LIBCPP___ALGORITHM_UNWRAP_ITER_H 88