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