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