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