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