summaryrefslogtreecommitdiffstats
path: root/src/third-party/scnlib/src/reader_float.cpp
blob: 77c66a51db35acd6cca5d9ef9f1b6a4831958ad4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright 2017 Elias Kosunen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file is a part of scnlib:
//     https://github.com/eliaskosunen/scnlib

#if defined(SCN_HEADER_ONLY) && SCN_HEADER_ONLY
#define SCN_READER_FLOAT_CPP
#endif

#include <scn/detail/args.h>
#include <scn/reader/float.h>

#include <cerrno>
#include <clocale>

#if SCN_HAS_FLOAT_CHARCONV
#include <charconv>
#endif

SCN_GCC_PUSH
SCN_GCC_IGNORE("-Wold-style-cast")
SCN_GCC_IGNORE("-Wnoexcept")
SCN_GCC_IGNORE("-Wshift-count-overflow")
SCN_GCC_IGNORE("-Wsign-conversion")

SCN_CLANG_PUSH
SCN_CLANG_IGNORE("-Wold-style-cast")

#if SCN_CLANG >= SCN_COMPILER(13, 0, 0)
SCN_CLANG_IGNORE("-Wreserved-identifier")
#endif

#if SCN_CLANG >= SCN_COMPILER(10, 0, 0)
SCN_CLANG_IGNORE("-Wextra-semi-stmt")
#endif

#include <fast_float/fast_float.h>

SCN_CLANG_POP
SCN_GCC_POP

namespace scn {
    SCN_BEGIN_NAMESPACE

    namespace read_float {
        static bool is_hexfloat(const char* str, std::size_t len) noexcept
        {
            if (len < 3) {
                return false;
            }
            return str[0] == '0' && (str[1] == 'x' || str[1] == 'X');
        }
        static bool is_hexfloat(const wchar_t* str, std::size_t len) noexcept
        {
            if (len < 3) {
                return false;
            }
            return str[0] == L'0' && (str[1] == L'x' || str[1] == L'X');
        }

        namespace cstd {
#if SCN_GCC >= SCN_COMPILER(7, 0, 0)
            SCN_GCC_PUSH
            SCN_GCC_IGNORE("-Wnoexcept-type")
#endif
            template <typename T, typename CharT, typename F>
            expected<T> impl(F&& f_strtod,
                             T huge_value,
                             const CharT* str,
                             size_t& chars,
                             uint8_t options)
            {
                // Get current C locale
                const auto loc = std::setlocale(LC_NUMERIC, nullptr);
                // For whatever reason, this cannot be stored in the heap if
                // setlocale hasn't been called before, or msan errors with
                // 'use-of-unitialized-value' when resetting the locale back.
                // POSIX specifies that the content of loc may not be static, so
                // we need to save it ourselves
                char locbuf[64] = {0};
                std::strcpy(locbuf, loc);

                std::setlocale(LC_NUMERIC, "C");

                CharT* end{};
                errno = 0;
                T f = f_strtod(str, &end);
                chars = static_cast<size_t>(end - str);
                auto err = errno;
                // Reset locale
                std::setlocale(LC_NUMERIC, locbuf);
                errno = 0;

                SCN_GCC_COMPAT_PUSH
                SCN_GCC_COMPAT_IGNORE("-Wfloat-equal")
                // No conversion
                if (f == detail::zero_value<T>::value && chars == 0) {
                    return error(error::invalid_scanned_value, "strtod");
                }
                // Range error
                if (err == ERANGE) {
                    // Underflow
                    if (f == detail::zero_value<T>::value) {
                        return error(
                            error::value_out_of_range,
                            "Floating-point value out of range: underflow");
                    }
                    // Overflow
                    if (f == huge_value || f == -huge_value) {
                        return error(
                            error::value_out_of_range,
                            "Floating-point value out of range: overflow");
                    }
                    // Subnormals cause ERANGE but a value is still returned
                }

                if (is_hexfloat(str, detail::strlen(str)) &&
                    (options & detail::float_scanner<T>::allow_hex) == 0) {
                    return error(error::invalid_scanned_value,
                                 "Hexfloats not allowed by the format string");
                }

                SCN_GCC_COMPAT_POP
                return f;
            }
#if SCN_GCC >= SCN_COMPILER(7, 0, 0)
            SCN_GCC_POP
#endif

