1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___FORMAT_FORMATTER_OUTPUT_H
11#define _LIBCPP___FORMAT_FORMATTER_OUTPUT_H
12
13#include <__algorithm/ranges_copy.h>
14#include <__algorithm/ranges_fill_n.h>
15#include <__algorithm/ranges_transform.h>
16#include <__bit/countl.h>
17#include <__concepts/same_as.h>
18#include <__config>
19#include <__cstddef/ptrdiff_t.h>
20#include <__cstddef/size_t.h>
21#include <__format/buffer.h>
22#include <__format/fmt_char_type.h>
23#include <__format/formatter.h>
24#include <__format/parser_std_format_spec.h>
25#include <__format/unicode.h>
26#include <__iterator/back_insert_iterator.h>
27#include <__iterator/concepts.h>
28#include <__iterator/iterator_traits.h>
29#include <__memory/addressof.h>
30#include <__memory/pointer_traits.h>
31#include <__utility/move.h>
32#include <__utility/unreachable.h>
33#include <string_view>
34
35#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
36# pragma GCC system_header
37#endif
38
39_LIBCPP_PUSH_MACROS
40#include <__undef_macros>
41
42_LIBCPP_BEGIN_NAMESPACE_STD
43
44#if _LIBCPP_STD_VER >= 20
45
46namespace __formatter {
47
48struct __padding_size_result {
49 size_t __before_;
50 size_t __after_;
51};
52
53constexpr __padding_size_result __padding_size(size_t __size, size_t __width, __format_spec::__alignment __align) {
54 _LIBCPP_ASSERT_INTERNAL(__width > __size, "don't call this function when no padding is required");
55 _LIBCPP_ASSERT_INTERNAL(
56 __align != __format_spec::__alignment::__zero_padding, "the caller should have handled the zero-padding");
57
58 size_t __fill = __width - __size;
59 switch (__align) {
60 case __format_spec::__alignment::__zero_padding:
61 __libcpp_unreachable();
62
63 case __format_spec::__alignment::__left:
64 return {0, __fill};
65
66 case __format_spec::__alignment::__center: {
67 // The extra padding is divided per [format.string.std]/3
68 // __before = floor(__fill, 2);
69 // __after = ceil(__fill, 2);
70 size_t __before = __fill / 2;
71 size_t __after = __fill - __before;
72 return {__before, __after};
73 }
74 case __format_spec::__alignment::__default:
75 case __format_spec::__alignment::__right:
76 return {__fill, 0};
77 }
78 __libcpp_unreachable();
79}
80
81/// Copy wrapper.
82///
83/// This uses a "mass output function" of __format::__output_buffer when possible.
84template <__fmt_char_type _CharT, __fmt_char_type _OutCharT = _CharT>
85auto __copy(basic_string_view<_CharT> __str, output_iterator<const _OutCharT&> auto __out_it) -> decltype(__out_it) {
86 if constexpr (std::same_as<decltype(__out_it), std::back_insert_iterator<__format::__output_buffer<_OutCharT>>>) {
87 __out_it.__get_container()->__copy(__str);
88 return __out_it;
89 } else if constexpr (std::same_as<decltype(__out_it), typename __format::__retarget_buffer<_OutCharT>::__iterator>) {
90 __out_it.__buffer_->__copy(__str);
91 return __out_it;
92 } else {
93 return std::ranges::copy(__str, std::move(__out_it)).out;
94 }
95}
96
97template <contiguous_iterator _Iterator,
98 __fmt_char_type _CharT = typename iterator_traits<_Iterator>::value_type,
99 __fmt_char_type _OutCharT = _CharT>
100auto __copy(_Iterator __first, _Iterator __last, output_iterator<const _OutCharT&> auto __out_it)
101 -> decltype(__out_it) {
102 return __formatter::__copy(basic_string_view{__first, __last}, std::move(__out_it));
103}
104
105template <contiguous_iterator _Iterator,
106 __fmt_char_type _CharT = typename iterator_traits<_Iterator>::value_type,
107 __fmt_char_type _OutCharT = _CharT>
108auto __copy(_Iterator __first, size_t __n, output_iterator<const _OutCharT&> auto __out_it) -> decltype(__out_it) {
109 return __formatter::__copy(basic_string_view{std::to_address(__first), __n}, std::move(__out_it));
110}
111
112/// Transform wrapper.
113///
114/// This uses a "mass output function" of __format::__output_buffer when possible.
115template <contiguous_iterator _Iterator,
116 __fmt_char_type _CharT = typename iterator_traits<_Iterator>::value_type,
117 __fmt_char_type _OutCharT = _CharT,
118 class _UnaryOperation>
119auto __transform(
120 _Iterator __first, _Iterator __last, output_iterator<const _OutCharT&> auto __out_it, _UnaryOperation __operation)
121 -> decltype(__out_it) {
122 if constexpr (std::same_as<decltype(__out_it), std::back_insert_iterator<__format::__output_buffer<_OutCharT>>>) {
123 __out_it.__get_container()->__transform(__first, __last, std::move(__operation));
124 return __out_it;
125 } else if constexpr (std::same_as<decltype(__out_it), typename __format::__retarget_buffer<_OutCharT>::__iterator>) {
126 __out_it.__buffer_->__transform(__first, __last, std::move(__operation));
127 return __out_it;
128 } else {
129 return std::ranges::transform(__first, __last, std::move(__out_it), __operation).out;
130 }
131}
132
133/// Fill wrapper.
134///
135/// This uses a "mass output function" of __format::__output_buffer when possible.
136template <__fmt_char_type _CharT, output_iterator<const _CharT&> _OutIt>
137_OutIt __fill(_OutIt __out_it, size_t __n, _CharT __value) {
138 if constexpr (std::same_as<decltype(__out_it), std::back_insert_iterator<__format::__output_buffer<_CharT>>>) {
139 __out_it.__get_container()->__fill(__n, __value);
140 return __out_it;
141 } else if constexpr (std::same_as<decltype(__out_it), typename __format::__retarget_buffer<_CharT>::__iterator>) {
142 __out_it.__buffer_->__fill(__n, __value);
143 return __out_it;
144 } else {
145 return std::ranges::fill_n(std::move(__out_it), __n, __value);
146 }
147}
148
149template <__fmt_char_type _CharT, output_iterator<const _CharT&> _OutIt>
150_OutIt __fill(_OutIt __out_it, size_t __n, __format_spec::__code_point<_CharT> __value) {
151# if _LIBCPP_HAS_UNICODE
152 if constexpr (same_as<_CharT, char>) {
153 std::size_t __bytes = std::countl_one(t: static_cast<unsigned char>(__value.__data[0]));
154 if (__bytes == 0)
155 return __formatter::__fill(std::move(__out_it), __n, __value.__data[0]);
156
157 for (size_t __i = 0; __i < __n; ++__i)
158 __out_it = __formatter::__copy(
159 std::addressof(__value.__data[0]), std::addressof(__value.__data[0]) + __bytes, std::move(__out_it));
160 return __out_it;
161# if _LIBCPP_HAS_WIDE_CHARACTERS
162 } else if constexpr (same_as<_CharT, wchar_t>) {
163 if constexpr (sizeof(wchar_t) == 2) {
164 if (!__unicode::__is_high_surrogate(value: __value.__data[0]))
165 return __formatter::__fill(std::move(__out_it), __n, __value.__data[0]);
166
167 for (size_t __i = 0; __i < __n; ++__i)
168 __out_it = __formatter::__copy(
169 std::addressof(__value.__data[0]), std::addressof(__value.__data[0]) + 2, std::move(__out_it));
170 return __out_it;
171 } else if constexpr (sizeof(wchar_t) == 4) {
172 return __formatter::__fill(std::move(__out_it), __n, __value.__data[0]);
173 } else {
174 static_assert(false, "expected sizeof(wchar_t) to be 2 or 4");
175 }
176# endif // _LIBCPP_HAS_WIDE_CHARACTERS
177 } else {
178 static_assert(false, "Unexpected CharT");
179 }
180# else // _LIBCPP_HAS_UNICODE
181 return __formatter::__fill(std::move(__out_it), __n, __value.__data[0]);
182# endif // _LIBCPP_HAS_UNICODE
183}
184
185/// Writes the input to the output with the required padding.
186///
187/// Since the output column width is specified the function can be used for
188/// ASCII and Unicode output.
189///
190/// \pre \a __size <= \a __width. Using this function when this pre-condition
191/// doesn't hold incurs an unwanted overhead.
192///
193/// \param __str The string to write.
194/// \param __out_it The output iterator to write to.
195/// \param __specs The parsed formatting specifications.
196/// \param __size The (estimated) output column width. When the elements
197/// to be written are ASCII the following condition holds
198/// \a __size == \a __last - \a __first.
199///
200/// \returns An iterator pointing beyond the last element written.
201///
202/// \note The type of the elements in range [\a __first, \a __last) can differ
203/// from the type of \a __specs. Integer output uses \c std::to_chars for its
204/// conversion, which means the [\a __first, \a __last) always contains elements
205/// of the type \c char.
206template <class _CharT, class _ParserCharT>
207auto __write(basic_string_view<_CharT> __str,
208 output_iterator<const _CharT&> auto __out_it,
209 __format_spec::__parsed_specifications<_ParserCharT> __specs,
210 ptrdiff_t __size) -> decltype(__out_it) {
211 if (__size >= __specs.__width_)
212 return __formatter::__copy(__str, std::move(__out_it));
213
214 __padding_size_result __padding = __formatter::__padding_size(__size, width: __specs.__width_, align: __specs.__std_.__alignment_);
215 __out_it = __formatter::__fill(std::move(__out_it), __padding.__before_, __specs.__fill_);
216 __out_it = __formatter::__copy(__str, std::move(__out_it));
217 return __formatter::__fill(std::move(__out_it), __padding.__after_, __specs.__fill_);
218}
219
220template <contiguous_iterator _Iterator, class _ParserCharT>
221auto __write(_Iterator __first,
222 _Iterator __last,
223 output_iterator<const iter_value_t<_Iterator>&> auto __out_it,
224 __format_spec::__parsed_specifications<_ParserCharT> __specs,
225 ptrdiff_t __size) -> decltype(__out_it) {
226 _LIBCPP_ASSERT_VALID_INPUT_RANGE(__first <= __last, "Not a valid range");
227 return __formatter::__write(basic_string_view{__first, __last}, std::move(__out_it), __specs, __size);
228}
229
230/// \overload
231///
232/// Calls the function above where \a __size = \a __last - \a __first.
233template <contiguous_iterator _Iterator, class _ParserCharT>
234auto __write(_Iterator __first,
235 _Iterator __last,
236 output_iterator<const iter_value_t<_Iterator>&> auto __out_it,
237 __format_spec::__parsed_specifications<_ParserCharT> __specs) -> decltype(__out_it) {
238 _LIBCPP_ASSERT_VALID_INPUT_RANGE(__first <= __last, "Not a valid range");
239 return __formatter::__write(__first, __last, std::move(__out_it), __specs, __last - __first);
240}
241
242template <contiguous_iterator _Iterator,
243 class _CharT = typename iterator_traits<_Iterator>::value_type,
244 class _ParserCharT,
245 class _UnaryOperation>
246auto __write_transformed(
247 _Iterator __first,
248 _Iterator __last,
249 output_iterator<const _CharT&> auto __out_it,
250 __format_spec::__parsed_specifications<_ParserCharT> __specs,
251 _UnaryOperation __op) -> decltype(__out_it) {
252 _LIBCPP_ASSERT_VALID_INPUT_RANGE(__first <= __last, "Not a valid range");
253
254 ptrdiff_t __size = __last - __first;
255 if (__size >= __specs.__width_)
256 return __formatter::__transform(__first, __last, std::move(__out_it), __op);
257
258 __padding_size_result __padding = __formatter::__padding_size(__size, width: __specs.__width_, align: __specs.__alignment_);
259 __out_it = __formatter::__fill(std::move(__out_it), __padding.__before_, __specs.__fill_);
260 __out_it = __formatter::__transform(__first, __last, std::move(__out_it), __op);
261 return __formatter::__fill(std::move(__out_it), __padding.__after_, __specs.__fill_);
262}
263
264/// Writes a string using format's width estimation algorithm.
265///
266/// \pre !__specs.__has_precision()
267///
268/// \note When \c _LIBCPP_HAS_UNICODE is false the function assumes the input is ASCII.
269template <class _CharT>
270auto __write_string_no_precision(basic_string_view<_CharT> __str,
271 output_iterator<const _CharT&> auto __out_it,
272 __format_spec::__parsed_specifications<_CharT> __specs) -> decltype(__out_it) {
273 _LIBCPP_ASSERT_INTERNAL(!__specs.__has_precision(), "use __write_string");
274
275 // No padding -> copy the string
276 if (!__specs.__has_width())
277 return __formatter::__copy(__str, std::move(__out_it));
278
279 // Note when the estimated width is larger than size there's no padding. So
280 // there's no reason to get the real size when the estimate is larger than or
281 // equal to the minimum field width.
282 size_t __size =
283 __format_spec::__estimate_column_width(__str, __specs.__width_, __format_spec::__column_width_rounding::__up)
284 .__width_;
285 return __formatter::__write(__str, std::move(__out_it), __specs, __size);
286}
287
288template <class _CharT>
289int __truncate(basic_string_view<_CharT>& __str, int __precision) {
290 __format_spec::__column_width_result __result =
291 __format_spec::__estimate_column_width(__str, __precision, __format_spec::__column_width_rounding::__down);
292 __str = basic_string_view<_CharT>{__str.begin(), __result.__last_};
293 return __result.__width_;
294}
295
296} // namespace __formatter
297
298#endif // _LIBCPP_STD_VER >= 20
299
300_LIBCPP_END_NAMESPACE_STD
301
302_LIBCPP_POP_MACROS
303
304#endif // _LIBCPP___FORMAT_FORMATTER_OUTPUT_H
305