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 <__memory/pointer_traits.h> 14 #include <iterator> 15 #include <type_traits> 16 17 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) 18 # pragma GCC system_header 19 # pragma clang include_instead(<algorithm>) 20 #endif 21 22 _LIBCPP_BEGIN_NAMESPACE_STD 23 24 // The job of __unwrap_iter is to lower contiguous iterators (such as 25 // vector<T>::iterator) into pointers, to reduce the number of template 26 // instantiations and to enable pointer-based optimizations e.g. in std::copy. 27 // For iterators that are not contiguous, it must be a no-op. 28 // In debug mode, we don't do this. 29 // 30 // __unwrap_iter is non-constexpr for user-defined iterators whose 31 // `to_address` and/or `operator->` is non-constexpr. This is okay; but we 32 // try to avoid doing __unwrap_iter in constant-evaluated contexts anyway. 33 // 34 // Some algorithms (e.g. std::copy, but not std::sort) need to convert an 35 // "unwrapped" result back into a contiguous iterator. Since contiguous iterators 36 // are random-access, we can do this portably using iterator arithmetic; this 37 // is the job of __rewrap_iter. 38 39 template <class _Iter, bool = __is_cpp17_contiguous_iterator<_Iter>::value> 40 struct __unwrap_iter_impl { 41 static _LIBCPP_CONSTEXPR _Iter 42 __apply(_Iter __i) _NOEXCEPT { 43 return __i; 44 } 45 }; 46 47 #if _LIBCPP_DEBUG_LEVEL < 2 48 49 template <class _Iter> 50 struct __unwrap_iter_impl<_Iter, true> { 51 static _LIBCPP_CONSTEXPR decltype(_VSTD::__to_address(declval<_Iter>())) 52 __apply(_Iter __i) _NOEXCEPT { 53 return _VSTD::__to_address(__i); 54 } 55 }; 56 57 #endif // _LIBCPP_DEBUG_LEVEL < 2 58 59 template<class _Iter, class _Impl = __unwrap_iter_impl<_Iter> > 60 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR 61 decltype(_Impl::__apply(declval<_Iter>())) 62 __unwrap_iter(_Iter __i) _NOEXCEPT 63 { 64 return _Impl::__apply(__i); 65 } 66 67 template<class _OrigIter> 68 _LIBCPP_HIDE_FROM_ABI 69 _OrigIter __rewrap_iter(_OrigIter, _OrigIter __result) 70 { 71 return __result; 72 } 73 74 template<class _OrigIter, class _UnwrappedIter> 75 _LIBCPP_HIDE_FROM_ABI 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 #endif // _LIBCPP___ALGORITHM_UNWRAP_ITER_H 86