            template <typename CharT, typename T>
            struct read;

            template <>
            struct read<char, float> {
                static expected<float> get(const char* str,
                                           size_t& chars,
                                           uint8_t options)
                {
                    return impl<float>(strtof, HUGE_VALF, str, chars, options);
                }
            };

            template <>
            struct read<char, double> {
                static expected<double> get(const char* str,
                                            size_t& chars,
                                            uint8_t options)
                {
                    return impl<double>(strtod, HUGE_VAL, str, chars, options);
                }
            };

            template <>
            struct read<char, long double> {
                static expected<long double> get(const char* str,
                                                 size_t& chars,
                                                 uint8_t options)
                {
                    return impl<long double>(strtold, HUGE_VALL, str, chars,
                                             options);
                }
            };

            template <>
            struct read<wchar_t, float> {
                static expected<float> get(const wchar_t* str,
                                           size_t& chars,
                                           uint8_t options)
                {
                    return impl<float>(wcstof, HUGE_VALF, str, chars, options);
                }
            };
            template <>
            struct read<wchar_t, double> {
                static expected<double> get(const wchar_t* str,
                                            size_t& chars,
                                            uint8_t options)
                {
                    return impl<double>(wcstod, HUGE_VAL, str, chars, options);
                }
            };
            template <>
            struct read<wchar_t, long double> {
                static expected<long double> get(const wchar_t* str,
                                                 size_t& chars,
                                                 uint8_t options)
                {
                    return impl<long double>(wcstold, HUGE_VALL, str, chars,
                                             options);
                }
            };
        }  // namespace cstd

        namespace from_chars {
#if SCN_HAS_FLOAT_CHARCONV
            template <typename T>
            struct read {
                static expected<T> get(const char* str,
                                       size_t& chars,
                                       uint8_t options)
                {
                    const auto len = std::strlen(str);
                    std::chars_format flags{};
                    if (((options & detail::float_scanner<T>::allow_hex) !=
                         0) &&
                        is_hexfloat(str, len)) {
                        str += 2;
                        flags = std::chars_format::hex;
                    }
                    else {
                        if ((options & detail::float_scanner<T>::allow_fixed) !=
                            0) {
                            flags |= std::chars_format::fixed;
                        }
                        if ((options &
                             detail::float_scanner<T>::allow_scientific) != 0) {
                            flags |= std::chars_format::scientific;
                        }
                    }
                    if (flags == static_cast<std::chars_format>(0)) {
                        return error{error::invalid_scanned_value,
                                     "Expected a hexfloat"};
                    }

                    T value{};
                    const auto result =
                        std::from_chars(str, str + len, value, flags);
                    if (result.ec == std::errc::invalid_argument) {
                        return error(error::invalid_scanned_value,
                                     "from_chars");
                    }
                    if (result.ec == std::errc::result_out_of_range) {
                        // Out of range, may be subnormal -> fall back to strtod
                        // On gcc std::from_chars doesn't parse subnormals
                        return cstd::read<char, T>::get(str, chars, options);
                    }
                    chars = static_cast<size_t>(result.ptr - str);
                    return value;
                }
            };
#else
            template <typename T>
            struct read {
                static expected<T> get(const char* str,
                                       size_t& chars,
                                       uint8_t options)
                {
                    // Fall straight back to strtod
                    return cstd::read<char, T>::get(str, chars, options);
                }
            };
#endif
        }  // namespace from_chars

