DAW JSON Link
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 
11 #include "version.h"
12 
13 #include "daw_json_assert.h"
14 
15 #include <daw/daw_attributes.h>
16 #include <daw/daw_cpp_feature_check.h>
17 
18 #include <cstdlib>
19 #include <limits>
20 #include <system_error>
21 #include <type_traits>
22 
23 #if not defined( DAW_JSON_USE_STRTOD )
24 #include <charconv>
25 #endif
26 
27 namespace daw::json {
28  inline namespace DAW_JSON_VER {
29  namespace json_details {
34  template<typename Real>
35  DAW_ATTRIB_NOINLINE DAW_ATTRIB_NONNULL( ) [[nodiscard]] Real
36  parse_with_strtod( char const *first, char const *last ) {
37  static_assert( std::is_floating_point_v<Real>,
38  "Unexpected type passed to parse_with_strtod" );
39 #if defined( DAW_JSON_USE_STRTOD )
40  (void)last;
41  char **end = nullptr;
42  if constexpr( std::is_same_v<Real, float> ) {
43  return static_cast<Real>( std::strtof( first, end ) );
44  } else if( std::is_same_v<Real, double> ) {
45  return static_cast<Real>( std::strtod( first, end ) );
46  } else {
47  return static_cast<Real>( std::strtold( first, end ) );
48  }
49 #else
50  Real result;
51  auto fc_res = std::from_chars( first, last, result );
52  if( fc_res.ec == std::errc::result_out_of_range ) {
53  if( *first == '-' ) {
54  return -std::numeric_limits<Real>::infinity( );
55  }
56  return std::numeric_limits<Real>::infinity( );
57  }
58  daw_json_ensure( fc_res.ec == std::errc( ),
59  ErrorReason::InvalidNumber );
60  return result;
61 #endif
62  }
63  } // namespace json_details
64  } // namespace DAW_JSON_VER
65 } // 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:25