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