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