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
106namespace __itoa {
107_LIBCPP_AVAILABILITY_TO_CHARS _LIBCPP_FUNC_VIS char* __u64toa(uint64_t __value, char* __buffer) _NOEXCEPT;
108_LIBCPP_AVAILABILITY_TO_CHARS _LIBCPP_FUNC_VIS char* __u32toa(uint32_t __value, char* __buffer) _NOEXCEPT;
109} // namespace __itoa
110
111#ifndef _LIBCPP_CXX03_LANG
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 _LIBCPP_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 _LIBCPP_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_INLINE_VISIBILITY int __width(_Tp __v)
155    {
156        auto __t = (64 - _VSTD::__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_INLINE_VISIBILITY char* __convert(_Tp __v, char* __p)
162    {
163        return __u64toa(__v, __p);
164    }
165
166    static _LIBCPP_INLINE_VISIBILITY 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_INLINE_VISIBILITY int __width(_Tp __v)
176    {
177        auto __t = (32 - _VSTD::__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_INLINE_VISIBILITY char* __convert(_Tp __v, char* __p)
183    {
184        return __u32toa(__v, __p);
185    }
186
187    static _LIBCPP_INLINE_VISIBILITY decltype(__pow10_32)& __pow() { return __pow10_32; }
188};
189
190template <typename _Tp>
191inline _LIBCPP_INLINE_VISIBILITY 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_INLINE_VISIBILITY 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_INLINE_VISIBILITY 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_INLINE_VISIBILITY 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 _LIBCPP_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_INLINE_VISIBILITY 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_INLINE_VISIBILITY _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_INLINE_VISIBILITY _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_INLINE_VISIBILITY 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_INLINE_VISIBILITY 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_INLINE_VISIBILITY 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_INLINE_VISIBILITY int __to_chars_integral_width(_Tp __value, unsigned __base) {
324  _LIBCPP_ASSERT(__value >= 0, "The function requires a non-negative value.");
325
326  unsigned __base_2 = __base * __base;
327  unsigned __base_3 = __base_2 * __base;
328  unsigned __base_4 = __base_2 * __base_2;
329
330  int __r = 0;
331  while (true) {
332    if (__value < __base)
333      return __r + 1;
334    if (__value < __base_2)
335      return __r + 2;
336    if (__value < __base_3)
337      return __r + 3;
338    if (__value < __base_4)
339      return __r + 4;
340
341    __value /= __base_4;
342    __r += 4;
343  }
344
345  __libcpp_unreachable();
346}
347
348template <typename _Tp>
349_LIBCPP_AVAILABILITY_TO_CHARS
350inline _LIBCPP_INLINE_VISIBILITY to_chars_result
351__to_chars_integral(char* __first, char* __last, _Tp __value, int __base,
352                    false_type)
353{
354  if (__base == 10)
355    return __to_chars_itoa(__first, __last, __value, false_type());
356
357  ptrdiff_t __cap = __last - __first;
358  int __n = __to_chars_integral_width(__value, __base);
359  if (__n > __cap)
360    return {__last, errc::value_too_large};
361
362  __last = __first + __n;
363  char* __p = __last;
364  do {
365    unsigned __c = __value % __base;
366    __value /= __base;
367    *--__p = "0123456789abcdefghijklmnopqrstuvwxyz"[__c];
368  } while (__value != 0);
369  return {__last, errc(0)};
370}
371
372template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
373_LIBCPP_AVAILABILITY_TO_CHARS
374inline _LIBCPP_INLINE_VISIBILITY to_chars_result
375to_chars(char* __first, char* __last, _Tp __value)
376{
377    return __to_chars_itoa(__first, __last, __value, is_signed<_Tp>());
378}
379
380template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
381_LIBCPP_AVAILABILITY_TO_CHARS
382inline _LIBCPP_INLINE_VISIBILITY to_chars_result
383to_chars(char* __first, char* __last, _Tp __value, int __base)
384{
385    _LIBCPP_ASSERT(2 <= __base && __base <= 36, "base not in [2, 36]");
386    return __to_chars_integral(__first, __last, __value, __base,
387                               is_signed<_Tp>());
388}
389
390template <typename _It, typename _Tp, typename _Fn, typename... _Ts>
391inline _LIBCPP_INLINE_VISIBILITY from_chars_result
392__sign_combinator(_It __first, _It __last, _Tp& __value, _Fn __f, _Ts... __args)
393{
394    using __tl = numeric_limits<_Tp>;
395    decltype(__to_unsigned_like(__value)) __x;
396
397    bool __neg = (__first != __last && *__first == '-');
398    auto __r = __f(__neg ? __first + 1 : __first, __last, __x, __args...);
399    switch (__r.ec)
400    {
401    case errc::invalid_argument:
402        return {__first, __r.ec};
403    case errc::result_out_of_range:
404        return __r;
405    default:
406        break;
407    }
408
409    if (__neg)
410    {
411        if (__x <= __complement(__to_unsigned_like(__tl::min())))
412        {
413            __x = __complement(__x);
414            _VSTD::memcpy(&__value, &__x, sizeof(__x));
415            return __r;
416        }
417    }
418    else
419    {
420        if (__x <= __tl::max())
421        {
422            __value = __x;
423            return __r;
424        }
425    }
426
427    return {__r.ptr, errc::result_out_of_range};
428}
429
430template <typename _Tp>
431inline _LIBCPP_INLINE_VISIBILITY bool
432__in_pattern(_Tp __c)
433{
434    return '0' <= __c && __c <= '9';
435}
436
437struct _LIBCPP_HIDDEN __in_pattern_result
438{
439    bool __ok;
440    int __val;
441
442    explicit _LIBCPP_INLINE_VISIBILITY operator bool() const { return __ok; }
443};
444
445template <typename _Tp>
446inline _LIBCPP_INLINE_VISIBILITY __in_pattern_result
447__in_pattern(_Tp __c, int __base)
448{
449    if (__base <= 10)
450        return {'0' <= __c && __c < '0' + __base, __c - '0'};
451    else if (__in_pattern(__c))
452        return {true, __c - '0'};
453    else if ('a' <= __c && __c < 'a' + __base - 10)
454        return {true, __c - 'a' + 10};
455    else
456        return {'A' <= __c && __c < 'A' + __base - 10, __c - 'A' + 10};
457}
458
459template <typename _It, typename _Tp, typename _Fn, typename... _Ts>
460inline _LIBCPP_INLINE_VISIBILITY from_chars_result
461__subject_seq_combinator(_It __first, _It __last, _Tp& __value, _Fn __f,
462                         _Ts... __args)
463{
464    auto __find_non_zero = [](_It __first, _It __last) {
465        for (; __first != __last; ++__first)
466            if (*__first != '0')
467                break;
468        return __first;
469    };
470
471    auto __p = __find_non_zero(__first, __last);
472    if (__p == __last || !__in_pattern(*__p, __args...))
473    {
474        if (__p == __first)
475            return {__first, errc::invalid_argument};
476        else
477        {
478            __value = 0;
479            return {__p, {}};
480        }
481    }
482
483    auto __r = __f(__p, __last, __value, __args...);
484    if (__r.ec == errc::result_out_of_range)
485    {
486        for (; __r.ptr != __last; ++__r.ptr)
487        {
488            if (!__in_pattern(*__r.ptr, __args...))
489                break;
490        }
491    }
492
493    return __r;
494}
495
496template <typename _Tp, typename enable_if<is_unsigned<_Tp>::value, int>::type = 0>
497inline _LIBCPP_INLINE_VISIBILITY from_chars_result
498__from_chars_atoi(const char* __first, const char* __last, _Tp& __value)
499{
500    using __tx = __itoa::__traits<_Tp>;
501    using __output_type = typename __tx::type;
502
503    return __subject_seq_combinator(
504        __first, __last, __value,
505        [](const char* __first, const char* __last,
506           _Tp& __value) -> from_chars_result {
507            __output_type __a, __b;
508            auto __p = __tx::__read(__first, __last, __a, __b);
509            if (__p == __last || !__in_pattern(*__p))
510            {
511                __output_type __m = numeric_limits<_Tp>::max();
512                if (__m >= __a && __m - __a >= __b)
513                {
514                    __value = __a + __b;
515                    return {__p, {}};
516                }
517            }
518            return {__p, errc::result_out_of_range};
519        });
520}
521
522template <typename _Tp, typename enable_if<is_signed<_Tp>::value, int>::type = 0>
523inline _LIBCPP_INLINE_VISIBILITY from_chars_result
524__from_chars_atoi(const char* __first, const char* __last, _Tp& __value)
525{
526    using __t = decltype(__to_unsigned_like(__value));
527    return __sign_combinator(__first, __last, __value, __from_chars_atoi<__t>);
528}
529
530template <typename _Tp, typename enable_if<is_unsigned<_Tp>::value, int>::type = 0>
531inline _LIBCPP_INLINE_VISIBILITY from_chars_result
532__from_chars_integral(const char* __first, const char* __last, _Tp& __value,
533                      int __base)
534{
535    if (__base == 10)
536        return __from_chars_atoi(__first, __last, __value);
537
538    return __subject_seq_combinator(
539        __first, __last, __value,
540        [](const char* __p, const char* __lastx, _Tp& __value,
541           int __base) -> from_chars_result {
542            using __tl = numeric_limits<_Tp>;
543            auto __digits = __tl::digits / log2f(float(__base));
544            _Tp __a = __in_pattern(*__p++, __base).__val, __b = 0;
545
546            for (int __i = 1; __p != __lastx; ++__i, ++__p)
547            {
548                if (auto __c = __in_pattern(*__p, __base))
549                {
550                    if (__i < __digits - 1)
551                        __a = __a * __base + __c.__val;
552                    else
553                    {
554                        if (!__itoa::__mul_overflowed(__a, __base, __a))
555                            ++__p;
556                        __b = __c.__val;
557                        break;
558                    }
559                }
560                else
561                    break;
562            }
563
564            if (__p == __lastx || !__in_pattern(*__p, __base))
565            {
566                if (__tl::max() - __a >= __b)
567                {
568                    __value = __a + __b;
569                    return {__p, {}};
570                }
571            }
572            return {__p, errc::result_out_of_range};
573        },
574        __base);
575}
576
577template <typename _Tp, typename enable_if<is_signed<_Tp>::value, int>::type = 0>
578inline _LIBCPP_INLINE_VISIBILITY from_chars_result
579__from_chars_integral(const char* __first, const char* __last, _Tp& __value,
580                      int __base)
581{
582    using __t = decltype(__to_unsigned_like(__value));
583    return __sign_combinator(__first, __last, __value,
584                             __from_chars_integral<__t>, __base);
585}
586
587template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
588inline _LIBCPP_INLINE_VISIBILITY from_chars_result
589from_chars(const char* __first, const char* __last, _Tp& __value)
590{
591    return __from_chars_atoi(__first, __last, __value);
592}
593
594template <typename _Tp, typename enable_if<is_integral<_Tp>::value, int>::type = 0>
595inline _LIBCPP_INLINE_VISIBILITY from_chars_result
596from_chars(const char* __first, const char* __last, _Tp& __value, int __base)
597{
598    _LIBCPP_ASSERT(2 <= __base && __base <= 36, "base not in [2, 36]");
599    return __from_chars_integral(__first, __last, __value, __base);
600}
601
602// Floating-point implementation starts here.
603// Unlike the other parts of charconv this is only available in C++17 and newer.
604#if _LIBCPP_STD_VER > 14
605
606_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
607to_chars_result to_chars(char* __first, char* __last, float __value);
608
609_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
610to_chars_result to_chars(char* __first, char* __last, double __value);
611
612_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
613to_chars_result to_chars(char* __first, char* __last, long double __value);
614
615_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
616to_chars_result to_chars(char* __first, char* __last, float __value, chars_format __fmt);
617
618_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
619to_chars_result to_chars(char* __first, char* __last, double __value, chars_format __fmt);
620
621_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
622to_chars_result to_chars(char* __first, char* __last, long double __value, chars_format __fmt);
623
624_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
625to_chars_result to_chars(char* __first, char* __last, float __value, chars_format __fmt, int __precision);
626
627_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
628to_chars_result to_chars(char* __first, char* __last, double __value, chars_format __fmt, int __precision);
629
630_LIBCPP_AVAILABILITY_TO_CHARS_FLOATING_POINT _LIBCPP_FUNC_VIS
631to_chars_result to_chars(char* __first, char* __last, long double __value, chars_format __fmt, int __precision);
632
633#  endif // _LIBCPP_STD_VER > 14
634#endif // _LIBCPP_CXX03_LANG
635
636_LIBCPP_END_NAMESPACE_STD
637
638_LIBCPP_POP_MACROS
639
640#endif // _LIBCPP_CHARCONV
641