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