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_INTEGRAL_H
11 #define _LIBCPP___FORMAT_FORMATTER_INTEGRAL_H
12
13 #include <__charconv/to_chars_integral.h>
14 #include <__charconv/to_chars_result.h>
15 #include <__charconv/traits.h>
16 #include <__concepts/arithmetic.h>
17 #include <__concepts/same_as.h>
18 #include <__config>
19 #include <__format/concepts.h>
20 #include <__format/format_error.h>
21 #include <__format/formatter_output.h>
22 #include <__format/parser_std_format_spec.h>
23 #include <__system_error/errc.h>
24 #include <__type_traits/make_unsigned.h>
25 #include <__utility/unreachable.h>
26 #include <array>
27 #include <limits>
28 #include <string>
29 #include <string_view>
30
31 #ifndef _LIBCPP_HAS_NO_LOCALIZATION
32 # include <locale>
33 #endif
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
46 namespace __formatter {
47
48 //
49 // Generic
50 //
51
__insert_sign(char * __buf,bool __negative,__format_spec::__sign __sign)52 _LIBCPP_HIDE_FROM_ABI inline char* __insert_sign(char* __buf, bool __negative, __format_spec::__sign __sign) {
53 if (__negative)
54 *__buf++ = '-';
55 else
56 switch (__sign) {
57 case __format_spec::__sign::__default:
58 case __format_spec::__sign::__minus:
59 // No sign added.
60 break;
61 case __format_spec::__sign::__plus:
62 *__buf++ = '+';
63 break;
64 case __format_spec::__sign::__space:
65 *__buf++ = ' ';
66 break;
67 }
68
69 return __buf;
70 }
71
72 /**
73 * Determines the required grouping based on the size of the input.
74 *
75 * The grouping's last element will be repeated. For simplicity this repeating
76 * is unwrapped based on the length of the input. (When the input is short some
77 * groups are not processed.)
78 *
79 * @returns The size of the groups to write. This means the number of
80 * separator characters written is size() - 1.
81 *
82 * @note Since zero-sized groups cause issues they are silently ignored.
83 *
84 * @note The grouping field of the locale is always a @c std::string,
85 * regardless whether the @c std::numpunct's type is @c char or @c wchar_t.
86 */
__determine_grouping(ptrdiff_t __size,const string & __grouping)87 _LIBCPP_HIDE_FROM_ABI inline string __determine_grouping(ptrdiff_t __size, const string& __grouping) {
88 _LIBCPP_ASSERT(!__grouping.empty() && __size > __grouping[0],
89 "The slow grouping formatting is used while there will be no "
90 "separators written");
91 string __r;
92 auto __end = __grouping.end() - 1;
93 auto __ptr = __grouping.begin();
94
95 while (true) {
96 __size -= *__ptr;
97 if (__size > 0)
98 __r.push_back(*__ptr);
99 else {
100 // __size <= 0 so the value pushed will be <= *__ptr.
101 __r.push_back(*__ptr + __size);
102 return __r;
103 }
104
105 // Proceed to the next group.
106 if (__ptr != __end) {
107 do {
108 ++__ptr;
109 // Skip grouping with a width of 0.
110 } while (*__ptr == 0 && __ptr != __end);
111 }
112 }
113
114 __libcpp_unreachable();
115 }
116
117 //
118 // Char
119 //
120
121 template <__fmt_char_type _CharT>
122 _LIBCPP_HIDE_FROM_ABI auto __format_char(
123 integral auto __value,
124 output_iterator<const _CharT&> auto __out_it,
125 __format_spec::__parsed_specifications<_CharT> __specs) -> decltype(__out_it) {
126 using _Tp = decltype(__value);
127 if constexpr (!same_as<_CharT, _Tp>) {
128 // cmp_less and cmp_greater can't be used for character types.
129 if constexpr (signed_integral<_CharT> == signed_integral<_Tp>) {
130 if (__value < numeric_limits<_CharT>::min() || __value > numeric_limits<_CharT>::max())
131 std::__throw_format_error("Integral value outside the range of the char type");
132 } else if constexpr (signed_integral<_CharT>) {
133 // _CharT is signed _Tp is unsigned
134 if (__value > static_cast<make_unsigned_t<_CharT>>(numeric_limits<_CharT>::max()))
135 std::__throw_format_error("Integral value outside the range of the char type");
136 } else {
137 // _CharT is unsigned _Tp is signed
138 if (__value < 0 || static_cast<make_unsigned_t<_Tp>>(__value) > numeric_limits<_CharT>::max())
139 std::__throw_format_error("Integral value outside the range of the char type");
140 }
141 }
142
143 const auto __c = static_cast<_CharT>(__value);
144 return __formatter::__write(_VSTD::addressof(__c), _VSTD::addressof(__c) + 1, _VSTD::move(__out_it), __specs);
145 }
146
147 //
148 // Integer
149 //
150
151 /** Wrapper around @ref to_chars, returning the output pointer. */
152 template <integral _Tp>
__to_buffer(char * __first,char * __last,_Tp __value,int __base)153 _LIBCPP_HIDE_FROM_ABI char* __to_buffer(char* __first, char* __last, _Tp __value, int __base) {
154 // TODO FMT Evaluate code overhead due to not calling the internal function
155 // directly. (Should be zero overhead.)
156 to_chars_result __r = _VSTD::to_chars(__first, __last, __value, __base);
157 _LIBCPP_ASSERT(__r.ec == errc(0), "Internal buffer too small");
158 return __r.ptr;
159 }
160
161 /**
162 * Helper to determine the buffer size to output a integer in Base @em x.
163 *
164 * There are several overloads for the supported bases. The function uses the
165 * base as template argument so it can be used in a constant expression.
166 */
167 template <unsigned_integral _Tp, size_t _Base>
__buffer_size()168 consteval size_t __buffer_size() noexcept
169 requires(_Base == 2)
170 {
171 return numeric_limits<_Tp>::digits // The number of binary digits.
172 + 2 // Reserve space for the '0[Bb]' prefix.
173 + 1; // Reserve space for the sign.
174 }
175
176 template <unsigned_integral _Tp, size_t _Base>
__buffer_size()177 consteval size_t __buffer_size() noexcept
178 requires(_Base == 8)
179 {
180 return numeric_limits<_Tp>::digits // The number of binary digits.
181 / 3 // Adjust to octal.
182 + 1 // Turn floor to ceil.
183 + 1 // Reserve space for the '0' prefix.
184 + 1; // Reserve space for the sign.
185 }
186
187 template <unsigned_integral _Tp, size_t _Base>
__buffer_size()188 consteval size_t __buffer_size() noexcept
189 requires(_Base == 10)
190 {
191 return numeric_limits<_Tp>::digits10 // The floored value.
192 + 1 // Turn floor to ceil.
193 + 1; // Reserve space for the sign.
194 }
195
196 template <unsigned_integral _Tp, size_t _Base>
__buffer_size()197 consteval size_t __buffer_size() noexcept
198 requires(_Base == 16)
199 {
200 return numeric_limits<_Tp>::digits // The number of binary digits.
201 / 4 // Adjust to hexadecimal.
202 + 2 // Reserve space for the '0[Xx]' prefix.
203 + 1; // Reserve space for the sign.
204 }
205
206 template <unsigned_integral _Tp, class _CharT>
207 _LIBCPP_HIDE_FROM_ABI auto __format_integer(
208 _Tp __value,
209 auto& __ctx,
210 __format_spec::__parsed_specifications<_CharT> __specs,
211 bool __negative,
212 char* __begin,
213 char* __end,
214 const char* __prefix,
215 int __base) -> decltype(__ctx.out()) {
216 char* __first = __formatter::__insert_sign(__begin, __negative, __specs.__std_.__sign_);
217 if (__specs.__std_.__alternate_form_ && __prefix)
218 while (*__prefix)
219 *__first++ = *__prefix++;
220
221 char* __last = __formatter::__to_buffer(__first, __end, __value, __base);
222
223 # ifndef _LIBCPP_HAS_NO_LOCALIZATION
224 if (__specs.__std_.__locale_specific_form_) {
225 const auto& __np = std::use_facet<numpunct<_CharT>>(__ctx.locale());
226 string __grouping = __np.grouping();
227 ptrdiff_t __size = __last - __first;
228 // Writing the grouped form has more overhead than the normal output
229 // routines. If there will be no separators written the locale-specific
230 // form is identical to the normal routine. Test whether to grouped form
231 // is required.
232 if (!__grouping.empty() && __size > __grouping[0])
233 return __formatter::__write_using_decimal_separators(
234 __ctx.out(),
235 __begin,
236 __first,
237 __last,
238 __formatter::__determine_grouping(__size, __grouping),
239 __np.thousands_sep(),
240 __specs);
241 }
242 # endif
243 auto __out_it = __ctx.out();
244 if (__specs.__alignment_ != __format_spec::__alignment::__zero_padding)
245 __first = __begin;
246 else {
247 // __buf contains [sign][prefix]data
248 // ^ location of __first
249 // The zero padding is done like:
250 // - Write [sign][prefix]
251 // - Write data right aligned with '0' as fill character.
252 __out_it = __formatter::__copy(__begin, __first, _VSTD::move(__out_it));
253 __specs.__alignment_ = __format_spec::__alignment::__right;
254 __specs.__fill_ = _CharT('0');
255 int32_t __size = __first - __begin;
256
257 __specs.__width_ -= _VSTD::min(__size, __specs.__width_);
258 }
259
260 if (__specs.__std_.__type_ != __format_spec::__type::__hexadecimal_upper_case) [[likely]]
261 return __formatter::__write(__first, __last, __ctx.out(), __specs);
262
263 return __formatter::__write_transformed(__first, __last, __ctx.out(), __specs, __formatter::__hex_to_upper);
264 }
265
266 template <unsigned_integral _Tp, class _CharT>
267 _LIBCPP_HIDE_FROM_ABI auto __format_integer(
268 _Tp __value, auto& __ctx, __format_spec::__parsed_specifications<_CharT> __specs, bool __negative = false)
269 -> decltype(__ctx.out()) {
270 switch (__specs.__std_.__type_) {
271 case __format_spec::__type::__binary_lower_case: {
272 array<char, __formatter::__buffer_size<decltype(__value), 2>()> __array;
273 return __formatter::__format_integer(__value, __ctx, __specs, __negative, __array.begin(), __array.end(), "0b", 2);
274 }
275 case __format_spec::__type::__binary_upper_case: {
276 array<char, __formatter::__buffer_size<decltype(__value), 2>()> __array;
277 return __formatter::__format_integer(__value, __ctx, __specs, __negative, __array.begin(), __array.end(), "0B", 2);
278 }
279 case __format_spec::__type::__octal: {
280 // Octal is special; if __value == 0 there's no prefix.
281 array<char, __formatter::__buffer_size<decltype(__value), 8>()> __array;
282 return __formatter::__format_integer(
283 __value, __ctx, __specs, __negative, __array.begin(), __array.end(), __value != 0 ? "0" : nullptr, 8);
284 }
285 case __format_spec::__type::__default:
286 case __format_spec::__type::__decimal: {
287 array<char, __formatter::__buffer_size<decltype(__value), 10>()> __array;
288 return __formatter::__format_integer(
289 __value, __ctx, __specs, __negative, __array.begin(), __array.end(), nullptr, 10);
290 }
291 case __format_spec::__type::__hexadecimal_lower_case: {
292 array<char, __formatter::__buffer_size<decltype(__value), 16>()> __array;
293 return __formatter::__format_integer(__value, __ctx, __specs, __negative, __array.begin(), __array.end(), "0x", 16);
294 }
295 case __format_spec::__type::__hexadecimal_upper_case: {
296 array<char, __formatter::__buffer_size<decltype(__value), 16>()> __array;
297 return __formatter::__format_integer(__value, __ctx, __specs, __negative, __array.begin(), __array.end(), "0X", 16);
298 }
299 default:
300 _LIBCPP_ASSERT(false, "The parse function should have validated the type");
301 __libcpp_unreachable();
302 }
303 }
304
305 template <signed_integral _Tp, class _CharT>
306 _LIBCPP_HIDE_FROM_ABI auto
307 __format_integer(_Tp __value, auto& __ctx, __format_spec::__parsed_specifications<_CharT> __specs)
308 -> decltype(__ctx.out()) {
309 // Depending on the std-format-spec string the sign and the value
310 // might not be outputted together:
311 // - alternate form may insert a prefix string.
312 // - zero-padding may insert additional '0' characters.
313 // Therefore the value is processed as a positive unsigned value.
314 // The function @ref __insert_sign will a '-' when the value was negative.
315 auto __r = std::__to_unsigned_like(__value);
316 bool __negative = __value < 0;
317 if (__negative)
318 __r = std::__complement(__r);
319
320 return __formatter::__format_integer(__r, __ctx, __specs, __negative);
321 }
322
323 //
324 // Formatter arithmetic (bool)
325 //
326
327 template <class _CharT>
328 struct _LIBCPP_TEMPLATE_VIS __bool_strings;
329
330 template <>
331 struct _LIBCPP_TEMPLATE_VIS __bool_strings<char> {
332 static constexpr string_view __true{"true"};
333 static constexpr string_view __false{"false"};
334 };
335
336 # ifndef _LIBCPP_HAS_NO_WIDE_CHARACTERS
337 template <>
338 struct _LIBCPP_TEMPLATE_VIS __bool_strings<wchar_t> {
339 static constexpr wstring_view __true{L"true"};
340 static constexpr wstring_view __false{L"false"};
341 };
342 # endif
343
344 template <class _CharT>
345 _LIBCPP_HIDE_FROM_ABI auto
346 __format_bool(bool __value, auto& __ctx, __format_spec::__parsed_specifications<_CharT> __specs)
347 -> decltype(__ctx.out()) {
348 # ifndef _LIBCPP_HAS_NO_LOCALIZATION
349 if (__specs.__std_.__locale_specific_form_) {
350 const auto& __np = std::use_facet<numpunct<_CharT>>(__ctx.locale());
351 basic_string<_CharT> __str = __value ? __np.truename() : __np.falsename();
352 return __formatter::__write_string_no_precision(basic_string_view<_CharT>{__str}, __ctx.out(), __specs);
353 }
354 # endif
355 basic_string_view<_CharT> __str =
356 __value ? __formatter::__bool_strings<_CharT>::__true : __formatter::__bool_strings<_CharT>::__false;
357 return __formatter::__write(__str.begin(), __str.end(), __ctx.out(), __specs);
358 }
359
360 } // namespace __formatter
361
362 #endif //_LIBCPP_STD_VER >= 20
363
364 _LIBCPP_END_NAMESPACE_STD
365
366 _LIBCPP_POP_MACROS
367
368 #endif // _LIBCPP___FORMAT_FORMATTER_INTEGRAL_H
369