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_CHARCONV
11#define _LIBCPP_CHARCONV
12
13/*
14    charconv synopsis
15
16namespace std {
17
18  // floating-point format for primitive numerical conversion
19  enum class chars_format {
20    scientific = unspecified,
21    fixed = unspecified,
22    hex = unspecified,
23    general = fixed | scientific
24  };
25
26  // 23.20.2, primitive numerical output conversion
27  struct to_chars_result {
28    char* ptr;
29    errc ec;
30    friend bool operator==(const to_chars_result&, const to_chars_result&) = default; // since C++20
31  };
32
33  to_chars_result to_chars(char* first, char* last, see below value,
34                           int base = 10);
35  to_chars_result to_chars(char* first, char* last, bool value,
36                           int base = 10) = delete;
37
38  to_chars_result to_chars(char* first, char* last, float value);
39  to_chars_result to_chars(char* first, char* last, double value);
40  to_chars_result to_chars(char* first, char* last, long double value);
41
42  to_chars_result to_chars(char* first, char* last, float value,
43                           chars_format fmt);
44  to_chars_result to_chars(char* first, char* last, double value,
45                           chars_format fmt);
46  to_chars_result to_chars(char* first, char* last, long double value,
47                           chars_format fmt);
48
49  to_chars_result to_chars(char* first, char* last, float value,
50                           chars_format fmt, int precision);
51  to_chars_result to_chars(char* first, char* last, double value,
52                           chars_format fmt, int precision);
53  to_chars_result to_chars(char* first, char* last, long double value,
54                           chars_format fmt, int precision);
55
56  // 23.20.3, primitive numerical input conversion
57  struct from_chars_result {
58    const char* ptr;
59    errc ec;
60    friend bool operator==(const from_chars_result&, const from_chars_result&) = default; // since C++20
61  };
62
63  from_chars_result from_chars(const char* first, const char* last,
64                               see below& value, int base = 10);
65
66  from_chars_result from_chars(const char* first, const char* last,
67                               float& value,
68                               chars_format fmt = chars_format::general);
69  from_chars_result from_chars(const char* first, const char* last,
70                               double& value,
71                               chars_format fmt = chars_format::general);
72  from_chars_result from_chars(const char* first, const char* last,
73                               long double& value,
74                               chars_format fmt = chars_format::general);
75
76} // namespace std
77
78*/
79
80#include <__assert>
81#include <__availability>
82#include <__bits>
83#include <__charconv/chars_format.h>
84#include <__charconv/from_chars_result.h>
85#include <__charconv/to_chars_result.h>
86#include <__config>
87#include <__debug>
88#include <__errc>
89#include <__utility/unreachable.h>
90#include <cmath> // for log2f
91#include <cstdint>
92#include <cstdlib>
93#include <cstring>
94#include <limits>
95#include <type_traits>
96
97#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
98#  pragma GCC system_header
99#endif
100
101_LIBCPP_PUSH_MACROS
102#include <__undef_macros>
103
104_LIBCPP_BEGIN_NAMESPACE_STD
105
106#ifndef _LIBCPP_CXX03_LANG
107
108namespace __itoa {
109_LIBCPP_AVAILABILITY_TO_CHARS _LIBCPP_FUNC_VIS char* __u64toa(uint64_t __value, char* __buffer) noexcept;
110_LIBCPP_AVAILABILITY_TO_CHARS _LIBCPP_FUNC_VIS char* __u32toa(uint32_t __value, char* __buffer) noexcept;
111} // namespace __itoa
112
113to_chars_result to_chars(char*, char*, bool, int = 10) = delete;
114from_chars_result from_chars(const char*, const char*, bool, int = 10) = delete;
115
116namespace __itoa
117{
118
119static constexpr uint64_t __pow10_64[] = {
120    UINT64_C(0),
121    UINT64_C(10),
122    UINT64_C(100),
123    UINT64_C(1000),
124    UINT64_C(10000),
125    UINT64_C(100000),
126    UINT64_C(1000000),
127    UINT64_C(10000000),
128    UINT64_C(100000000),
129    UINT64_C(1000000000),
130    UINT64_C(10000000000),
131    UINT64_C(100000000000),
132    UINT64_C(1000000000000),
133    UINT64_C(10000000000000),
134    UINT64_C(100000000000000),
135    UINT64_C(1000000000000000),
136    UINT64_C(10000000000000000),
137    UINT64_C(100000000000000000),
138    UINT64_C(1000000000000000000),
139    UINT64_C(10000000000000000000),
140};
141
142static constexpr uint32_t __pow10_32[] = {
143    UINT32_C(0),          UINT32_C(10),       UINT32_C(100),
144    UINT32_C(1000),       UINT32_C(10000),    UINT32_C(100000),
145    UINT32_C(1000000),    UINT32_C(10000000), UINT32_C(100000000),
146    UINT32_C(1000000000),
147};
148
149template <typename _Tp, typename = void>
150struct _LIBCPP_HIDDEN __traits_base
151{
152    using type = uint64_t;
153
154    static _LIBCPP_HIDE_FROM_ABI int __width(_Tp __v)
155    {
156        auto __t = (64 - std::__libcpp_clz(static_cast<type>(__v | 1))) * 1233 >> 12;
157        return __t - (__v < __pow10_64[__t]) + 1;
158    }
159
160    _LIBCPP_AVAILABILITY_TO_CHARS
161    static _LIBCPP_HIDE_FROM_ABI char* __convert(_Tp __v, char* __p)
162    {
163        return __u64toa(__v, __p);
164    }
165
166    static _LIBCPP_HIDE_FROM_ABI decltype(__pow10_64)& __pow() { return __pow10_64; }
167};
168
169template <typename _Tp>
170struct _LIBCPP_HIDDEN
171    __traits_base<_Tp, decltype(void(uint32_t{declval<_Tp>()}))>
172{
173    using type = uint32_t;
174
175    static _LIBCPP_HIDE_FROM_ABI int __width(_Tp __v)
176    {
177        auto __t = (32 - std::__libcpp_clz(static_cast<type>(__v | 1))) * 1233 >> 12;
178        return __t - (__v < __pow10_32[__t]) + 1;
179    }
180
181    _LIBCPP_AVAILABILITY_TO_CHARS
182    static _LIBCPP_HIDE_FROM_ABI char* __convert(_Tp __v, char* __p)
183    {
184        return __u32toa(__v, __p);
185    }
186
187    static _LIBCPP_HIDE_FROM_ABI decltype(__pow10_32)& __pow() { return __pow10_32; }
188};
189
190template <typename _Tp>
191inline _LIBCPP_HIDE_FROM_ABI bool
192__mul_overflowed(unsigned char __a, _Tp __b, unsigned char& __r)
193{
194    auto __c = __a * __b;
195    __r = __c;
196    return __c > numeric_limits<unsigned char>::max();
197}
198
199template <typename _Tp>
200inline _LIBCPP_HIDE_FROM_ABI bool
201__mul_overflowed(unsigned short __a, _Tp __b, unsigned short& __r)
202{
203    auto __c = __a * __b;
204    __r = __c;
205    return __c > numeric_limits<unsigned short>::max();
206}
207
208template <typename _Tp>
209inline _LIBCPP_HIDE_FROM_ABI bool
210__mul_overflowed(_Tp __a, _Tp __b, _Tp& __r)
211{
212    static_assert(is_unsigned<_Tp>::value, "");
213#if !defined(_LIBCPP_COMPILER_MSVC)
214    return __builtin_mul_overflow(__a, __b, &__r);
215#else
216    bool __did = __b && (numeric_limits<_Tp>::max() / __b) < __a;
217    __r = __a * __b;
218    return __did;
219#endif
220}
221
222template <typename _Tp, typename _Up>
223inline _LIBCPP_HIDE_FROM_ABI bool
224__mul_overflowed(_Tp __a, _Up __b, _Tp& __r)
225{
226    return __mul_overflowed(__a, static_cast<_Tp>(__b), __r);
227}
228
229template <typename _Tp>
230struct _LIBCPP_HIDDEN __traits : __traits_base<_Tp>
231{
232    static constexpr int digits = numeric_limits<_Tp>::digits10 + 1;
233    using __traits_base<_Tp>::__pow;
234    using typename __traits_base<_Tp>::type;
235
236    // precondition: at least one non-zero character available
237    static _LIBCPP_HIDE_FROM_ABI char const*
238    __read(char const* __p, char const* __ep, type& __a, type& __b)
239    {
240        type __cprod[digits];
241        int __j = digits - 1;
242        int __i = digits;
243        do
244        {
245            if (!('0' <= *__p && *__p <= '9'))
246                break;
247            __cprod[--__i] = *__p++ - '0';
248        } while (__p != __ep && __i != 0);
249
250        __a = __inner_product(__cprod + __i + 1, __cprod + __j, __pow() + 1,
251                              __cprod[__i]);
252        if (__mul_overflowed(__cprod[__j], __pow()[__j - __i], __b))
253            --__p;
254        return __p;
255    }
256
257    template <typename _It1, typename _It2, class _Up>
258    static _LIBCPP_HIDE_FROM_ABI _Up
259    __inner_product(_It1 __first1, _It1 __last1, _It2 __first2, _Up __init)
260    {
261        for (; __first1 < __last1; ++__first1, ++__first2)
262            __init = __init + *__first1 * *__first2;
263        return __init;
264    }
265};
266
267}  // namespace __itoa
268
269template <typename _Tp>
270inline _LIBCPP_HIDE_FROM_ABI _Tp
271__complement(_Tp __x)
272{
273    static_assert(is_unsigned<_Tp>::value, "cast to unsigned first");
274    return _Tp(~__x + 1);
275}
276
277template <typename _Tp>
278_LIBCPP_AVAILABILITY_TO_CHARS
279inline _LIBCPP_HIDE_FROM_ABI to_chars_result
280__to_chars_itoa(char* __first, char* __last, _Tp __value, true_type)
281{
282    auto __x = __to_unsigned_like(__value);
283    if (__value < 0 && __first != __last)
284    {
285        *__first++ = '-';
286        __x = __complement(__x);
287    }
288
289    return __to_chars_itoa(__first, __last, __x, false_type());
290}
291
292template <typename _Tp>
293_LIBCPP_AVAILABILITY_TO_CHARS
294inline _LIBCPP_HIDE_FROM_ABI to_chars_result
295__to_chars_itoa(char* __first, char* __last, _Tp __value, false_type)
296{
297    using __tx = __itoa::__traits<_Tp>;
298    auto __diff = __last - __first;
299
300    if (__tx::digits <= __diff || __tx::__width(__value) <= __diff)
301        return {__tx::__convert(__value, __first), errc(0)};
302    else
303        return {__last, errc::value_too_large};
304}
305
306template <typename _Tp>
307_LIBCPP_AVAILABILITY_TO_CHARS
308inline _LIBCPP_HIDE_FROM_ABI to_chars_result
309__to_chars_integral(char* __first, char* __last, _Tp __value, int __base,
310                    true_type)
311{
312    auto __x = __to_unsigned_like(__value);
313    if (__value < 0 && __first != __last)
314    {
315        *__first++ = '-';
316        __x = __complement(__x);
317    }
318
319    return __to_chars_integral(__first, __last, __x, __base, false_type());
320}
321
322template <typename _Tp>
323_LIBCPP_AVAILABILITY_TO_CHARS _LIBCPP_HIDE_FROM_ABI int
324__to_chars_integral_width(_Tp __value, unsigned __base) {
325  _LIBCPP_ASSERT(__value >= 0, "The function requires a non-negative value.");
326
327  unsigned __base_2 = __base * __base;
328  unsigned __base_3 = __base_2 * __base;
329  unsigned __base_4 = __base_2 * __base_2;
330
331  int __r = 0;
332  while (true) {
333    if (__value < __base)
334      return __r + 1;
335    if (__value < __base_2)
336      return __r + 2;
337    if (__value < __base_3)
338      return __r + 3;
339    if (__value < __base_4)
340      return __r + 4;
341
342    __value /= __base_4;
343    __r += 4;
344  }
345
346  __libcpp_unreachable();
347}
348
349template <typename _Tp>
350_LIBCPP_AVAILABILITY_TO_CHARS
351inline _LIBCPP_HIDE_FROM_ABI to_chars_result
352__to_chars_integral(char* __first, char* __last, _Tp __value, int __base,
353                    false_type)
354{
355  if (__base == 10)
356    return __to_chars_itoa(__first, __last, __value, false_type());
357
358  ptrdiff_t __cap = __last - __first;
359  int __n = __to_chars_integral_width(__value, __base);
360  if (__n > __cap)
361    return {__last, errc::value_too_large};
362
363  __last = __first + __n;
364  char* __p = __last;
365  do {
366    unsigned __c = __value % __base;
367    __value /= __base;
368    *--__p = "0123456789abcdefghijklmnopqrstuvwxyz"[__c];
369  } while (__value != 0);
370  return {__last, errc(0)};
371}
372
373template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
374_LIBCPP_AVAILABILITY_TO_CHARS
375inline _LIBCPP_HIDE_FROM_ABI to_chars_result
376to_chars(char* __first, char* __last, _Tp __value)
377{
378    return __to_chars_itoa(__first, __last, __value, is_signed<_Tp>());
379}
380
381template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
382_LIBCPP_AVAILABILITY_TO_CHARS
383inline _LIBCPP_HIDE_FROM_ABI to_chars_result
384to_chars(char* __first, char* __last, _Tp __value, int __base)
385{
386    _LIBCPP_ASSERT(2 <= __base && __base <= 36, "base not in [2, 36]");
387    return __to_chars_integral(__first, __last, __value, __base,
388                               is_signed<_Tp>());
389}
390
391template <typename _It, typename _Tp, typename _Fn, typename... _Ts>
392inline _LIBCPP_HIDE_FROM_ABI from_chars_result
393__sign_combinator(_It __first, _It __last, _Tp& __value, _Fn __f, _Ts... __args)
394{
395    using __tl = numeric_limits<_Tp>;
396    decltype(__to_unsigned_like(__value)) __x;
397
398    bool __neg = (__first != __last && *__first == '-');
399    auto __r = __f(__neg ? __first + 1 : __first, __last, __x, __args...);
400    switch (__r.ec)
401    {
402    case errc::invalid_argument:
403        return {__first, __r.ec};
404    case errc::result_out_of_range:
405        return __r;
406    default:
407        break;
408    }
409
410    if (__neg)
411    {
412        if (__x <= __complement(__to_unsigned_like(__tl::min())))
413        {
414            __x = __complement(__x);
415            std::memcpy(&__value, &__x, sizeof(__x));
416            return __r;
417        }
418    }
419    else
420    {
421        if (__x <= __tl::max())
422        {
423            __value = __x;
424            return __r;
425        }
426    }
427
428    return {__r.ptr, errc::result_out_of_range};
429}
430
431template <typename _Tp>
432inline _LIBCPP_HIDE_FROM_ABI bool
433__in_pattern(_Tp __c)
434{
435    return '0' <= __c && __c <= '9';
436}
437
438struct _LIBCPP_HIDDEN __in_pattern_result
439{
440    bool __ok;
441    int __val;
442
443    explicit _LIBCPP_HIDE_FROM_ABI operator bool() const { return __ok; }
444};
445
446template <typename _Tp>
447inline _LIBCPP_HIDE_FROM_ABI __in_pattern_result
448__in_pattern(_Tp __c, int __base)
449{
450    if (__base <= 10)
451        return {'0' <= __c && __c < '0' + __base, __c - '0'};
452    else if (__in_pattern(__c))
453        return {true, __c - '0'};
454    else if ('a' <= __c && __c < 'a' + __base - 10)
455        return {true, __c - 'a' + 10};
456    else
457        return {'A' <= __c && __c < 'A' + __base - 10, __c - 'A' + 10};
458}
459
460template <typename _It, typename _Tp, typename _Fn, typename... _Ts>
461inline _LIBCPP_HIDE_FROM_ABI from_chars_result
462__subject_seq_combinator(_It __first, _It __last, _Tp& __value, _Fn __f,
463                         _Ts... __args)
464{
465    auto __find_non_zero = [](_It __first, _It __last) {
466        for (; __first != __last; ++__first)
467            if (*__first != '0')
468                break;
469        return __first;
470    };
471
472    auto __p = __find_non_zero(__first, __last);
473    if (__p == __last || !__in_pattern(*__p, __args...))
474    {
475        if (__p == __first)
476            return {__first, errc::invalid_argument};
477        else
478        {
479            __value = 0;
480            return {__p, {}};
481        }
482    }
483
484    auto __r = __f(__p, __last, __value, __args...);
485    if (__r.ec == errc::result_out_of_range)
486    {
487        for (; __r.ptr != __last; ++__r.ptr)
488        {
489            if (!__in_pattern(*__r.ptr, __args...))
490                break;
491        }
492    }
493
494    return __r;
495}
496
497template <typename _Tp, typename enable_if<is_unsigned<_Tp>::value, int>::type = 0>
498inline _LIBCPP_HIDE_FROM_ABI from_chars_result
499__from_chars_atoi(const char* __first, const char* __last, _Tp& __value)
500{
501    using __tx = __itoa::__traits<_Tp>;
502    using __output_type = typename __tx::type;
503
504    return __subject_seq_combinator(
505        __first, __last, __value,
506        [](const char* __first, const char* __last,
507           _Tp& __value) -> from_chars_result {
508            __output_type __a, __b;
509            auto __p = __tx::__read(__first, __last, __a, __b);
510            if (__p == __last || !__in_pattern(*__p))
511            {
512                __output_type __m = numeric_limits<_Tp>::max();
513                if (__m >= __a && __m - __a >= __b)
514                {
515                    __value = __a + __b;
516                    return {__p, {}};
517                }
518            }
519            return {__p, errc::result_out_of_range};
520        });
521}
522
523template <typename _Tp, typename enable_if<is_signed<_Tp>::value, int>::type = 0>
524inline _LIBCPP_HIDE_FROM_ABI from_chars_result
525__from_chars_atoi(const char* __first, const char* __last, _Tp& __value)
526{
527    using __t = decltype(__to_unsigned_like(__value));
528    return __sign_combinator(__first, __last, __value, __from_chars_atoi<__t>);
529}
530
531template <typename _Tp, typename enable_if<is_unsigned<_Tp>::value, int>::type = 0>
532inline _LIBCPP_HIDE_FROM_ABI from_chars_result
533__from_chars_integral(const char* __first, const char* __last, _Tp& __value,
534                      int __base)
535{
536    if (__base == 10)
537        return __from_chars_atoi(__first, __last, __value);
538
539    return __subject_seq_combinator(
540        __first, __last, __value,
541        [](const char* __p, const char* __lastx, _Tp& __value,
542           int __base) -> from_chars_result {
543            using __tl = numeric_limits<_Tp>;
544            auto __digits = __tl::digits / log2f(float(__base));
545            _Tp __a = __in_pattern(*__p++, __base).__val, __b = 0;
546
547            for (int __i = 1; __p != __lastx; ++__i, ++__p)
548            {
549                if (auto __c = __in_pattern(*__p, __base))
550                {
551                    if (__i < __digits - 1)
552                        __a = __a * __base + __c.__val;
553                    else
554                    {
555                        if (!__itoa::__mul_overflowed(__a, __base, __a))
556                            ++__p;
557                        __b = __c.__val;
558                        break;
559                    }
560                }
561                else
562                    break;
563            }
564
565            if (__p == __lastx || !__in_pattern(*__p, __base))
566            {
567                if (__tl::max() - __a >= __b)
568                {
569                    __value = __a + __b;
570                    return {__p, {}};
571                }
572            }
573            return {__p, errc::result_out_of_range};
574        },
575        __base);
576}
577
578template <typename _Tp, typename enable_if<is_signed<_Tp>::value, int>::type = 0>
579inline _LIBCPP_HIDE_FROM_ABI from_chars_result
580__from_chars_integral(const char* __first, const char* __last, _Tp& __value,
581                      int __base)
582{
583    using __t = decltype(__to_unsigned_like(__value));
584    return __sign_combinator(__first, __last, __value,
585                             __from_chars_integral<__t>, __base);
586}
587
588template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
589inline _LIBCPP_HIDE_FROM_ABI from_chars_result
590from_chars(const char* __first, const char* __last, _Tp& __value)
591{
592    return __from_chars_atoi(__first, __last, __value);
593}
594
595template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
596inline _LIBCPP_HIDE_FROM_ABI from_chars_result
597from_chars(const char* __first, const char* __last, _Tp& __value, int __base)
598{
599    _LIBCPP_ASSERT(2 <= __base && __base <= 36, "base not in [2, 36]");
600    return __from_chars_integral(__first, __last, __value, __base);
601}
602
603// Floating-point implementation starts here.
604// Unlike the other parts of charconv this is only available in C++17 and newer.
605#if _LIBCPP_STD_VER > 14
606
607_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
608to_chars_result to_chars(char* __first, char* __last, float __value);
609
610_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
611to_chars_result to_chars(char* __first, char* __last, double __value);
612
613_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
614to_chars_result to_chars(char* __first, char* __last, long double __value);
615
616_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
617to_chars_result to_chars(char* __first, char* __last, float __value, chars_format __fmt);
618
619_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
620to_chars_result to_chars(char* __first, char* __last, double __value, chars_format __fmt);
621
622_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
623to_chars_result to_chars(char* __first, char* __last, long double __value, chars_format __fmt);
624
625_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
626to_chars_result to_chars(char* __first, char* __last, float __value, chars_format __fmt, int __precision);
627
628_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
629to_chars_result to_chars(char* __first, char* __last, double __value, chars_format __fmt, int __precision);
630
631_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
632to_chars_result to_chars(char* __first, char* __last, long double __value, chars_format __fmt, int __precision);
633
634#  endif // _LIBCPP_STD_VER > 14
635#endif // _LIBCPP_CXX03_LANG
636
637_LIBCPP_END_NAMESPACE_STD
638
639_LIBCPP_POP_MACROS
640
641#endif // _LIBCPP_CHARCONV
642