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_CONSTEXPR_SINCE_CXX20 _OutputIterator __fill_n(_OutputIterator __first, _Size __n, const _Tp& __value) {
39#ifndef _LIBCPP_CXX03_LANG
40 if constexpr (__is_segmented_iterator_v<_OutputIterator>) {
41 using __local_iterator = typename __segmented_iterator_traits<_OutputIterator>::__local_iterator;
42 if constexpr (__has_random_access_iterator_category<__local_iterator>::value) {
43 return std::__for_each_n_segment(__first, __n, [&](__local_iterator __lfirst, __local_iterator __llast) {
44 std::__fill_n(__lfirst, __llast - __lfirst, __value);
45 });
46 }
47 }
48#endif
49 for (; __n > 0; ++__first, (void)--__n)
50 *__first = __value;
51 return __first;
52}
53
54template <class _OutIter,
55 class _Size,
56 class _Tp,
57 __enable_if_t<__specialized_algorithm<_Algorithm::__fill_n, __single_iterator<_OutIter> >::__has_algorithm,
58 int> = 0>
59_LIBCPP_CONSTEXPR_SINCE_CXX20 _OutIter __fill_n(_OutIter __first, _Size __n, const _Tp& __value) {
60 return __specialized_algorithm<_Algorithm::__fill_n, __single_iterator<_OutIter> >()(
61 std::move(__first), __n, __value);
62}
63
64template <class _OutputIterator, class _Size, class _Tp>
65inline _LIBCPP_CONSTEXPR_SINCE_CXX20 _OutputIterator fill_n(_OutputIterator __first, _Size __n, const _Tp& __value) {
66 return std::__fill_n(__first, std::__convert_to_integral(__n), __value);
67}
68
69_LIBCPP_END_NAMESPACE_STD
70
71_LIBCPP_POP_MACROS
72
73#endif // _LIBCPP___ALGORITHM_FILL_N_H
74