1 // Tencent is pleased to support the open source community by making RapidJSON available.
3 // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
5 // Licensed under the MIT License (the "License"); you may not use this file except
6 // in compliance with the License. You may obtain a copy of the License at
8 // http://opensource.org/licenses/MIT
10 // Unless required by applicable law or agreed to in writing, software distributed
11 // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12 // CONDITIONS OF ANY KIND, either express or implied. See the License for the
13 // specific language governing permissions and limitations under the License.
15 #ifndef RAPIDJSON_STRTOD_
16 #define RAPIDJSON_STRTOD_
19 #include "biginteger.h"
25 RAPIDJSON_NAMESPACE_BEGIN
28 inline double FastPath(double significand, int exp) {
32 return significand * internal::Pow10(exp);
34 return significand / internal::Pow10(-exp);
37 inline double StrtodNormalPrecision(double d, int p) {
39 // Prevent expSum < -308, making Pow10(p) = 0
40 d = FastPath(d, -308);
41 d = FastPath(d, p + 308);
49 inline T Min3(T a, T b, T c) {
56 inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp) {
58 const uint64_t bInt = db.IntegerSignificand();
59 const int bExp = db.IntegerExponent();
60 const int hExp = bExp - 1;
62 int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0;
64 // Adjust for decimal exponent
76 // Adjust for binary exponent
84 // Adjust for half ulp exponent
92 // Remove common power of two factor from all three scaled values
93 int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2);
94 dS_Exp2 -= common_Exp2;
95 bS_Exp2 -= common_Exp2;
96 hS_Exp2 -= common_Exp2;
99 dS.MultiplyPow5(static_cast<unsigned>(dS_Exp5)) <<= static_cast<unsigned>(dS_Exp2);
102 bS.MultiplyPow5(static_cast<unsigned>(bS_Exp5)) <<= static_cast<unsigned>(bS_Exp2);
105 hS.MultiplyPow5(static_cast<unsigned>(hS_Exp5)) <<= static_cast<unsigned>(hS_Exp2);
108 dS.Difference(bS, &delta);
110 return delta.Compare(hS);
113 inline bool StrtodFast(double d, int p, double* result) {
114 // Use fast path for string-to-double conversion if possible
115 // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
116 if (p > 22 && p < 22 + 16) {
117 // Fast Path Cases In Disguise
118 d *= internal::Pow10(p - 22);
122 if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1
123 *result = FastPath(d, p);
130 // Compute an approximation and see if it is within 1/2 ULP
131 inline bool StrtodDiyFp(const char* decimals, int dLen, int dExp, double* result) {
132 uint64_t significand = 0;
133 int i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999
134 for (; i < dLen; i++) {
135 if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) ||
136 (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5'))
138 significand = significand * 10u + static_cast<unsigned>(decimals[i] - '0');
141 if (i < dLen && decimals[i] >= '5') // Rounding
144 int remaining = dLen - i;
145 const int kUlpShift = 3;
146 const int kUlp = 1 << kUlpShift;
147 int64_t error = (remaining == 0) ? 0 : kUlp / 2;
149 DiyFp v(significand, 0);
156 DiyFp cachedPower = GetCachedPower10(dExp, &actualExp);
157 if (actualExp != dExp) {
158 static const DiyFp kPow10[] = {
159 DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 0x00000000), -60), // 10^1
160 DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 0x00000000), -57), // 10^2
161 DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 0x00000000), -54), // 10^3
162 DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), -50), // 10^4
163 DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 0x00000000), -47), // 10^5
164 DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 0x00000000), -44), // 10^6
165 DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 0x00000000), -40) // 10^7
167 int adjustment = dExp - actualExp;
168 RAPIDJSON_ASSERT(adjustment >= 1 && adjustment < 8);
169 v = v * kPow10[adjustment - 1];
170 if (dLen + adjustment > 19) // has more digits than decimal digits in 64-bit
176 error += kUlp + (error == 0 ? 0 : 1);
178 const int oldExp = v.e;
180 error <<= oldExp - v.e;
182 const int effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e);
183 int precisionSize = 64 - effectiveSignificandSize;
184 if (precisionSize + kUlpShift >= 64) {
185 int scaleExp = (precisionSize + kUlpShift) - 63;
188 error = (error >> scaleExp) + 1 + kUlp;
189 precisionSize -= scaleExp;
192 DiyFp rounded(v.f >> precisionSize, v.e + precisionSize);
193 const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp;
194 const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp;
195 if (precisionBits >= halfWay + static_cast<unsigned>(error)) {
197 if (rounded.f & (DiyFp::kDpHiddenBit << 1)) { // rounding overflows mantissa (issue #340)
203 *result = rounded.ToDouble();
205 return halfWay - static_cast<unsigned>(error) >= precisionBits || precisionBits >= halfWay + static_cast<unsigned>(error);
208 inline double StrtodBigInteger(double approx, const char* decimals, int dLen, int dExp) {
209 RAPIDJSON_ASSERT(dLen >= 0);
210 const BigInteger dInt(decimals, static_cast<unsigned>(dLen));
212 int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp);
214 return a.Value(); // within half ULP
216 // Round towards even
217 if (a.Significand() & 1)
218 return a.NextPositiveDouble();
223 return a.NextPositiveDouble();
226 inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp) {
227 RAPIDJSON_ASSERT(d >= 0.0);
228 RAPIDJSON_ASSERT(length >= 1);
231 if (StrtodFast(d, p, &result))
234 RAPIDJSON_ASSERT(length <= INT_MAX);
235 int dLen = static_cast<int>(length);
237 RAPIDJSON_ASSERT(length >= decimalPosition);
238 RAPIDJSON_ASSERT(length - decimalPosition <= INT_MAX);
239 int dExpAdjust = static_cast<int>(length - decimalPosition);
241 RAPIDJSON_ASSERT(exp >= INT_MIN + dExpAdjust);
242 int dExp = exp - dExpAdjust;
244 // Make sure length+dExp does not overflow
245 RAPIDJSON_ASSERT(dExp <= INT_MAX - dLen);
247 // Trim leading zeros
248 while (dLen > 0 && *decimals == '0') {
253 // Trim trailing zeros
254 while (dLen > 0 && decimals[dLen - 1] == '0') {
259 if (dLen == 0) { // Buffer only contains zeros.
263 // Trim right-most digits
264 const int kMaxDecimalDigit = 767 + 1;
265 if (dLen > kMaxDecimalDigit) {
266 dExp += dLen - kMaxDecimalDigit;
267 dLen = kMaxDecimalDigit;
270 // If too small, underflow to zero.
271 // Any x <= 10^-324 is interpreted as zero.
272 if (dLen + dExp <= -324)
275 // If too large, overflow to infinity.
276 // Any x >= 10^309 is interpreted as +infinity.
277 if (dLen + dExp > 309)
278 return std::numeric_limits<double>::infinity();
280 if (StrtodDiyFp(decimals, dLen, dExp, &result))
283 // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison
284 return StrtodBigInteger(result, decimals, dLen, dExp);
287 } // namespace internal
288 RAPIDJSON_NAMESPACE_END
290 #endif // RAPIDJSON_STRTOD_