        namespace fast_float {
            template <typename T>
            expected<T> impl(const char* str,
                             size_t& chars,
                             uint8_t options,
                             char locale_decimal_point)
            {
                const auto len = std::strlen(str);
                if (((options & detail::float_scanner<T>::allow_hex) != 0) &&
                    is_hexfloat(str, len)) {
                    // fast_float doesn't support hexfloats
                    return from_chars::read<T>::get(str, chars, options);
                }

                T value{};
                ::fast_float::parse_options flags{};
                if ((options & detail::float_scanner<T>::allow_fixed) != 0) {
                    flags.format = ::fast_float::fixed;
                }
                if ((options & detail::float_scanner<T>::allow_scientific) !=
                    0) {
                    flags.format = static_cast<::fast_float::chars_format>(
                        flags.format | ::fast_float::scientific);
                }
                if ((options & detail::float_scanner<T>::localized) != 0) {
                    flags.decimal_point = locale_decimal_point;
                }

                const auto result = ::fast_float::from_chars_advanced(
                    str, str + len, value, flags);
                if (result.ec == std::errc::invalid_argument) {
                    return error(error::invalid_scanned_value, "fast_float");
                }
                if (result.ec == std::errc::result_out_of_range) {
                    return error(error::value_out_of_range, "fast_float");
                }
                if (std::isinf(value)) {
                    // fast_float represents very large or small values as inf
                    // But, it also parses "inf", which from_chars does not
                    if (!(len >= 3 && (str[0] == 'i' || str[0] == 'I'))) {
                        // Input was not actually infinity ->
                        // invalid result, fall back to from_chars
                        return from_chars::read<T>::get(str, chars, options);
                    }
                }
                chars = static_cast<size_t>(result.ptr - str);
                return value;
            }

            template <typename T>
            struct read;

            template <>
            struct read<float> {
                static expected<float> get(const char* str,
                                           size_t& chars,
                                           uint8_t options,
                                           char locale_decimal_point)
                {
                    return impl<float>(str, chars, options,
                                       locale_decimal_point);
                }
            };
            template <>
            struct read<double> {
                static expected<double> get(const char* str,
                                            size_t& chars,
                                            uint8_t options,
                                            char locale_decimal_points)
                {
                    return impl<double>(str, chars, options,
                                        locale_decimal_points);
                }
            };
            template <>
            struct read<long double> {
                static expected<long double> get(const char* str,
                                                 size_t& chars,
                                                 uint8_t options,
                                                 char)
                {
                    // Fallback to strtod
                    // fast_float doesn't support long double
                    return cstd::read<char, long double>::get(str, chars,
                                                              options);
                }
            };
        }  // namespace fast_float

        template <typename CharT, typename T>
        struct read;

        template <typename T>
        struct read<char, T> {
            static expected<T> get(const char* str,
                                   size_t& chars,
                                   uint8_t options,
                                   char locale_decimal_points)
            {
                // char -> default to fast_float,
                // fallback to strtod if necessary
                return read_float::fast_float::read<T>::get(
                    str, chars, options, locale_decimal_points);
            }
        };
        template <typename T>
        struct read<wchar_t, T> {
            static expected<T> get(const wchar_t* str,
                                   size_t& chars,
                                   uint8_t options,
                                   wchar_t)
            {
                // wchar_t -> straight to strtod
                return read_float::cstd::read<wchar_t, T>::get(str, chars,
                                                               options);
            }
        };
    }  // namespace read_float

    namespace detail {
        template <typename T>
        template <typename CharT>
        expected<T> float_scanner<T>::_read_float_impl(
            const CharT* str,
            size_t& chars,
            CharT locale_decimal_point)
        {
            // Parsing algorithm to use:
            // If CharT == wchar_t -> strtod
            // If CharT == char:
            //   1. fast_float
            //      fallback if a hex float, or incorrectly parsed an inf
            //      (very large or small value)
            //   2. std::from_chars
            //      fallback if not available (C++17) or float is subnormal
            //   3. std::strtod
            return read_float::read<CharT, T>::get(str, chars, format_options,
                                                   locale_decimal_point);
        }

#if SCN_INCLUDE_SOURCE_DEFINITIONS

        template expected<float>
        float_scanner<float>::_read_float_impl(const char*, size_t&, char);
        template expected<double>
        float_scanner<double>::_read_float_impl(const char*, size_t&, char);
        template expected<long double>
        float_scanner<long double>::_read_float_impl(const char*,
                                                     size_t&,
                                                     char);
        template expected<float> float_scanner<float>::_read_float_impl(
            const wchar_t*,
            size_t&,
            wchar_t);
        template expected<double> float_scanner<double>::_read_float_impl(
            const wchar_t*,
            size_t&,
            wchar_t);
        template expected<long double>
        float_scanner<long double>::_read_float_impl(const wchar_t*,
                                                     size_t&,
                                                     wchar_t);
#endif
    }  // namespace detail

    SCN_END_NAMESPACE
}  // namespace scn