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_FILL_N_H
10#define _LIBCPP___ALGORITHM_FILL_N_H
11
12#include <__algorithm/for_each_n_segment.h>
13#include <__algorithm/specialized_algorithms.h>
14#include <__config>
15#include <__iterator/iterator_traits.h>
16#include <__iterator/segmented_iterator.h>
17#include <__type_traits/enable_if.h>
18#include <__utility/convert_to_integral.h>
19#include <__utility/move.h>
20
21#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
22# pragma GCC system_header
23#endif
24
25_LIBCPP_PUSH_MACROS
26#include <__undef_macros>
27
28_LIBCPP_BEGIN_NAMESPACE_STD
29
30// fill_n isn't specialized for std::memset, because the compiler already optimizes the loop to a call to std::memset.
31
32template <
33 class _OutputIterator,
34 class _Size,
35 class _Tp,
36 __enable_if_t<!__specialized_algorithm<_Algorithm::__fill_n, __single_iterator<_OutputIterator> >::__has_algorithm,
37 int> = 0>
38inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _OutputIterator
39__fill_n(_OutputIterator __first, _Size __n, const _Tp& __value) {
40#ifndef _LIBCPP_CXX03_LANG
41 if constexpr (__is_segmented_iterator_v<_OutputIterator>) {
42 using __local_iterator = typename __segmented_iterator_traits<_OutputIterator>::__local_iterator;
43 if constexpr (__has_random_access_iterator_category<__local_iterator>::value) {
44 return std::__for_each_n_segment(__first, __n, [&](__local_iterator __lfirst, __local_iterator __llast) {
45 std::__fill_n(__lfirst, __llast - __lfirst, __value);
46 });
47 }
48 }
49#endif
50 for (; __n > 0; ++__first, (void)--__n)
51 *__first = __value;
52 return __first;
53}
54
55template <class _OutIter,
56 class _Size,
57 class _Tp,
58 __enable_if_t<__specialized_algorithm<_Algorithm::__fill_n, __single_iterator<_OutIter> >::__has_algorithm,
59 int> = 0>
60_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _OutIter __fill_n(_OutIter __first, _Size __n, const _Tp& __value) {
61 return __specialized_algorithm<_Algorithm::__fill_n, __single_iterator<_OutIter> >()(
62 std::move(__first), __n, __value);
63}
64
65template <class _OutputIterator, class _Size, class _Tp>
66inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _OutputIterator
67fill_n(_OutputIterator __first, _Size __n, const _Tp& __value) {
68 return std::__fill_n(__first, std::__convert_to_integral(__n), __value);
69}
70
71_LIBCPP_END_NAMESPACE_STD
72
73_LIBCPP_POP_MACROS
74
75#endif // _LIBCPP___ALGORITHM_FILL_N_H
76