copy_n.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. #ifndef _LIBCPP___ALGORITHM_COPY_N_H
  9. #define _LIBCPP___ALGORITHM_COPY_N_H
  10. #include <__algorithm/copy.h>
  11. #include <__config>
  12. #include <__iterator/iterator_traits.h>
  13. #include <__type_traits/enable_if.h>
  14. #include <__utility/convert_to_integral.h>
  15. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  16. # pragma GCC system_header
  17. #endif
  18. _LIBCPP_BEGIN_NAMESPACE_STD
  19. template <class _InputIterator,
  20. class _Size,
  21. class _OutputIterator,
  22. __enable_if_t<__has_input_iterator_category<_InputIterator>::value &&
  23. !__has_random_access_iterator_category<_InputIterator>::value,
  24. int> = 0>
  25. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _OutputIterator
  26. copy_n(_InputIterator __first, _Size __orig_n, _OutputIterator __result) {
  27. typedef decltype(std::__convert_to_integral(__orig_n)) _IntegralSize;
  28. _IntegralSize __n = __orig_n;
  29. if (__n > 0) {
  30. *__result = *__first;
  31. ++__result;
  32. for (--__n; __n > 0; --__n) {
  33. ++__first;
  34. *__result = *__first;
  35. ++__result;
  36. }
  37. }
  38. return __result;
  39. }
  40. template <class _InputIterator,
  41. class _Size,
  42. class _OutputIterator,
  43. __enable_if_t<__has_random_access_iterator_category<_InputIterator>::value, int> = 0>
  44. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _OutputIterator
  45. copy_n(_InputIterator __first, _Size __orig_n, _OutputIterator __result) {
  46. typedef typename iterator_traits<_InputIterator>::difference_type difference_type;
  47. typedef decltype(std::__convert_to_integral(__orig_n)) _IntegralSize;
  48. _IntegralSize __n = __orig_n;
  49. return std::copy(__first, __first + difference_type(__n), __result);
  50. }
  51. _LIBCPP_END_NAMESPACE_STD
  52. #endif // _LIBCPP___ALGORITHM_COPY_N_H