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