1 // Copyright 2018 Ulf Adams
3 // The contents of this file may be used under the terms of the Apache License,
6 // (See accompanying file LICENSE-Apache or copy at
7 // http://www.apache.org/licenses/LICENSE-2.0)
9 // Alternatively, the contents of this file may be used under the terms of
10 // the Boost Software License, Version 1.0.
11 // (See accompanying file LICENSE-Boost or copy at
12 // https://www.boost.org/LICENSE_1_0.txt)
14 // Unless required by applicable law or agreed to in writing, this software
15 // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 // KIND, either express or implied.
19 This is a derivative work
22 #ifndef BOOST_JSON_DETAIL_RYU_DETAIL_COMMON_HPP
23 #define BOOST_JSON_DETAIL_RYU_DETAIL_COMMON_HPP
25 #include <boost/json/detail/config.hpp>
34 constexpr int DOUBLE_MANTISSA_BITS = 52;
35 constexpr int DOUBLE_EXPONENT_BITS = 11;
36 constexpr int DOUBLE_BIAS = 1023;
38 #if defined(_M_IX86) || defined(_M_ARM)
39 #define BOOST_JSON_RYU_32_BIT_PLATFORM
42 inline uint32_t decimalLength9(const uint32_t v) {
43 // Function precondition: v is not a 10-digit number.
44 // (f2s: 9 digits are sufficient for round-tripping.)
45 // (d2fixed: We print 9-digit blocks.)
46 BOOST_ASSERT(v < 1000000000);
47 if (v >= 100000000) { return 9; }
48 if (v >= 10000000) { return 8; }
49 if (v >= 1000000) { return 7; }
50 if (v >= 100000) { return 6; }
51 if (v >= 10000) { return 5; }
52 if (v >= 1000) { return 4; }
53 if (v >= 100) { return 3; }
54 if (v >= 10) { return 2; }
58 // Returns e == 0 ? 1 : ceil(log_2(5^e)).
59 inline int32_t pow5bits(const int32_t e) {
60 // This approximation works up to the point that the multiplication overflows at e = 3529.
61 // If the multiplication were done in 64 bits, it would fail at 5^4004 which is just greater
64 BOOST_ASSERT(e <= 3528);
65 return (int32_t) (((((uint32_t) e) * 1217359) >> 19) + 1);
68 // Returns floor(log_10(2^e)).
69 inline uint32_t log10Pow2(const int32_t e) {
70 // The first value this approximation fails for is 2^1651 which is just greater than 10^297.
72 BOOST_ASSERT(e <= 1650);
73 return (((uint32_t) e) * 78913) >> 18;
76 // Returns floor(log_10(5^e)).
77 inline uint32_t log10Pow5(const int32_t e) {
78 // The first value this approximation fails for is 5^2621 which is just greater than 10^1832.
80 BOOST_ASSERT(e <= 2620);
81 return (((uint32_t) e) * 732923) >> 20;
84 inline int copy_special_str(char * const result, const bool sign, const bool exponent, const bool mantissa) {
86 memcpy(result, "NaN", 3);
93 memcpy(result + sign, "Infinity", 8);
96 memcpy(result + sign, "0E0", 3);
100 inline uint32_t float_to_bits(const float f) {
102 memcpy(&bits, &f, sizeof(float));
106 inline uint64_t double_to_bits(const double d) {
108 memcpy(&bits, &d, sizeof(double));