DAW JSON Link
Loading...
Searching...
No Matches
daw_fp_fallback.h
Go to the documentation of this file.
1// Copyright (c) Darrell Wright
2//
3// Distributed under the Boost Software License, Version 1.0. (See accompanying
4// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
5//
6// Official repository: https://github.com/beached/daw_json_link
7//
8
9#pragma once
10
12
14
15#include <daw/daw_attributes.h>
16#include <daw/daw_cpp_feature_check.h>
17#include <daw/daw_not_null.h>
18
19#include <cstdlib>
20#include <string>
21#include <system_error>
22#include <type_traits>
23
24#if not defined( DAW_JSON_USE_STRTOD )
25#include <charconv>
26#endif
27
28namespace daw::json {
29 inline namespace DAW_JSON_VER {
30 namespace json_details {
35 template<typename Real>
36 DAW_ATTRIB_NOINLINE [[nodiscard]] Real
37 parse_with_strtod( daw::not_null<char const *> first,
38 daw::not_null<char const *> last ) {
39 static_assert( std::is_floating_point_v<Real>,
40 "Unexpected type passed to parse_with_strtod" );
41#if defined( DAW_JSON_USE_STRTOD )
42 (void)last;
43 char **end = nullptr;
44 if constexpr( std::is_same_v<Real, float> ) {
45 return static_cast<Real>( std::strtof( first, end ) );
46 } else if( std::is_same_v<Real, double> ) {
47 return static_cast<Real>( std::strtod( first, end ) );
48 } else {
49 return static_cast<Real>( std::strtold( first, end ) );
50 }
51#else
52 Real result;
53 auto fc_res = std::from_chars( first, last, result );
54 if( fc_res.ec == std::errc::result_out_of_range ) {
55 // from_chars reports the same error for overflow and underflow.
56 // Retry this cold path with a bounded, null-terminated token so
57 // subnormal values are not incorrectly returned as infinity.
58 auto const token = std::string( first.get( ), last.get( ) );
59 if constexpr( std::is_same_v<Real, float> ) {
60 return std::strtof( token.c_str( ), nullptr );
61 } else if constexpr( std::is_same_v<Real, double> ) {
62 return std::strtod( token.c_str( ), nullptr );
63 } else {
64 return std::strtold( token.c_str( ), nullptr );
65 }
66 }
67 daw_json_ensure( fc_res.ec == std::errc( ),
68 ErrorReason::InvalidNumber );
69 return result;
70#endif
71 }
72 } // namespace json_details
73 } // namespace DAW_JSON_VER
74} // namespace daw::json
#define daw_json_ensure(Bool,...)
Ensure that Bool is true. If false pass rest of args to daw_json_error.
Customization point traits.
#define DAW_JSON_VER
The version string used in namespace definitions. Must be a valid namespace name.
Definition version.h:20