Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-03 08:13:50

0001 // -*- C++ -*-
0002 //===----------------------------------------------------------------------===//
0003 //
0004 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0005 // See https://llvm.org/LICENSE.txt for license information.
0006 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0007 //
0008 //===----------------------------------------------------------------------===//
0009 
0010 #ifndef _LIBCPP___FORMAT_FORMATTER_INTEGRAL_H
0011 #define _LIBCPP___FORMAT_FORMATTER_INTEGRAL_H
0012 
0013 #include <__charconv/to_chars_integral.h>
0014 #include <__charconv/to_chars_result.h>
0015 #include <__charconv/traits.h>
0016 #include <__concepts/arithmetic.h>
0017 #include <__concepts/same_as.h>
0018 #include <__config>
0019 #include <__format/concepts.h>
0020 #include <__format/format_error.h>
0021 #include <__format/formatter_output.h>
0022 #include <__format/parser_std_format_spec.h>
0023 #include <__iterator/concepts.h>
0024 #include <__iterator/iterator_traits.h>
0025 #include <__memory/pointer_traits.h>
0026 #include <__system_error/errc.h>
0027 #include <__type_traits/make_unsigned.h>
0028 #include <__utility/unreachable.h>
0029 #include <array>
0030 #include <cstdint>
0031 #include <limits>
0032 #include <string>
0033 #include <string_view>
0034 
0035 #if _LIBCPP_HAS_LOCALIZATION
0036 #  include <__locale>
0037 #endif
0038 
0039 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
0040 #  pragma GCC system_header
0041 #endif
0042 
0043 _LIBCPP_PUSH_MACROS
0044 #include <__undef_macros>
0045 
0046 _LIBCPP_BEGIN_NAMESPACE_STD
0047 
0048 #if _LIBCPP_STD_VER >= 20
0049 
0050 namespace __formatter {
0051 
0052 //
0053 // Generic
0054 //
0055 
0056 template <contiguous_iterator _Iterator>
0057   requires same_as<char, iter_value_t<_Iterator>>
0058 _LIBCPP_HIDE_FROM_ABI inline _Iterator __insert_sign(_Iterator __buf, bool __negative, __format_spec::__sign __sign) {
0059   if (__negative)
0060     *__buf++ = '-';
0061   else
0062     switch (__sign) {
0063     case __format_spec::__sign::__default:
0064     case __format_spec::__sign::__minus:
0065       // No sign added.
0066       break;
0067     case __format_spec::__sign::__plus:
0068       *__buf++ = '+';
0069       break;
0070     case __format_spec::__sign::__space:
0071       *__buf++ = ' ';
0072       break;
0073     }
0074 
0075   return __buf;
0076 }
0077 
0078 /**
0079  * Determines the required grouping based on the size of the input.
0080  *
0081  * The grouping's last element will be repeated. For simplicity this repeating
0082  * is unwrapped based on the length of the input. (When the input is short some
0083  * groups are not processed.)
0084  *
0085  * @returns The size of the groups to write. This means the number of
0086  * separator characters written is size() - 1.
0087  *
0088  * @note Since zero-sized groups cause issues they are silently ignored.
0089  *
0090  * @note The grouping field of the locale is always a @c std::string,
0091  * regardless whether the @c std::numpunct's type is @c char or @c wchar_t.
0092  */
0093 _LIBCPP_HIDE_FROM_ABI inline string __determine_grouping(ptrdiff_t __size, const string& __grouping) {
0094   _LIBCPP_ASSERT_INTERNAL(!__grouping.empty() && __size > __grouping[0],
0095                           "The slow grouping formatting is used while there will be no separators written");
0096   string __r;
0097   auto __end = __grouping.end() - 1;
0098   auto __ptr = __grouping.begin();
0099 
0100   while (true) {
0101     __size -= *__ptr;
0102     if (__size > 0)
0103       __r.push_back(*__ptr);
0104     else {
0105       // __size <= 0 so the value pushed will be <= *__ptr.
0106       __r.push_back(*__ptr + __size);
0107       return __r;
0108     }
0109 
0110     // Proceed to the next group.
0111     if (__ptr != __end) {
0112       do {
0113         ++__ptr;
0114         // Skip grouping with a width of 0.
0115       } while (*__ptr == 0 && __ptr != __end);
0116     }
0117   }
0118 
0119   __libcpp_unreachable();
0120 }
0121 
0122 //
0123 // Char
0124 //
0125 
0126 template <__fmt_char_type _CharT>
0127 _LIBCPP_HIDE_FROM_ABI auto
0128 __format_char(integral auto __value,
0129               output_iterator<const _CharT&> auto __out_it,
0130               __format_spec::__parsed_specifications<_CharT> __specs) -> decltype(__out_it) {
0131   using _Tp = decltype(__value);
0132   if constexpr (!same_as<_CharT, _Tp>) {
0133     // cmp_less and cmp_greater can't be used for character types.
0134     if constexpr (signed_integral<_CharT> == signed_integral<_Tp>) {
0135       if (__value < numeric_limits<_CharT>::min() || __value > numeric_limits<_CharT>::max())
0136         std::__throw_format_error("Integral value outside the range of the char type");
0137     } else if constexpr (signed_integral<_CharT>) {
0138       // _CharT is signed _Tp is unsigned
0139       if (__value > static_cast<make_unsigned_t<_CharT>>(numeric_limits<_CharT>::max()))
0140         std::__throw_format_error("Integral value outside the range of the char type");
0141     } else {
0142       // _CharT is unsigned _Tp is signed
0143       if (__value < 0 || static_cast<make_unsigned_t<_Tp>>(__value) > numeric_limits<_CharT>::max())
0144         std::__throw_format_error("Integral value outside the range of the char type");
0145     }
0146   }
0147 
0148   const auto __c = static_cast<_CharT>(__value);
0149   return __formatter::__write(std::addressof(__c), std::addressof(__c) + 1, std::move(__out_it), __specs);
0150 }
0151 
0152 //
0153 // Integer
0154 //
0155 
0156 /** Wrapper around @ref to_chars, returning the output iterator. */
0157 template <contiguous_iterator _Iterator, integral _Tp>
0158   requires same_as<char, iter_value_t<_Iterator>>
0159 _LIBCPP_HIDE_FROM_ABI _Iterator __to_buffer(_Iterator __first, _Iterator __last, _Tp __value, int __base) {
0160   // TODO FMT Evaluate code overhead due to not calling the internal function
0161   // directly. (Should be zero overhead.)
0162   to_chars_result __r = std::to_chars(std::to_address(__first), std::to_address(__last), __value, __base);
0163   _LIBCPP_ASSERT_INTERNAL(__r.ec == errc(0), "Internal buffer too small");
0164   auto __diff = __r.ptr - std::to_address(__first);
0165   return __first + __diff;
0166 }
0167 
0168 /**
0169  * Helper to determine the buffer size to output a integer in Base @em x.
0170  *
0171  * There are several overloads for the supported bases. The function uses the
0172  * base as template argument so it can be used in a constant expression.
0173  */
0174 template <unsigned_integral _Tp, size_t _Base>
0175 consteval size_t __buffer_size() noexcept
0176   requires(_Base == 2)
0177 {
0178   return numeric_limits<_Tp>::digits // The number of binary digits.
0179        + 2                           // Reserve space for the '0[Bb]' prefix.
0180        + 1;                          // Reserve space for the sign.
0181 }
0182 
0183 template <unsigned_integral _Tp, size_t _Base>
0184 consteval size_t __buffer_size() noexcept
0185   requires(_Base == 8)
0186 {
0187   return numeric_limits<_Tp>::digits // The number of binary digits.
0188            / 3                       // Adjust to octal.
0189        + 1                           // Turn floor to ceil.
0190        + 1                           // Reserve space for the '0' prefix.
0191        + 1;                          // Reserve space for the sign.
0192 }
0193 
0194 template <unsigned_integral _Tp, size_t _Base>
0195 consteval size_t __buffer_size() noexcept
0196   requires(_Base == 10)
0197 {
0198   return numeric_limits<_Tp>::digits10 // The floored value.
0199        + 1                             // Turn floor to ceil.
0200        + 1;                            // Reserve space for the sign.
0201 }
0202 
0203 template <unsigned_integral _Tp, size_t _Base>
0204 consteval size_t __buffer_size() noexcept
0205   requires(_Base == 16)
0206 {
0207   return numeric_limits<_Tp>::digits // The number of binary digits.
0208            / 4                       // Adjust to hexadecimal.
0209        + 2                           // Reserve space for the '0[Xx]' prefix.
0210        + 1;                          // Reserve space for the sign.
0211 }
0212 
0213 template <class _OutIt, contiguous_iterator _Iterator, class _CharT>
0214   requires same_as<char, iter_value_t<_Iterator>>
0215 _LIBCPP_HIDE_FROM_ABI _OutIt __write_using_decimal_separators(
0216     _OutIt __out_it,
0217     _Iterator __begin,
0218     _Iterator __first,
0219     _Iterator __last,
0220     string&& __grouping,
0221     _CharT __sep,
0222     __format_spec::__parsed_specifications<_CharT> __specs) {
0223   int __size = (__first - __begin) +    // [sign][prefix]
0224                (__last - __first) +     // data
0225                (__grouping.size() - 1); // number of separator characters
0226 
0227   __padding_size_result __padding = {0, 0};
0228   if (__specs.__alignment_ == __format_spec::__alignment::__zero_padding) {
0229     // Write [sign][prefix].
0230     __out_it = __formatter::__copy(__begin, __first, std::move(__out_it));
0231 
0232     if (__specs.__width_ > __size) {
0233       // Write zero padding.
0234       __padding.__before_ = __specs.__width_ - __size;
0235       __out_it            = __formatter::__fill(std::move(__out_it), __specs.__width_ - __size, _CharT('0'));
0236     }
0237   } else {
0238     if (__specs.__width_ > __size) {
0239       // Determine padding and write padding.
0240       __padding = __formatter::__padding_size(__size, __specs.__width_, __specs.__alignment_);
0241 
0242       __out_it = __formatter::__fill(std::move(__out_it), __padding.__before_, __specs.__fill_);
0243     }
0244     // Write [sign][prefix].
0245     __out_it = __formatter::__copy(__begin, __first, std::move(__out_it));
0246   }
0247 
0248   auto __r = __grouping.rbegin();
0249   auto __e = __grouping.rend() - 1;
0250   _LIBCPP_ASSERT_INTERNAL(
0251       __r != __e, "The slow grouping formatting is used while there will be no separators written.");
0252   // The output is divided in small groups of numbers to write:
0253   // - A group before the first separator.
0254   // - A separator and a group, repeated for the number of separators.
0255   // - A group after the last separator.
0256   // This loop achieves that process by testing the termination condition
0257   // midway in the loop.
0258   //
0259   // TODO FMT This loop evaluates the loop invariant `__parser.__type !=
0260   // _Flags::_Type::__hexadecimal_upper_case` for every iteration. (This test
0261   // happens in the __write call.) Benchmark whether making two loops and
0262   // hoisting the invariant is worth the effort.
0263   while (true) {
0264     if (__specs.__std_.__type_ == __format_spec::__type::__hexadecimal_upper_case) {
0265       __last   = __first + *__r;
0266       __out_it = __formatter::__transform(__first, __last, std::move(__out_it), __hex_to_upper);
0267       __first  = __last;
0268     } else {
0269       __out_it = __formatter::__copy(__first, *__r, std::move(__out_it));
0270       __first += *__r;
0271     }
0272 
0273     if (__r == __e)
0274       break;
0275 
0276     ++__r;
0277     *__out_it++ = __sep;
0278   }
0279 
0280   return __formatter::__fill(std::move(__out_it), __padding.__after_, __specs.__fill_);
0281 }
0282 
0283 template <unsigned_integral _Tp, contiguous_iterator _Iterator, class _CharT, class _FormatContext>
0284   requires same_as<char, iter_value_t<_Iterator>>
0285 _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator __format_integer(
0286     _Tp __value,
0287     _FormatContext& __ctx,
0288     __format_spec::__parsed_specifications<_CharT> __specs,
0289     bool __negative,
0290     _Iterator __begin,
0291     _Iterator __end,
0292     const char* __prefix,
0293     int __base) {
0294   _Iterator __first = __formatter::__insert_sign(__begin, __negative, __specs.__std_.__sign_);
0295   if (__specs.__std_.__alternate_form_ && __prefix)
0296     while (*__prefix)
0297       *__first++ = *__prefix++;
0298 
0299   _Iterator __last = __formatter::__to_buffer(__first, __end, __value, __base);
0300 
0301 #  if _LIBCPP_HAS_LOCALIZATION
0302   if (__specs.__std_.__locale_specific_form_) {
0303     const auto& __np  = std::use_facet<numpunct<_CharT>>(__ctx.locale());
0304     string __grouping = __np.grouping();
0305     ptrdiff_t __size  = __last - __first;
0306     // Writing the grouped form has more overhead than the normal output
0307     // routines. If there will be no separators written the locale-specific
0308     // form is identical to the normal routine. Test whether to grouped form
0309     // is required.
0310     if (!__grouping.empty() && __size > __grouping[0])
0311       return __formatter::__write_using_decimal_separators(
0312           __ctx.out(),
0313           __begin,
0314           __first,
0315           __last,
0316           __formatter::__determine_grouping(__size, __grouping),
0317           __np.thousands_sep(),
0318           __specs);
0319   }
0320 #  endif
0321   auto __out_it = __ctx.out();
0322   if (__specs.__alignment_ != __format_spec::__alignment::__zero_padding)
0323     __first = __begin;
0324   else {
0325     // __buf contains [sign][prefix]data
0326     //                              ^ location of __first
0327     // The zero padding is done like:
0328     // - Write [sign][prefix]
0329     // - Write data right aligned with '0' as fill character.
0330     __out_it                  = __formatter::__copy(__begin, __first, std::move(__out_it));
0331     __specs.__alignment_      = __format_spec::__alignment::__right;
0332     __specs.__fill_.__data[0] = _CharT('0');
0333     int32_t __size            = __first - __begin;
0334 
0335     __specs.__width_ -= std::min(__size, __specs.__width_);
0336   }
0337 
0338   if (__specs.__std_.__type_ != __format_spec::__type::__hexadecimal_upper_case) [[likely]]
0339     return __formatter::__write(__first, __last, __ctx.out(), __specs);
0340 
0341   return __formatter::__write_transformed(__first, __last, __ctx.out(), __specs, __formatter::__hex_to_upper);
0342 }
0343 
0344 template <unsigned_integral _Tp, class _CharT, class _FormatContext>
0345 _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator
0346 __format_integer(_Tp __value,
0347                  _FormatContext& __ctx,
0348                  __format_spec::__parsed_specifications<_CharT> __specs,
0349                  bool __negative = false) {
0350   switch (__specs.__std_.__type_) {
0351   case __format_spec::__type::__binary_lower_case: {
0352     array<char, __formatter::__buffer_size<decltype(__value), 2>()> __array;
0353     return __formatter::__format_integer(__value, __ctx, __specs, __negative, __array.begin(), __array.end(), "0b", 2);
0354   }
0355   case __format_spec::__type::__binary_upper_case: {
0356     array<char, __formatter::__buffer_size<decltype(__value), 2>()> __array;
0357     return __formatter::__format_integer(__value, __ctx, __specs, __negative, __array.begin(), __array.end(), "0B", 2);
0358   }
0359   case __format_spec::__type::__octal: {
0360     // Octal is special; if __value == 0 there's no prefix.
0361     array<char, __formatter::__buffer_size<decltype(__value), 8>()> __array;
0362     return __formatter::__format_integer(
0363         __value, __ctx, __specs, __negative, __array.begin(), __array.end(), __value != 0 ? "0" : nullptr, 8);
0364   }
0365   case __format_spec::__type::__default:
0366   case __format_spec::__type::__decimal: {
0367     array<char, __formatter::__buffer_size<decltype(__value), 10>()> __array;
0368     return __formatter::__format_integer(
0369         __value, __ctx, __specs, __negative, __array.begin(), __array.end(), nullptr, 10);
0370   }
0371   case __format_spec::__type::__hexadecimal_lower_case: {
0372     array<char, __formatter::__buffer_size<decltype(__value), 16>()> __array;
0373     return __formatter::__format_integer(__value, __ctx, __specs, __negative, __array.begin(), __array.end(), "0x", 16);
0374   }
0375   case __format_spec::__type::__hexadecimal_upper_case: {
0376     array<char, __formatter::__buffer_size<decltype(__value), 16>()> __array;
0377     return __formatter::__format_integer(__value, __ctx, __specs, __negative, __array.begin(), __array.end(), "0X", 16);
0378   }
0379   default:
0380     _LIBCPP_ASSERT_INTERNAL(false, "The parse function should have validated the type");
0381     __libcpp_unreachable();
0382   }
0383 }
0384 
0385 template <signed_integral _Tp, class _CharT, class _FormatContext>
0386 _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator
0387 __format_integer(_Tp __value, _FormatContext& __ctx, __format_spec::__parsed_specifications<_CharT> __specs) {
0388   // Depending on the std-format-spec string the sign and the value
0389   // might not be outputted together:
0390   // - alternate form may insert a prefix string.
0391   // - zero-padding may insert additional '0' characters.
0392   // Therefore the value is processed as a positive unsigned value.
0393   // The function @ref __insert_sign will a '-' when the value was negative.
0394   auto __r        = std::__to_unsigned_like(__value);
0395   bool __negative = __value < 0;
0396   if (__negative)
0397     __r = std::__complement(__r);
0398 
0399   return __formatter::__format_integer(__r, __ctx, __specs, __negative);
0400 }
0401 
0402 //
0403 // Formatter arithmetic (bool)
0404 //
0405 
0406 template <class _CharT>
0407 struct _LIBCPP_TEMPLATE_VIS __bool_strings;
0408 
0409 template <>
0410 struct _LIBCPP_TEMPLATE_VIS __bool_strings<char> {
0411   static constexpr string_view __true{"true"};
0412   static constexpr string_view __false{"false"};
0413 };
0414 
0415 #  if _LIBCPP_HAS_WIDE_CHARACTERS
0416 template <>
0417 struct _LIBCPP_TEMPLATE_VIS __bool_strings<wchar_t> {
0418   static constexpr wstring_view __true{L"true"};
0419   static constexpr wstring_view __false{L"false"};
0420 };
0421 #  endif
0422 
0423 template <class _CharT, class _FormatContext>
0424 _LIBCPP_HIDE_FROM_ABI typename _FormatContext::iterator
0425 __format_bool(bool __value, _FormatContext& __ctx, __format_spec::__parsed_specifications<_CharT> __specs) {
0426 #  if _LIBCPP_HAS_LOCALIZATION
0427   if (__specs.__std_.__locale_specific_form_) {
0428     const auto& __np           = std::use_facet<numpunct<_CharT>>(__ctx.locale());
0429     basic_string<_CharT> __str = __value ? __np.truename() : __np.falsename();
0430     return __formatter::__write_string_no_precision(basic_string_view<_CharT>{__str}, __ctx.out(), __specs);
0431   }
0432 #  endif
0433   basic_string_view<_CharT> __str =
0434       __value ? __formatter::__bool_strings<_CharT>::__true : __formatter::__bool_strings<_CharT>::__false;
0435   return __formatter::__write(__str.begin(), __str.end(), __ctx.out(), __specs);
0436 }
0437 
0438 } // namespace __formatter
0439 
0440 #endif // _LIBCPP_STD_VER >= 20
0441 
0442 _LIBCPP_END_NAMESPACE_STD
0443 
0444 _LIBCPP_POP_MACROS
0445 
0446 #endif // _LIBCPP___FORMAT_FORMATTER_INTEGRAL_H