simdjson 5.0.2
Ridiculously Fast JSON
Loading...
Searching...
No Matches
numberparsing.h
1#ifndef SIMDJSON_GENERIC_NUMBERPARSING_H
2
3#ifndef SIMDJSON_CONDITIONAL_INCLUDE
4#define SIMDJSON_GENERIC_NUMBERPARSING_H
5#include "simdjson/generic/base.h"
6#include "simdjson/generic/jsoncharutils.h"
7#include "simdjson/generic/atomparsing.h"
8#include "simdjson/internal/numberparsing_tables.h"
9#endif // SIMDJSON_CONDITIONAL_INCLUDE
10
11#include <limits>
12#include <ostream>
13#include <cstring>
14
15namespace simdjson {
16namespace SIMDJSON_IMPLEMENTATION {
17namespace numberparsing {
18
19#ifdef JSON_TEST_NUMBERS
20#define INVALID_NUMBER(SRC) (found_invalid_number((SRC)), NUMBER_ERROR)
21#define WRITE_INTEGER(VALUE, SRC, WRITER) (found_integer((VALUE), (SRC)), (WRITER).append_s64((VALUE)))
22#define WRITE_UNSIGNED(VALUE, SRC, WRITER) (found_unsigned_integer((VALUE), (SRC)), (WRITER).append_u64((VALUE)))
23#define WRITE_DOUBLE(VALUE, SRC, WRITER) (found_float((VALUE), (SRC)), (WRITER).append_double((VALUE)))
24#define BIGINT_NUMBER(SRC) (found_invalid_number((SRC)), BIGINT_ERROR)
25#else
26#define INVALID_NUMBER(SRC) (NUMBER_ERROR)
27#define WRITE_INTEGER(VALUE, SRC, WRITER) (WRITER).append_s64((VALUE))
28#define WRITE_UNSIGNED(VALUE, SRC, WRITER) (WRITER).append_u64((VALUE))
29#define WRITE_DOUBLE(VALUE, SRC, WRITER) (WRITER).append_double((VALUE))
30#define BIGINT_NUMBER(SRC) (BIGINT_ERROR)
31#endif
32
33namespace {
34
35// Convert a mantissa, an exponent and a sign bit into an ieee64 double.
36// The real_exponent needs to be in [0, 2046] (technically real_exponent = 2047 would be acceptable).
37// The mantissa should be in [0,1<<53). The bit at index (1ULL << 52) while be zeroed.
38simdjson_inline double to_double(uint64_t mantissa, uint64_t real_exponent, bool negative) {
39 double d;
40 mantissa &= ~(1ULL << 52);
41 mantissa |= real_exponent << 52;
42 mantissa |= ((static_cast<uint64_t>(negative)) << 63);
43 std::memcpy(&d, &mantissa, sizeof(d));
44 return d;
45}
46
47// Convert a mantissa, an exponent and a sign bit into an ieee32 float (binary32).
48// The real_exponent needs to be in [0, 254] (technically real_exponent = 255 would be acceptable).
49// The mantissa should be in [0,1<<24). The bit at index (1U << 23) will be zeroed.
50simdjson_inline float to_float(uint32_t mantissa, uint32_t real_exponent, bool negative) {
51 float f;
52 mantissa &= ~(uint32_t(1) << 23);
53 mantissa |= real_exponent << 23;
54 mantissa |= ((static_cast<uint32_t>(negative)) << 31);
55 std::memcpy(&f, &mantissa, sizeof(f));
56 return f;
57}
58
59// Attempts to compute i * 10^(power) exactly; and if "negative" is
60// true, negate the result.
61// This function will only work in some cases, when it does not work, success is
62// set to false. This should work *most of the time* (like 99% of the time).
63// We assume that power is in the [smallest_power,
64// largest_power] interval: the caller is responsible for this check.
65simdjson_inline bool compute_float_64(int64_t power, uint64_t i, bool negative, double &d) {
66 // we start with a fast path
67 // It was described in
68 // Clinger WD. How to read floating point numbers accurately.
69 // ACM SIGPLAN Notices. 1990
70#ifndef FLT_EVAL_METHOD
71#error "FLT_EVAL_METHOD should be defined, please include cfloat."
72#endif
73#if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0)
74 // We cannot be certain that x/y is rounded to nearest.
75 if (0 <= power && power <= 22 && i <= 9007199254740991)
76#else
77 if (-22 <= power && power <= 22 && i <= 9007199254740991)
78#endif
79 {
80 // convert the integer into a double. This is lossless since
81 // 0 <= i <= 2^53 - 1.
82 d = double(i);
83 //
84 // The general idea is as follows.
85 // If 0 <= s < 2^53 and if 10^0 <= p <= 10^22 then
86 // 1) Both s and p can be represented exactly as 64-bit floating-point
87 // values
88 // (binary64).
89 // 2) Because s and p can be represented exactly as floating-point values,
90 // then s * p
91 // and s / p will produce correctly rounded values.
92 //
93 if (power < 0) {
94 d = d / simdjson::internal::power_of_ten[-power];
95 } else {
96 d = d * simdjson::internal::power_of_ten[power];
97 }
98 if (negative) {
99 d = -d;
100 }
101 return true;
102 }
103 // When 22 < power && power < 22 + 16, we could
104 // hope for another, secondary fast path. It was
105 // described by David M. Gay in "Correctly rounded
106 // binary-decimal and decimal-binary conversions." (1990)
107 // If you need to compute i * 10^(22 + x) for x < 16,
108 // first compute i * 10^x, if you know that result is exact
109 // (e.g., when i * 10^x < 2^53),
110 // then you can still proceed and do (i * 10^x) * 10^22.
111 // Is this worth your time?
112 // You need 22 < power *and* power < 22 + 16 *and* (i * 10^(x-22) < 2^53)
113 // for this second fast path to work.
114 // If you you have 22 < power *and* power < 22 + 16, and then you
115 // optimistically compute "i * 10^(x-22)", there is still a chance that you
116 // have wasted your time if i * 10^(x-22) >= 2^53. It makes the use cases of
117 // this optimization maybe less common than we would like. Source:
118 // http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
119 // also used in RapidJSON: https://rapidjson.org/strtod_8h_source.html
120
121 // The fast path has now failed, so we are failing back on the slower path.
122
123 // In the slow path, we need to adjust i so that it is > 1<<63 which is always
124 // possible, except if i == 0, so we handle i == 0 separately.
125 if(i == 0) {
126 d = negative ? -0.0 : 0.0;
127 return true;
128 }
129
130
131 // The exponent is 1024 + 63 + power
132 // + floor(log(5**power)/log(2)).
133 // The 1024 comes from the ieee64 standard.
134 // The 63 comes from the fact that we use a 64-bit word.
135 //
136 // Computing floor(log(5**power)/log(2)) could be
137 // slow. Instead we use a fast function.
138 //
139 // For power in (-400,350), we have that
140 // (((152170 + 65536) * power ) >> 16);
141 // is equal to
142 // floor(log(5**power)/log(2)) + power when power >= 0
143 // and it is equal to
144 // ceil(log(5**-power)/log(2)) + power when power < 0
145 //
146 // The 65536 is (1<<16) and corresponds to
147 // (65536 * power) >> 16 ---> power
148 //
149 // ((152170 * power ) >> 16) is equal to
150 // floor(log(5**power)/log(2))
151 //
152 // Note that this is not magic: 152170/(1<<16) is
153 // approximately equal to log(5)/log(2).
154 // The 1<<16 value is a power of two; we could use a
155 // larger power of 2 if we wanted to.
156 //
157 int64_t exponent = (((152170 + 65536) * power) >> 16) + 1024 + 63;
158
159
160 // We want the most significant bit of i to be 1. Shift if needed.
161 int lz = leading_zeroes(i);
162 i <<= lz;
163
164
165 // We are going to need to do some 64-bit arithmetic to get a precise product.
166 // We use a table lookup approach.
167 // It is safe because
168 // power >= smallest_power
169 // and power <= largest_power
170 // We recover the mantissa of the power, it has a leading 1. It is always
171 // rounded down.
172 //
173 // We want the most significant 64 bits of the product. We know
174 // this will be non-zero because the most significant bit of i is
175 // 1.
176 const uint32_t index = 2 * uint32_t(power - simdjson::internal::smallest_power);
177 // Optimization: It may be that materializing the index as a variable might confuse some compilers and prevent effective complex-addressing loads. (Done for code clarity.)
178 //
179 // The full_multiplication function computes the 128-bit product of two 64-bit words
180 // with a returned value of type value128 with a "low component" corresponding to the
181 // 64-bit least significant bits of the product and with a "high component" corresponding
182 // to the 64-bit most significant bits of the product.
183#if SIMDJSON_STATIC_REFLECTION
184 simdjson::internal::value128 firstproduct = full_multiplication(i, simdjson::internal::powers_template<>::power_of_five_128[index]);
185#else
186 simdjson::internal::value128 firstproduct = full_multiplication(i, simdjson::internal::power_of_five_128[index]);
187#endif
188
189 // Both i and power_of_five_128[index] have their most significant bit set to 1 which
190 // implies that the either the most or the second most significant bit of the product
191 // is 1. We pack values in this manner for efficiency reasons: it maximizes the use
192 // we make of the product. It also makes it easy to reason about the product: there
193 // is 0 or 1 leading zero in the product.
194
195 // Unless the least significant 9 bits of the high (64-bit) part of the full
196 // product are all 1s, then we know that the most significant 55 bits are
197 // exact and no further work is needed. Having 55 bits is necessary because
198 // we need 53 bits for the mantissa but we have to have one rounding bit and
199 // we can waste a bit if the most significant bit of the product is zero.
200 if((firstproduct.high & 0x1FF) == 0x1FF) {
201 // We want to compute i * 5^q, but only care about the top 55 bits at most.
202 // Consider the scenario where q>=0. Then 5^q may not fit in 64-bits. Doing
203 // the full computation is wasteful. So we do what is called a "truncated
204 // multiplication".
205 // We take the most significant 64-bits, and we put them in
206 // power_of_five_128[index]. Usually, that's good enough to approximate i * 5^q
207 // to the desired approximation using one multiplication. Sometimes it does not suffice.
208 // Then we store the next most significant 64 bits in power_of_five_128[index + 1], and
209 // then we get a better approximation to i * 5^q.
210 //
211 // That's for when q>=0. The logic for q<0 is somewhat similar but it is somewhat
212 // more complicated.
213 //
214 // There is an extra layer of complexity in that we need more than 55 bits of
215 // accuracy in the round-to-even scenario.
216 //
217 // The full_multiplication function computes the 128-bit product of two 64-bit words
218 // with a returned value of type value128 with a "low component" corresponding to the
219 // 64-bit least significant bits of the product and with a "high component" corresponding
220 // to the 64-bit most significant bits of the product.
221#if SIMDJSON_STATIC_REFLECTION
222 simdjson::internal::value128 secondproduct = full_multiplication(i, simdjson::internal::powers_template<>::power_of_five_128[index + 1]);
223#else
224 simdjson::internal::value128 secondproduct = full_multiplication(i, simdjson::internal::power_of_five_128[index + 1]);
225#endif
226 firstproduct.low += secondproduct.high;
227 if(secondproduct.high > firstproduct.low) { firstproduct.high++; }
228 // As it has been proven by Noble Mushtak and Daniel Lemire in "Fast Number Parsing Without
229 // Fallback" (https://arxiv.org/abs/2212.06644), at this point we are sure that the product
230 // is sufficiently accurate, and more computation is not needed.
231 }
232 uint64_t lower = firstproduct.low;
233 uint64_t upper = firstproduct.high;
234 // The final mantissa should be 53 bits with a leading 1.
235 // We shift it so that it occupies 54 bits with a leading 1.
237 uint64_t upperbit = upper >> 63;
238 uint64_t mantissa = upper >> (upperbit + 9);
239 lz += int(1 ^ upperbit);
240
241 // Here we have mantissa < (1<<54).
242 int64_t real_exponent = exponent - lz;
243 if (simdjson_unlikely(real_exponent <= 0)) { // we have a subnormal?
244 // Here have that real_exponent <= 0 so -real_exponent >= 0
245 if(-real_exponent + 1 >= 64) { // if we have more than 64 bits below the minimum exponent, you have a zero for sure.
246 d = negative ? -0.0 : 0.0;
247 return true;
248 }
249 // next line is safe because -real_exponent + 1 < 0
250 mantissa >>= -real_exponent + 1;
251 // Thankfully, we can't have both "round-to-even" and subnormals because
252 // "round-to-even" only occurs for powers close to 0.
253 mantissa += (mantissa & 1); // round up
254 mantissa >>= 1;
255 // There is a weird scenario where we don't have a subnormal but just.
256 // Suppose we start with 2.2250738585072013e-308, we end up
257 // with 0x3fffffffffffff x 2^-1023-53 which is technically subnormal
258 // whereas 0x40000000000000 x 2^-1023-53 is normal. Now, we need to round
259 // up 0x3fffffffffffff x 2^-1023-53 and once we do, we are no longer
260 // subnormal, but we can only know this after rounding.
261 // So we only declare a subnormal if we are smaller than the threshold.
262 real_exponent = (mantissa < (uint64_t(1) << 52)) ? 0 : 1;
263 d = to_double(mantissa, real_exponent, negative);
264 return true;
265 }
266 // We have to round to even. The "to even" part
267 // is only a problem when we are right in between two floats
268 // which we guard against.
269 // If we have lots of trailing zeros, we may fall right between two
270 // floating-point values.
271 //
272 // The round-to-even cases take the form of a number 2m+1 which is in (2^53,2^54]
273 // times a power of two. That is, it is right between a number with binary significand
274 // m and another number with binary significand m+1; and it must be the case
275 // that it cannot be represented by a float itself.
276 //
277 // We must have that w * 10 ^q == (2m+1) * 2^p for some power of two 2^p.
278 // Recall that 10^q = 5^q * 2^q.
279 // When q >= 0, we must have that (2m+1) is divible by 5^q, so 5^q <= 2^54. We have that
280 // 5^23 <= 2^54 and it is the last power of five to qualify, so q <= 23.
281 // When q<0, we have w >= (2m+1) x 5^{-q}. We must have that w<2^{64} so
282 // (2m+1) x 5^{-q} < 2^{64}. We have that 2m+1>2^{53}. Hence, we must have
283 // 2^{53} x 5^{-q} < 2^{64}.
284 // Hence we have 5^{-q} < 2^{11}$ or q>= -4.
285 //
286 // We require lower <= 1 and not lower == 0 because we could not prove that
287 // that lower == 0 is implied; but we could prove that lower <= 1 is a necessary and sufficient test.
288 if (simdjson_unlikely((lower <= 1) && (power >= -4) && (power <= 23) && ((mantissa & 3) == 1))) {
289 if((mantissa << (upperbit + 64 - 53 - 2)) == upper) {
290 mantissa &= ~1; // flip it so that we do not round up
291 }
292 }
293
294 mantissa += mantissa & 1;
295 mantissa >>= 1;
296
297 // Here we have mantissa < (1<<53), unless there was an overflow
298 if (mantissa >= (1ULL << 53)) {
300 // This will happen when parsing values such as 7.2057594037927933e+16
302 mantissa = (1ULL << 52);
303 real_exponent++;
304 }
305 mantissa &= ~(1ULL << 52);
306 // we have to check that real_exponent is in range, otherwise we bail out
307 if (simdjson_unlikely(real_exponent > 2046)) {
308 // We have an infinite value!!! We could actually throw an error here if we could.
309 return false;
310 }
311 d = to_double(mantissa, real_exponent, negative);
312 return true;
313}
314
315// Attempts to compute i * 10^(power) as a binary32 (float) value; and if
316// "negative" is true, negate the result.
317//
318// This is the same Eisel-Lemire algorithm as compute_float_64, retargeted at
319// binary32. It is adapted from fast_float
320// (https://github.com/fastfloat/fast_float), where the routine is written once
321// and instantiated for each binary format. We only need 24 bits of mantissa
322// instead of 53, so we ask the truncated product for 24 + 2 = 26 accurate bits
323// (plus one bit that may be lost to the "upperbit" shift), and we shift the
324// product right by (upperbit + 64 - 23 - 3) instead of (upperbit + 64 - 52 - 3).
325//
326// The power-of-five table is shared with the binary64 code: the useful range
327// for binary32, [smallest_power_binary32, largest_power_binary32], is a strict
328// subset of [smallest_power, largest_power].
329//
330// The function returns false when the result would be infinite: simdjson
331// refuses to parse infinite values, so the caller reports an error. Unlike
332// compute_float_64, a false return never means "try harder": the accuracy of
333// the two-limb product is guaranteed by Noble Mushtak and Daniel Lemire,
334// "Fast Number Parsing Without Fallback" (https://arxiv.org/abs/2212.06644).
335// The caller must still fall back to a slow path when the 64-bit mantissa i
336// was truncated (more than 19 significant digits).
337//
338// We assume that power is in the [smallest_power, largest_power] interval: the
339// caller is responsible for this check.
340simdjson_inline bool compute_float_32(int64_t power, uint64_t i, bool negative, float &d) {
341 // Powers of ten that are exactly representable as binary32 values: 10^k is
342 // exact as long as k <= 10 (5^10 = 9765625 < 2**24 while 5^11 > 2**24).
343 static constexpr float power_of_ten_float[] = {
344 1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f,
345 1e6f, 1e7f, 1e8f, 1e9f, 1e10f};
346 // The range of powers of ten that a non-zero, finite binary32 value can be
347 // built from. Anything smaller rounds to zero, anything larger is infinite.
348 // These are the smallest_power_of_ten()/largest_power_of_ten() constants that
349 // fast_float uses for binary32.
350 constexpr int smallest_power_binary32 = -65;
351 constexpr int largest_power_binary32 = 38;
352
353 // We start with the fast path described in
354 // Clinger WD. How to read floating point numbers accurately.
355 // ACM SIGPLAN Notices. 1990
356#ifndef FLT_EVAL_METHOD
357#error "FLT_EVAL_METHOD should be defined, please include cfloat."
358#endif
359#if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0)
360 // We cannot be certain that x/y is rounded to nearest.
361 if (0 <= power && power <= 10 && i <= 16777215)
362#else
363 if (-10 <= power && power <= 10 && i <= 16777215)
364#endif
365 {
366 // Convert the integer into a float. This is lossless since
367 // 0 <= i <= 2^24 - 1.
368 d = float(i);
369 // Both d and the power of ten are exactly representable as binary32
370 // values, so the product (or quotient) is correctly rounded.
371 if (power < 0) {
372 d = d / power_of_ten_float[-power];
373 } else {
374 d = d * power_of_ten_float[power];
375 }
376 if (negative) {
377 d = -d;
378 }
379 return true;
380 }
381
382 // The fast path has failed, so we fall back on the Eisel-Lemire algorithm.
383 // It needs i > 0 (so that the leading bit of i can be normalized), so we
384 // handle i == 0 separately. We also handle the powers of ten that are so
385 // small (or so large) that the answer is zero (or infinite) whatever the
386 // mantissa is.
387 if (i == 0 || power < smallest_power_binary32) {
388 d = negative ? -0.0f : 0.0f;
389 return true;
390 }
391 if (power > largest_power_binary32) {
392 // We have, for sure, an infinite value.
393 return false;
394 }
395
396 // The exponent is 128 + 63 + power + floor(log(5**power)/log(2)).
397 // The 128 comes from the ieee32 standard (the minimal exponent is -127).
398 // The 63 comes from the fact that we use a 64-bit word.
399 // See compute_float_64 for a discussion of the magical 152170 + 65536.
400 int64_t exponent = (((152170 + 65536) * power) >> 16) + 128 + 63;
401
402 // We want the most significant bit of i to be 1. Shift if needed.
403 int lz = leading_zeroes(i);
404 i <<= lz;
405
406 // We want the most significant 64 bits of the product i * 5**power. It is
407 // safe to index the table because
408 // smallest_power <= smallest_power_binary32 <= power
409 // <= largest_power_binary32 <= largest_power.
410 const uint32_t index = 2 * uint32_t(power - simdjson::internal::smallest_power);
411#if SIMDJSON_STATIC_REFLECTION
412 simdjson::internal::value128 firstproduct = full_multiplication(i, simdjson::internal::powers_template<>::power_of_five_128[index]);
413#else
414 simdjson::internal::value128 firstproduct = full_multiplication(i, simdjson::internal::power_of_five_128[index]);
415#endif
416
417 // Unless the least significant 38 bits of the high (64-bit) part of the full
418 // product are all 1s, then we know that the most significant 26 bits are
419 // exact and no further work is needed. Having 26 bits is necessary because
420 // we need 24 bits for the mantissa but we have to have one rounding bit and
421 // we can waste a bit if the most significant bit of the product is zero.
422 // (For binary64, the same reasoning gives 55 bits and a 9-bit mask.)
423 if((firstproduct.high & 0x3FFFFFFFFF) == 0x3FFFFFFFFF) {
424 // The truncated multiplication was not accurate enough; use the next 64
425 // bits of the power of five to refine it. See compute_float_64 for a
426 // detailed discussion.
427#if SIMDJSON_STATIC_REFLECTION
428 simdjson::internal::value128 secondproduct = full_multiplication(i, simdjson::internal::powers_template<>::power_of_five_128[index + 1]);
429#else
430 simdjson::internal::value128 secondproduct = full_multiplication(i, simdjson::internal::power_of_five_128[index + 1]);
431#endif
432 firstproduct.low += secondproduct.high;
433 if(secondproduct.high > firstproduct.low) { firstproduct.high++; }
434 }
435 uint64_t lower = firstproduct.low;
436 uint64_t upper = firstproduct.high;
437 // The final mantissa should be 24 bits with a leading 1.
438 // We shift it so that it occupies 25 bits with a leading 1.
440 uint64_t upperbit = upper >> 63;
441 uint64_t mantissa = upper >> (upperbit + 38); // 38 == 64 - 23 - 3
442 lz += int(1 ^ upperbit);
443
444 // Here we have mantissa < (1<<25).
445 int64_t real_exponent = exponent - lz;
446 if (simdjson_unlikely(real_exponent <= 0)) { // we have a subnormal?
447 // Here we have that real_exponent <= 0 so -real_exponent >= 0
448 if(-real_exponent + 1 >= 64) { // if we have more than 64 bits below the minimum exponent, you have a zero for sure.
449 d = negative ? -0.0f : 0.0f;
450 return true;
451 }
452 // next line is safe because -real_exponent + 1 < 64
453 mantissa >>= -real_exponent + 1;
454 // Thankfully, we can't have both "round-to-even" and subnormals because
455 // "round-to-even" only occurs for powers close to 0.
456 mantissa += (mantissa & 1); // round up
457 mantissa >>= 1;
458 // As in compute_float_64, rounding up may take us out of the subnormal
459 // range, so we can only decide after rounding.
460 real_exponent = (mantissa < (uint64_t(1) << 23)) ? 0 : 1;
461 d = to_float(uint32_t(mantissa), uint32_t(real_exponent), negative);
462 return true;
463 }
464 // We have to round to even. The "to even" part is only a problem when we are
465 // right in between two floats, which we guard against. The bounds on the
466 // power of ten are those of fast_float's
467 // min_exponent_round_to_even()/max_exponent_round_to_even() for binary32:
468 // when q >= 0, (2m+1) must be divisible by 5^q with 5^q <= 2^25, so q <= 10;
469 // when q < 0, we need 2^24 x 5^{-q} < 2^{64}, so q >= -17.
470 if (simdjson_unlikely((lower <= 1) && (power >= -17) && (power <= 10) && ((mantissa & 3) == 1))) {
471 if((mantissa << (upperbit + 38)) == upper) {
472 mantissa &= ~uint64_t(1); // flip it so that we do not round up
473 }
474 }
475
476 mantissa += mantissa & 1;
477 mantissa >>= 1;
478
479 // Here we have mantissa < (1<<24), unless there was an overflow
480 if (mantissa >= (uint64_t(1) << 24)) {
481 mantissa = (uint64_t(1) << 23);
482 real_exponent++;
483 }
484 mantissa &= ~(uint64_t(1) << 23);
485 // we have to check that real_exponent is in range, otherwise we bail out
486 if (simdjson_unlikely(real_exponent > 254)) {
487 // We have an infinite value!!! We could actually throw an error here if we could.
488 return false;
489 }
490 d = to_float(uint32_t(mantissa), uint32_t(real_exponent), negative);
491 return true;
492}
493
494#if SIMDJSON_ENABLE_NAN_INF
495// Parses a nan or infinity. Returns true on success, false on failure.
496simdjson_unused simdjson_inline bool compute_nan_inf(const uint8_t* src, bool negative, double& d) noexcept {
497 if (atomparsing::is_valid_inf_atom(src)) {
498 double inf = std::numeric_limits<double>::infinity();
499 d = negative ? -inf : inf;
500 return true;
501 }
502
503 if (atomparsing::is_valid_nan_atom(src)) {
504 d = std::numeric_limits<double>::quiet_NaN();
505 return true;
506 }
507
508 return false;
509}
510
511// Parses a nan or infinity as a binary32 value. Returns true on success, false on failure.
512simdjson_unused simdjson_inline bool compute_nan_inf(const uint8_t* src, bool negative, float& d) noexcept {
513 if (atomparsing::is_valid_inf_atom(src)) {
514 float inf = std::numeric_limits<float>::infinity();
515 d = negative ? -inf : inf;
516 return true;
517 }
518
519 if (atomparsing::is_valid_nan_atom(src)) {
520 d = std::numeric_limits<float>::quiet_NaN();
521 return true;
522 }
523
524 return false;
525}
526#endif
527
528// We call a fallback floating-point parser that might be slow. Note
529// it will accept JSON numbers, but the JSON spec. is more restrictive so
530// before you call parse_float_fallback, you need to have validated the input
531// string with the JSON grammar.
532// It will return an error (false) if the parsed number is infinite.
533// The string parsing itself always succeeds. We know that there is at least
534// one digit.
535static bool parse_float_fallback(const uint8_t *ptr, double *outDouble) {
536 *outDouble = simdjson::internal::from_chars(reinterpret_cast<const char *>(ptr));
537 // We do not accept infinite values.
538
539 // Detecting finite values in a portable manner is ridiculously hard, ideally
540 // we would want to do:
541 // return !std::isfinite(*outDouble);
542 // but that mysteriously fails under legacy/old libc++ libraries, see
543 // https://github.com/simdjson/simdjson/issues/1286
544 //
545 // Therefore, fall back to this solution (the extra parens are there
546 // to handle that max may be a macro on windows).
547 return !(*outDouble > (std::numeric_limits<double>::max)() || *outDouble < std::numeric_limits<double>::lowest());
548}
549
550static bool parse_float_fallback(const uint8_t *ptr, const uint8_t *end_ptr, double *outDouble) {
551 *outDouble = simdjson::internal::from_chars(reinterpret_cast<const char *>(ptr), reinterpret_cast<const char *>(end_ptr));
552 // We do not accept infinite values.
553
554 // Detecting finite values in a portable manner is ridiculously hard, ideally
555 // we would want to do:
556 // return !std::isfinite(*outDouble);
557 // but that mysteriously fails under legacy/old libc++ libraries, see
558 // https://github.com/simdjson/simdjson/issues/1286
559 //
560 // Therefore, fall back to this solution (the extra parens are there
561 // to handle that max may be a macro on windows).
562 return !(*outDouble > (std::numeric_limits<double>::max)() || *outDouble < std::numeric_limits<double>::lowest());
563}
564
565// Same as parse_float_fallback, but for binary32 (float) values. Going through
566// the binary64 fallback and then rounding to binary32 would be subject to
567// double rounding, so we run the fallback algorithm directly on binary32.
568static bool parse_float_fallback(const uint8_t *ptr, float *outFloat) {
569 *outFloat = simdjson::internal::from_chars_float(reinterpret_cast<const char *>(ptr));
570 // We do not accept infinite values. See the binary64 version above for why we
571 // do not use std::isfinite.
572 return !(*outFloat > (std::numeric_limits<float>::max)() || *outFloat < std::numeric_limits<float>::lowest());
573}
574
575// check quickly whether the next 8 chars are made of digits
576// at a glance, it looks better than Mula's
577// http://0x80.pl/articles/swar-digits-validate.html
578simdjson_inline bool is_made_of_eight_digits_fast(const uint8_t *chars) {
579 uint64_t val;
580 // this can read up to 7 bytes beyond the buffer size, but we require
581 // SIMDJSON_PADDING of padding
582 static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7");
583 std::memcpy(&val, chars, 8);
584 // a branchy method might be faster:
585 // return (( val & 0xF0F0F0F0F0F0F0F0 ) == 0x3030303030303030)
586 // && (( (val + 0x0606060606060606) & 0xF0F0F0F0F0F0F0F0 ) ==
587 // 0x3030303030303030);
588 return (((val & 0xF0F0F0F0F0F0F0F0) |
589 (((val + 0x0606060606060606) & 0xF0F0F0F0F0F0F0F0) >> 4)) ==
590 0x3333333333333333);
591}
592
593// The same idea for four characters. A block of eight only bites when eight
594// digits are left, so a run of 4 to 7 digits used to fall back to one digit at a
595// time; taking four of them at once is what makes the tail of a long fraction
596// cheap. Adapted from fast_float, credit @aqrit.
597simdjson_inline bool is_made_of_four_digits_fast(const uint8_t *chars) {
598 uint32_t val;
599 // Reads up to 3 bytes beyond the digits, which SIMDJSON_PADDING covers.
600 static_assert(3 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 3");
601 std::memcpy(&val, chars, 4);
602 return !(((val + 0x46464646) | (val - 0x30303030)) & 0x80808080);
603}
604
605// Only call this when is_made_of_four_digits_fast() says the four characters are
606// digits. Little-endian: guarded by SIMDJSON_SWAR_NUMBER_PARSING.
607simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) {
608 uint32_t val;
609 std::memcpy(&val, chars, 4);
610 val -= 0x30303030;
611 val = (val * 10) + (val >> 8);
612 return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF;
613}
614
615template<typename I>
616SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later
617simdjson_inline bool parse_digit(const uint8_t c, I &i) {
618 const uint8_t digit = static_cast<uint8_t>(c - '0');
619 if (digit > 9) {
620 return false;
621 }
622 // PERF NOTE: multiplication by 10 is cheaper than arbitrary integer multiplication
623 i = 10 * i + digit; // might overflow, we will handle the overflow later
624 return true;
625}
626
627simdjson_inline bool is_digit(const uint8_t c) {
628 return static_cast<uint8_t>(c - '0') <= 9;
629}
630
631// Consumes a run of digits into i, eight at a time while eight are available,
632// then four, then one at a time. Overflow is deliberate: the caller counts the
633// digits and falls back when there are too many for a 64-bit mantissa.
634//
635// Long runs of digits are what a float-heavy document is made of: the fraction
636// of a binary64 printed to full precision is 15 to 17 digits, and reading those
637// one at a time is the single largest cost in parse_double(). Integer parts are
638// left alone: they are usually a handful of digits, and there the check for a
639// block of eight is wasted work.
640SIMDJSON_NO_SANITIZE_UNDEFINED
641simdjson_inline void parse_fraction_digits(const uint8_t *&p, uint64_t &i) {
642#ifdef SIMDJSON_SWAR_NUMBER_PARSING
643#if SIMDJSON_SWAR_NUMBER_PARSING
644 while (is_made_of_eight_digits_fast(p)) {
645 i = i * 100000000 + parse_eight_digits_unrolled(p);
646 p += 8;
647 }
648 // A 4 to 7 digit remainder is the common case once the blocks of eight are
649 // gone: 15 fraction digits leave 7, and 17 leave 1 after two blocks.
650 if (is_made_of_four_digits_fast(p)) {
651 i = i * 10000 + parse_four_digits_unrolled(p);
652 p += 4;
653 }
654#endif // SIMDJSON_SWAR_NUMBER_PARSING
655#endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING
656 while (parse_digit(*p, i)) { p++; }
657}
658
659SIMDJSON_NO_SANITIZE_UNDEFINED
660simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i,
661 bool &leading_zero) {
662 if (!parse_digit(*p, i)) { leading_zero = true; return; }
663 p++;
664 leading_zero = (i == 0);
665 while (parse_digit(*p, i)) { p++; }
666}
667
668SIMDJSON_NO_SANITIZE_UNDEFINED
669simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) {
670#ifdef SIMDJSON_SWAR_NUMBER_PARSING
671#if SIMDJSON_SWAR_NUMBER_PARSING
672 // Identifiers, timestamps and counters often have eight digits or more.
673 if (is_made_of_eight_digits_fast(p)) {
674 i = i * 100000000 + parse_eight_digits_unrolled(p);
675 p += 8;
676 }
677 const uint8_t *const swar_end = p + 8;
678 while (p < swar_end && is_made_of_four_digits_fast(p)) {
679 i = i * 10000 + parse_four_digits_unrolled(p);
680 p += 4;
681 }
682#endif // SIMDJSON_SWAR_NUMBER_PARSING
683#endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING
684 while (parse_digit(*p, i)) { p++; }
685}
686
687simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) {
688 // we continue with the fiction that we have an integer. If the
689 // floating point number is representable as x * 10^z for some integer
690 // z that fits in 53 bits, then we will be able to convert back the
691 // the integer into a float in a lossless manner.
692 const uint8_t *const first_after_period = p;
693 parse_fraction_digits(p, i);
694 exponent = first_after_period - p;
695 // Decimal without digits (123.) is illegal
696 if (exponent == 0) {
697 return INVALID_NUMBER(src);
698 }
699 return SUCCESS;
700}
701
702simdjson_warn_unused simdjson_inline error_code parse_exponent(simdjson_unused const uint8_t *const src, const uint8_t *&p, int64_t &exponent) {
703 // Exp Sign: -123.456e[-]78
704 bool neg_exp = ('-' == *p);
705 if (neg_exp || '+' == *p) { p++; } // Skip + as well
706
707 // Exponent: -123.456e-[78]
708 auto start_exp = p;
709 int64_t exp_number = 0;
710 while (parse_digit(*p, exp_number)) { ++p; }
711 // It is possible for parse_digit to overflow.
712 // In particular, it could overflow to INT64_MIN, and we cannot do - INT64_MIN.
713 // Thus we *must* check for possible overflow before we negate exp_number.
714
715 // Performance notes: it may seem like combining the two "simdjson_unlikely checks" below into
716 // a single simdjson_unlikely path would be faster. The reasoning is sound, but the compiler may
717 // not oblige and may, in fact, generate two distinct paths in any case. It might be
718 // possible to do uint64_t(p - start_exp - 1) >= 18 but it could end up trading off
719 // instructions for a simdjson_likely branch, an unconclusive gain.
720
721 // If there were no digits, it's an error.
722 if (simdjson_unlikely(p == start_exp)) {
723 return INVALID_NUMBER(src);
724 }
725 // We have a valid positive exponent in exp_number at this point, except that
726 // it may have overflowed.
727
728 // If there were more than 18 digits, we may have overflowed the integer. We have to do
729 // something!!!!
730 if (simdjson_unlikely(p > start_exp+18)) {
731 // Skip leading zeroes: 1e000000000000000000001 is technically valid and does not overflow
732 while (*start_exp == '0') { start_exp++; }
733 // 19 digits could overflow int64_t and is kind of absurd anyway. We don't
734 // support exponents smaller than -999,999,999,999,999,999 and bigger
735 // than 999,999,999,999,999,999.
736 // We can truncate.
737 // Note that 999999999999999999 is assuredly too large. The maximal ieee64 value before
738 // infinity is ~1.8e308. The smallest subnormal is ~5e-324. So, actually, we could
739 // truncate at 324.
740 // Note that there is no reason to fail per se at this point in time.
741 // E.g., 0e999999999999999999999 is a fine number.
742 if (p > start_exp+18) { exp_number = 999999999999999999; }
743 }
744 // At this point, we know that exp_number is a sane, positive, signed integer.
745 // It is <= 999,999,999,999,999,999. As long as 'exponent' is in
746 // [-8223372036854775808, 8223372036854775808], we won't overflow. Because 'exponent'
747 // is bounded in magnitude by the size of the JSON input, we are fine in this universe.
748 // To sum it up: the next line should never overflow.
749 exponent += (neg_exp ? -exp_number : exp_number);
750 return SUCCESS;
751}
752
753simdjson_inline bool check_if_integer(const uint8_t *const src, size_t max_length) {
754 const uint8_t *const srcend = src + max_length;
755 bool negative = (*src == '-'); // we can always read at least one character after the '-'
756 const uint8_t *p = src + uint8_t(negative);
757 if(p == srcend) { return false; }
758 if(*p == '0') {
759 ++p;
760 if(p == srcend) { return true; }
761 if(jsoncharutils::is_not_structural_or_whitespace(*p)) { return false; }
762 return true;
763 }
764 while(p != srcend && is_digit(*p)) { ++p; }
765 if(p == srcend) { return true; }
766 if(jsoncharutils::is_not_structural_or_whitespace(*p)) { return false; }
767 return true;
768}
769
770simdjson_inline size_t significant_digits(const uint8_t * start_digits, size_t digit_count) {
771 // It is possible that the integer had an overflow.
772 // We have to handle the case where we have 0.0000somenumber.
773 const uint8_t *start = start_digits;
774 while ((*start == '0') || (*start == '.')) { ++start; }
775 // we over-decrement by one when there is a '.'
776 return digit_count - size_t(start - start_digits);
777}
778
779} // unnamed namespace
780
782inline error_code slow_float_parsing(simdjson_unused const uint8_t * src, double* answer) {
783 if (parse_float_fallback(src, answer)) {
784 return SUCCESS;
785 }
786 return INVALID_NUMBER(src);
787}
788
790template<typename W>
791simdjson_warn_unused simdjson_inline error_code write_float(const uint8_t *const src, bool negative, uint64_t i, const uint8_t * start_digits, size_t digit_count, int64_t exponent, W &writer) {
792 // If we frequently had to deal with long strings of digits,
793 // we could extend our code by using a 128-bit integer instead
794 // of a 64-bit integer. However, this is uncommon in practice.
795 //
796 // 9999999999999999999 < 2**64 so we can accommodate 19 digits.
797 // If we have a decimal separator, then digit_count - 1 is the number of digits, but we
798 // may not have a decimal separator!
799 if (simdjson_unlikely(digit_count > 19 && significant_digits(start_digits, digit_count) > 19)) {
800 // Ok, chances are good that we had an overflow!
801 // this is almost never going to get called!!!
802 // we start anew, going slowly!!!
803 // This will happen in the following examples:
804 // 10000000000000000000000000000000000000000000e+308
805 // 3.1415926535897932384626433832795028841971693993751
806 //
807 // NOTE: We do not pass a reference to the to slow_float_parsing. If we passed our writer
808 // reference to it, it would force it to be stored in memory, preventing the compiler from
809 // picking it apart and putting into registers. i.e. if we pass it as reference,
810 // it gets slow.
811 double d;
812 error_code error = slow_float_parsing(src, &d);
813 writer.append_double(d);
814 return error;
815 }
816 // NOTE: it's weird that the simdjson_unlikely() only wraps half the if, but it seems to get slower any other
817 // way we've tried: https://github.com/simdjson/simdjson/pull/990#discussion_r448497331
818 // To future reader: we'd love if someone found a better way, or at least could explain this result!
819 if (simdjson_unlikely(exponent < simdjson::internal::smallest_power) || (exponent > simdjson::internal::largest_power)) {
820 //
821 // Important: smallest_power is such that it leads to a zero value.
822 // Observe that 18446744073709551615e-343 == 0, i.e. (2**64 - 1) e -343 is zero
823 // so something x 10^-343 goes to zero, but not so with something x 10^-342.
824 static_assert(simdjson::internal::smallest_power <= -342, "smallest_power is not small enough");
825 //
826 if((exponent < simdjson::internal::smallest_power) || (i == 0)) {
827 // E.g. Parse "-0.0e-999" into the same value as "-0.0". See https://en.wikipedia.org/wiki/Signed_zero
828 WRITE_DOUBLE(negative ? -0.0 : 0.0, src, writer);
829 return SUCCESS;
830 } else { // (exponent > largest_power) and (i != 0)
831 // We have, for sure, an infinite value and simdjson refuses to parse infinite values.
832 return INVALID_NUMBER(src);
833 }
834 }
835 double d;
836 if (!compute_float_64(exponent, i, negative, d)) {
837 // we are almost never going to get here.
838 if (!parse_float_fallback(src, &d)) { return INVALID_NUMBER(src); }
839 }
840 WRITE_DOUBLE(d, src, writer);
841 return SUCCESS;
842}
843
844// parse the number at src
845// define JSON_TEST_NUMBERS for unit testing
846//
847// It is assumed that the number is followed by a structural ({,},],[) character
848// or a white space character. If that is not the case (e.g., when the JSON
849// document is made of a single number), then it is necessary to copy the
850// content and append a space before calling this function.
851//
852// Our objective is accurate parsing (ULP of 0) at high speed.
853template<typename W>
854simdjson_warn_unused simdjson_inline error_code parse_number(const uint8_t *const src, W &writer);
855
856// for performance analysis, it is sometimes useful to skip parsing
857#ifdef SIMDJSON_SKIPNUMBERPARSING
858
859template<typename W>
860simdjson_warn_unused simdjson_inline error_code parse_number(const uint8_t *const, W &writer) {
861 writer.append_s64(0); // always write zero
862 return SUCCESS; // always succeeds
863}
864
865simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const uint8_t * const) noexcept { return 0; }
866simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uint8_t * const) noexcept { return 0; }
867simdjson_unused simdjson_inline simdjson_result<double> parse_double(const uint8_t * const) noexcept { return 0; }
868simdjson_unused simdjson_inline simdjson_result<float> parse_float(const uint8_t * const) noexcept { return 0; }
869simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const) noexcept { return 0; }
870simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t * const) noexcept { return 0; }
871simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * const) noexcept { return 0; }
872simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * const) noexcept { return 0; }
873simdjson_unused simdjson_inline bool is_negative(const uint8_t *) noexcept { return false; }
874simdjson_unused simdjson_inline simdjson_result<bool> is_integer(const uint8_t *) noexcept { return false; }
875simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(const uint8_t *) noexcept { return number_type::signed_integer; }
876#else
877
878// parse the number at src
879// define JSON_TEST_NUMBERS for unit testing
880//
881// It is assumed that the number is followed by a structural ({,},],[) character
882// or a white space character. If that is not the case (e.g., when the JSON
883// document is made of a single number), then it is necessary to copy the
884// content and append a space before calling this function.
885//
886// Our objective is accurate parsing (ULP of 0) at high speed.
887template<typename W>
888simdjson_warn_unused simdjson_inline error_code parse_number(const uint8_t *const src, W &writer) {
889 //
890 // Check for minus sign
891 //
892 bool negative = (*src == '-');
893 const uint8_t *p = src + uint8_t(negative);
894
895 //
896 // Parse the integer part.
897 //
898 // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
899 const uint8_t *const start_digits = p;
900 uint64_t i = 0;
901 while (parse_digit(*p, i)) { p++; }
902
903 // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
904 // Optimization note: size_t is expected to be unsigned.
905 size_t digit_count = size_t(p - start_digits);
906 if (digit_count == 0 || ('0' == *start_digits && digit_count > 1)) {
907
908#if SIMDJSON_ENABLE_NAN_INF
909 // By this point, we know that our input does not begin with a digit. We will attempt
910 // to handle NaN/Infinity.
911
912 double d;
913 if (compute_nan_inf(p, negative, d)) {
914 writer.append_double(d);
915 return SUCCESS;
916 }
917#endif
918
919 return INVALID_NUMBER(src);
920 }
921
922 //
923 // Handle floats if there is a . or e (or both)
924 //
925 int64_t exponent = 0;
926 bool is_float = false;
927 if ('.' == *p) {
928 is_float = true;
929 ++p;
930 SIMDJSON_TRY( parse_decimal_after_separator(src, p, i, exponent) );
931 digit_count = int(p - start_digits); // used later to guard against overflows
932 }
933 if (('e' == *p) || ('E' == *p)) {
934 is_float = true;
935 ++p;
936 SIMDJSON_TRY( parse_exponent(src, p, exponent) );
937 }
938 if (is_float) {
939 const bool dirty_end = jsoncharutils::is_not_structural_or_whitespace(*p);
940 SIMDJSON_TRY( write_float(src, negative, i, start_digits, digit_count, exponent, writer) );
941 if (dirty_end) { return INVALID_NUMBER(src); }
942 return SUCCESS;
943 }
944
945 // The longest negative 64-bit number is 19 digits.
946 // The longest positive 64-bit number is 20 digits.
947 // We do it this way so we don't trigger this branch unless we must.
948 size_t longest_digit_count = negative ? 19 : 20;
949 if (digit_count > longest_digit_count) { return BIGINT_NUMBER(src); }
950 if (digit_count == longest_digit_count) {
951 if (negative) {
952 // Anything negative above INT64_MAX+1 is invalid
953 if (i > uint64_t(INT64_MAX)+1) { return BIGINT_NUMBER(src); }
954 WRITE_INTEGER(~i+1, src, writer);
955 if (jsoncharutils::is_not_structural_or_whitespace(*p)) { return INVALID_NUMBER(src); }
956 return SUCCESS;
957 // Positive overflow check:
958 // - A 20 digit number starting with 2-9 is overflow, because 18,446,744,073,709,551,615 is the
959 // biggest uint64_t.
960 // - A 20 digit number starting with 1 is overflow if it is less than INT64_MAX.
961 // If we got here, it's a 20 digit number starting with the digit "1".
962 // - If a 20 digit number starting with 1 overflowed (i*10+digit), the result will be smaller
963 // than 1,553,255,926,290,448,384.
964 // - That is smaller than the smallest possible 20-digit number the user could write:
965 // 10,000,000,000,000,000,000.
966 // - Therefore, if the number is positive and lower than that, it's overflow.
967 // - The value we are looking at is less than or equal to INT64_MAX.
968 //
969 } else if (src[0] != uint8_t('1') || i <= uint64_t(INT64_MAX)) { return BIGINT_NUMBER(src); }
970 }
971
972 // Write unsigned if it does not fit in a signed integer.
973 if (i > uint64_t(INT64_MAX)) {
974 WRITE_UNSIGNED(i, src, writer);
975 } else {
976#if SIMDJSON_MINUS_ZERO_AS_FLOAT
977 if(i == 0 && negative) {
978 // We have to write -0.0 instead of 0
979 WRITE_DOUBLE(-0.0, src, writer);
980 } else {
981 WRITE_INTEGER(negative ? (~i+1) : i, src, writer);
982 }
983#else
984 WRITE_INTEGER(negative ? (~i+1) : i, src, writer);
985#endif
986 }
987 if (jsoncharutils::is_not_structural_or_whitespace(*p)) { return INVALID_NUMBER(src); }
988 return SUCCESS;
989}
990
991// Inlineable functions
992namespace {
993
994// This table can be used to characterize the final character of an integer
995// string. For JSON structural character and allowable white space characters,
996// we return SUCCESS. For 'e', '.' and 'E', we return INCORRECT_TYPE. Otherwise
997// we return NUMBER_ERROR.
998// Optimization note: we could easily reduce the size of the table by half (to 128)
999// at the cost of an extra branch.
1000// Optimization note: we want the values to use at most 8 bits (not, e.g., 32 bits):
1001static_assert(error_code(uint8_t(NUMBER_ERROR))== NUMBER_ERROR, "bad NUMBER_ERROR cast");
1002static_assert(error_code(uint8_t(SUCCESS))== SUCCESS, "bad NUMBER_ERROR cast");
1003static_assert(error_code(uint8_t(INCORRECT_TYPE))== INCORRECT_TYPE, "bad NUMBER_ERROR cast");
1004
1005const uint8_t integer_string_finisher[256] = {
1057 NUMBER_ERROR};
1058
1059// Parse any number from 0 to 18,446,744,073,709,551,615
1060simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const uint8_t * const src) noexcept {
1061 const uint8_t *p = src;
1062 //
1063 // Parse the integer part.
1064 //
1065 // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
1066 const uint8_t *const start_digits = p;
1067 uint64_t i = 0;
1068 parse_integer_digits(p, i);
1069
1070 // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
1071 // Optimization note: size_t is expected to be unsigned.
1072 size_t digit_count = size_t(p - start_digits);
1073 // The longest positive 64-bit number is 20 digits.
1074 // We do it this way so we don't trigger this branch unless we must.
1075 // Optimization note: the compiler can probably merge
1076 // ((digit_count == 0) || (digit_count > 20))
1077 // into a single branch since digit_count is unsigned.
1078 if ((digit_count == 0) || (digit_count > 20)) { return INCORRECT_TYPE; }
1079 // Here digit_count > 0.
1080 if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
1081 // We can do the following...
1082 // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
1083 // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
1084 // }
1085 // as a single table lookup:
1086 if (integer_string_finisher[*p] != SUCCESS) { return error_code(integer_string_finisher[*p]); }
1087
1088 if (digit_count == 20) {
1089 // Positive overflow check:
1090 // - A 20 digit number starting with 2-9 is overflow, because 18,446,744,073,709,551,615 is the
1091 // biggest uint64_t.
1092 // - A 20 digit number starting with 1 is overflow if it is less than INT64_MAX.
1093 // If we got here, it's a 20 digit number starting with the digit "1".
1094 // - If a 20 digit number starting with 1 overflowed (i*10+digit), the result will be smaller
1095 // than 1,553,255,926,290,448,384.
1096 // - That is smaller than the smallest possible 20-digit number the user could write:
1097 // 10,000,000,000,000,000,000.
1098 // - Therefore, if the number is positive and lower than that, it's overflow.
1099 // - The value we are looking at is less than or equal to INT64_MAX.
1100 //
1101 if (src[0] != uint8_t('1') || i <= uint64_t(INT64_MAX)) { return INCORRECT_TYPE; }
1102 }
1103
1104 return i;
1105}
1106
1107
1108// Parse any number from 0 to 18,446,744,073,709,551,615
1109// Never read at src_end or beyond
1110simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const uint8_t * const src, const uint8_t * const src_end) noexcept {
1111 const uint8_t *p = src;
1112 //
1113 // Parse the integer part.
1114 //
1115 // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
1116 const uint8_t *const start_digits = p;
1117 uint64_t i = 0;
1118 while ((p != src_end) && parse_digit(*p, i)) { p++; }
1119
1120 // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
1121 // Optimization note: size_t is expected to be unsigned.
1122 size_t digit_count = size_t(p - start_digits);
1123 // The longest positive 64-bit number is 20 digits.
1124 // We do it this way so we don't trigger this branch unless we must.
1125 // Optimization note: the compiler can probably merge
1126 // ((digit_count == 0) || (digit_count > 20))
1127 // into a single branch since digit_count is unsigned.
1128 if ((digit_count == 0) || (digit_count > 20)) { return INCORRECT_TYPE; }
1129 // Here digit_count > 0.
1130 if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
1131 // We can do the following...
1132 // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
1133 // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
1134 // }
1135 // as a single table lookup:
1136 if ((p != src_end) && integer_string_finisher[*p] != SUCCESS) { return error_code(integer_string_finisher[*p]); }
1137
1138 if (digit_count == 20) {
1139 // Positive overflow check:
1140 // - A 20 digit number starting with 2-9 is overflow, because 18,446,744,073,709,551,615 is the
1141 // biggest uint64_t.
1142 // - A 20 digit number starting with 1 is overflow if it is less than INT64_MAX.
1143 // If we got here, it's a 20 digit number starting with the digit "1".
1144 // - If a 20 digit number starting with 1 overflowed (i*10+digit), the result will be smaller
1145 // than 1,553,255,926,290,448,384.
1146 // - That is smaller than the smallest possible 20-digit number the user could write:
1147 // 10,000,000,000,000,000,000.
1148 // - Therefore, if the number is positive and lower than that, it's overflow.
1149 // - The value we are looking at is less than or equal to INT64_MAX.
1150 //
1151 if (src[0] != uint8_t('1') || i <= uint64_t(INT64_MAX)) { return INCORRECT_TYPE; }
1152 }
1153
1154 return i;
1155}
1156
1157// Parse any number from 0 to 18,446,744,073,709,551,615
1158simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept {
1159 const uint8_t *p = src + 1;
1160 //
1161 // Parse the integer part.
1162 //
1163 // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
1164 const uint8_t *const start_digits = p;
1165 uint64_t i = 0;
1166 parse_integer_digits(p, i);
1167
1168 // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
1169 // Optimization note: size_t is expected to be unsigned.
1170 size_t digit_count = size_t(p - start_digits);
1171 // The longest positive 64-bit number is 20 digits.
1172 // We do it this way so we don't trigger this branch unless we must.
1173 // Optimization note: the compiler can probably merge
1174 // ((digit_count == 0) || (digit_count > 20))
1175 // into a single branch since digit_count is unsigned.
1176 if ((digit_count == 0) || (digit_count > 20)) { return INCORRECT_TYPE; }
1177 // Here digit_count > 0.
1178 if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
1179 // We can do the following...
1180 // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
1181 // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
1182 // }
1183 // as a single table lookup:
1184 if (*p != '"') { return NUMBER_ERROR; }
1185
1186 if (digit_count == 20) {
1187 // Positive overflow check:
1188 // - A 20 digit number starting with 2-9 is overflow, because 18,446,744,073,709,551,615 is the
1189 // biggest uint64_t.
1190 // - A 20 digit number starting with 1 is overflow if it is less than INT64_MAX.
1191 // If we got here, it's a 20 digit number starting with the digit "1".
1192 // - If a 20 digit number starting with 1 overflowed (i*10+digit), the result will be smaller
1193 // than 1,553,255,926,290,448,384.
1194 // - That is smaller than the smallest possible 20-digit number the user could write:
1195 // 10,000,000,000,000,000,000.
1196 // - Therefore, if the number is positive and lower than that, it's overflow.
1197 // - The value we are looking at is less than or equal to INT64_MAX.
1198 //
1199 // Note: we use src[1] and not src[0] because src[0] is the quote character in this
1200 // instance.
1201 if (src[1] != uint8_t('1') || i <= uint64_t(INT64_MAX)) { return INCORRECT_TYPE; }
1202 }
1203
1204 return i;
1205}
1206
1207// Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
1208simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uint8_t *src) noexcept {
1209 //
1210 // Check for minus sign
1211 //
1212 bool negative = (*src == '-');
1213 const uint8_t *p = src + uint8_t(negative);
1214
1215 //
1216 // Parse the integer part.
1217 //
1218 // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
1219 const uint8_t *const start_digits = p;
1220 uint64_t i = 0;
1221 parse_integer_digits(p, i);
1222
1223 // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
1224 // Optimization note: size_t is expected to be unsigned.
1225 size_t digit_count = size_t(p - start_digits);
1226 // We go from
1227 // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
1228 // so we can never represent numbers that have more than 19 digits.
1229 size_t longest_digit_count = 19;
1230 // Optimization note: the compiler can probably merge
1231 // ((digit_count == 0) || (digit_count > longest_digit_count))
1232 // into a single branch since digit_count is unsigned.
1233 if ((digit_count == 0) || (digit_count > longest_digit_count)) { return INCORRECT_TYPE; }
1234 // Here digit_count > 0.
1235 if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
1236 // We can do the following...
1237 // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
1238 // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
1239 // }
1240 // as a single table lookup:
1241 if(integer_string_finisher[*p] != SUCCESS) { return error_code(integer_string_finisher[*p]); }
1242 // Negative numbers have can go down to - INT64_MAX - 1 whereas positive numbers are limited to INT64_MAX.
1243 // Performance note: This check is only needed when digit_count == longest_digit_count but it is
1244 // so cheap that we might as well always make it.
1245 if(i > uint64_t(INT64_MAX) + uint64_t(negative)) { return INCORRECT_TYPE; }
1246 return negative ? (~i+1) : i;
1247}
1248
1249// Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
1250// Never read at src_end or beyond
1251simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uint8_t * const src, const uint8_t * const src_end) noexcept {
1252 //
1253 // Check for minus sign
1254 //
1255 if(src == src_end) { return NUMBER_ERROR; }
1256 bool negative = (*src == '-');
1257 const uint8_t *p = src + uint8_t(negative);
1258
1259 //
1260 // Parse the integer part.
1261 //
1262 // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
1263 const uint8_t *const start_digits = p;
1264 uint64_t i = 0;
1265 while ((p != src_end) && parse_digit(*p, i)) { p++; }
1266
1267 // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
1268 // Optimization note: size_t is expected to be unsigned.
1269 size_t digit_count = size_t(p - start_digits);
1270 // We go from
1271 // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
1272 // so we can never represent numbers that have more than 19 digits.
1273 size_t longest_digit_count = 19;
1274 // Optimization note: the compiler can probably merge
1275 // ((digit_count == 0) || (digit_count > longest_digit_count))
1276 // into a single branch since digit_count is unsigned.
1277 if ((digit_count == 0) || (digit_count > longest_digit_count)) { return INCORRECT_TYPE; }
1278 // Here digit_count > 0.
1279 if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
1280 // We can do the following...
1281 // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
1282 // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
1283 // }
1284 // as a single table lookup:
1285 if((p != src_end) && integer_string_finisher[*p] != SUCCESS) { return error_code(integer_string_finisher[*p]); }
1286 // Negative numbers have can go down to - INT64_MAX - 1 whereas positive numbers are limited to INT64_MAX.
1287 // Performance note: This check is only needed when digit_count == longest_digit_count but it is
1288 // so cheap that we might as well always make it.
1289 if(i > uint64_t(INT64_MAX) + uint64_t(negative)) { return INCORRECT_TYPE; }
1290 return negative ? (~i+1) : i;
1291}
1292
1293// Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
1294simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept {
1295 //
1296 // Check for minus sign
1297 //
1298 bool negative = (*(src + 1) == '-');
1299 src += uint8_t(negative) + 1;
1300
1301 //
1302 // Parse the integer part.
1303 //
1304 // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
1305 const uint8_t *const start_digits = src;
1306 uint64_t i = 0;
1307 parse_integer_digits(src, i);
1308
1309 // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
1310 // Optimization note: size_t is expected to be unsigned.
1311 size_t digit_count = size_t(src - start_digits);
1312 // We go from
1313 // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
1314 // so we can never represent numbers that have more than 19 digits.
1315 size_t longest_digit_count = 19;
1316 // Optimization note: the compiler can probably merge
1317 // ((digit_count == 0) || (digit_count > longest_digit_count))
1318 // into a single branch since digit_count is unsigned.
1319 if ((digit_count == 0) || (digit_count > longest_digit_count)) { return INCORRECT_TYPE; }
1320 // Here digit_count > 0.
1321 if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
1322 // We can do the following...
1323 // if (!jsoncharutils::is_structural_or_whitespace(*src)) {
1324 // return (*src == '.' || *src == 'e' || *src == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
1325 // }
1326 // as a single table lookup:
1327 if(*src != '"') { return NUMBER_ERROR; }
1328 // Negative numbers have can go down to - INT64_MAX - 1 whereas positive numbers are limited to INT64_MAX.
1329 // Performance note: This check is only needed when digit_count == longest_digit_count but it is
1330 // so cheap that we might as well always make it.
1331 if(i > uint64_t(INT64_MAX) + uint64_t(negative)) { return INCORRECT_TYPE; }
1332 return negative ? (~i+1) : i;
1333}
1334
1335simdjson_unused simdjson_inline simdjson_result<double> parse_double(const uint8_t * src) noexcept {
1336 //
1337 // Check for minus sign
1338 //
1339 bool negative = (*src == '-');
1340 src += uint8_t(negative);
1341
1342 //
1343 // Parse the integer part.
1344 //
1345 uint64_t i = 0;
1346 const uint8_t *p = src;
1347 bool leading_zero;
1348 parse_float_integer_digits(p, i, leading_zero);
1349 // no integer digits, or 0123 (zero must be solo)
1350 if ( p == src ) {
1351
1352#if SIMDJSON_ENABLE_NAN_INF
1353 // If there are no loading digits, the number may be nan or infinity.
1354 // Attempt to compute those, and return on success.
1355 double d;
1356 if (compute_nan_inf(p, negative, d)) { return d; }
1357#endif
1358
1359 return INCORRECT_TYPE;
1360 }
1361 if ( (leading_zero && p != src+1)) { return NUMBER_ERROR; }
1362
1363 //
1364 // Parse the decimal part.
1365 //
1366 int64_t exponent = 0;
1367 bool overflow;
1368 if (simdjson_likely(*p == '.')) {
1369 p++;
1370 const uint8_t *start_decimal_digits = p;
1371 parse_fraction_digits(p, i);
1372 if (p == start_decimal_digits) { return NUMBER_ERROR; } // no decimal digits
1373 exponent = -(p - start_decimal_digits);
1374
1375 // Overflow check. More than 19 digits (minus the decimal) may be overflow.
1376 overflow = p-src-1 > 19;
1377 if (simdjson_unlikely(overflow && leading_zero)) {
1378 // Skip leading 0.00000 and see if it still overflows
1379 const uint8_t *start_digits = src + 2;
1380 while (*start_digits == '0') { start_digits++; }
1381 overflow = p-start_digits > 19;
1382 }
1383 } else {
1384 overflow = p-src > 19;
1385 }
1386
1387 //
1388 // Parse the exponent
1389 //
1390 if (*p == 'e' || *p == 'E') {
1391 p++;
1392 bool exp_neg = *p == '-';
1393 p += exp_neg || *p == '+';
1394
1395 uint64_t exp = 0;
1396 const uint8_t *start_exp_digits = p;
1397 while (parse_digit(*p, exp)) { p++; }
1398 // no exp digits, or 20+ exp digits
1399 if (p-start_exp_digits == 0 || p-start_exp_digits > 19) { return NUMBER_ERROR; }
1400
1401 exponent += exp_neg ? 0-exp : exp;
1402 }
1403
1404 if (jsoncharutils::is_not_structural_or_whitespace(*p)) { return NUMBER_ERROR; }
1405
1406 overflow = overflow || exponent < simdjson::internal::smallest_power || exponent > simdjson::internal::largest_power;
1407
1408 //
1409 // Assemble (or slow-parse) the float
1410 //
1411 double d;
1412 if (simdjson_likely(!overflow)) {
1413 if (compute_float_64(exponent, i, negative, d)) { return d; }
1414 }
1415 if (!parse_float_fallback(src - uint8_t(negative), &d)) {
1416 return NUMBER_ERROR;
1417 }
1418 return d;
1419}
1420
1421// Parse a JSON number into a binary32 (float) value.
1422//
1423// This mirrors parse_double, but it rounds to binary32 directly instead of
1424// rounding to binary64 and then to binary32: the latter is subject to double
1425// rounding and would not always produce the nearest float.
1426simdjson_unused simdjson_inline simdjson_result<float> parse_float(const uint8_t * src) noexcept {
1427 //
1428 // Check for minus sign
1429 //
1430 bool negative = (*src == '-');
1431 src += uint8_t(negative);
1432
1433 //
1434 // Parse the integer part.
1435 //
1436 uint64_t i = 0;
1437 const uint8_t *p = src;
1438 bool leading_zero;
1439 parse_float_integer_digits(p, i, leading_zero);
1440 // no integer digits, or 0123 (zero must be solo)
1441 if ( p == src ) {
1442
1443#if SIMDJSON_ENABLE_NAN_INF
1444 // If there are no leading digits, the number may be nan or infinity.
1445 // Attempt to compute those, and return on success.
1446 float f;
1447 if (compute_nan_inf(p, negative, f)) { return f; }
1448#endif
1449
1450 return INCORRECT_TYPE;
1451 }
1452 if ( (leading_zero && p != src+1)) { return NUMBER_ERROR; }
1453
1454 //
1455 // Parse the decimal part.
1456 //
1457 int64_t exponent = 0;
1458 bool overflow;
1459 if (simdjson_likely(*p == '.')) {
1460 p++;
1461 const uint8_t *start_decimal_digits = p;
1462 parse_fraction_digits(p, i);
1463 if (p == start_decimal_digits) { return NUMBER_ERROR; } // no decimal digits
1464 exponent = -(p - start_decimal_digits);
1465
1466 // Overflow check. More than 19 digits (minus the decimal) may be overflow.
1467 overflow = p-src-1 > 19;
1468 if (simdjson_unlikely(overflow && leading_zero)) {
1469 // Skip leading 0.00000 and see if it still overflows
1470 const uint8_t *start_digits = src + 2;
1471 while (*start_digits == '0') { start_digits++; }
1472 overflow = p-start_digits > 19;
1473 }
1474 } else {
1475 overflow = p-src > 19;
1476 }
1477
1478 //
1479 // Parse the exponent
1480 //
1481 if (*p == 'e' || *p == 'E') {
1482 p++;
1483 bool exp_neg = *p == '-';
1484 p += exp_neg || *p == '+';
1485
1486 uint64_t exp = 0;
1487 const uint8_t *start_exp_digits = p;
1488 while (parse_digit(*p, exp)) { p++; }
1489 // no exp digits, or 20+ exp digits
1490 if (p-start_exp_digits == 0 || p-start_exp_digits > 19) { return NUMBER_ERROR; }
1491
1492 exponent += exp_neg ? 0-exp : exp;
1493 }
1494
1495 if (jsoncharutils::is_not_structural_or_whitespace(*p)) { return NUMBER_ERROR; }
1496
1497 overflow = overflow || exponent < simdjson::internal::smallest_power || exponent > simdjson::internal::largest_power;
1498
1499 //
1500 // Assemble (or slow-parse) the float
1501 //
1502 float d;
1503 if (simdjson_likely(!overflow)) {
1504 if (compute_float_32(exponent, i, negative, d)) { return d; }
1505 }
1506 if (!parse_float_fallback(src - uint8_t(negative), &d)) {
1507 return NUMBER_ERROR;
1508 }
1509 return d;
1510}
1511
1512simdjson_unused simdjson_inline bool is_negative(const uint8_t * src) noexcept {
1513 return (*src == '-');
1514}
1515
1516simdjson_unused simdjson_inline simdjson_result<bool> is_integer(const uint8_t * src) noexcept {
1517 bool negative = (*src == '-');
1518 src += uint8_t(negative);
1519 const uint8_t *p = src;
1520 while(static_cast<uint8_t>(*p - '0') <= 9) { p++; }
1521 if ( p == src ) { return NUMBER_ERROR; }
1522 if (jsoncharutils::is_structural_or_whitespace(*p)) { return true; }
1523 return false;
1524}
1525
1526simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(const uint8_t * src) noexcept {
1527 bool negative = (*src == '-');
1528 src += uint8_t(negative);
1529 const uint8_t *p = src;
1530 while(static_cast<uint8_t>(*p - '0') <= 9) { p++; }
1531 size_t digit_count = size_t(p - src);
1532 if ( p == src ) { return NUMBER_ERROR; }
1533 if (jsoncharutils::is_structural_or_whitespace(*p)) {
1534 static const uint8_t * smaller_big_integer = reinterpret_cast<const uint8_t *>("9223372036854775808");
1535 // We have an integer.
1536 if(simdjson_unlikely(digit_count > 20)) {
1537 return number_type::big_integer;
1538 }
1539 // If the number is negative and valid, it must be a signed integer.
1540 if(negative) {
1541 if (simdjson_unlikely(digit_count > 19)) return number_type::big_integer;
1542 if (simdjson_unlikely(digit_count == 19 && memcmp(src, smaller_big_integer, 19) > 0)) {
1543 return number_type::big_integer;
1544 }
1545#if SIMDJSON_MINUS_ZERO_AS_FLOAT
1546 if(digit_count == 1 && src[0] == '0') {
1547 // We have to write -0.0 instead of 0
1548 return number_type::floating_point_number;
1549 }
1550#endif
1551 return number_type::signed_integer;
1552 }
1553 // Let us check if we have a big integer (>=2**64).
1554 static const uint8_t * two_to_sixtyfour = reinterpret_cast<const uint8_t *>("18446744073709551616");
1555 if((digit_count > 20) || (digit_count == 20 && memcmp(src, two_to_sixtyfour, 20) >= 0)) {
1556 return number_type::big_integer;
1557 }
1558 // The number is positive and smaller than 18446744073709551616 (or 2**64).
1559 // We want values larger or equal to 9223372036854775808 to be unsigned
1560 // integers, and the other values to be signed integers.
1561 if((digit_count == 20) || (digit_count >= 19 && memcmp(src, smaller_big_integer, 19) >= 0)) {
1562 return number_type::unsigned_integer;
1563 }
1564 return number_type::signed_integer;
1565 }
1566 // Hopefully, we have 'e' or 'E' or '.'.
1567 return number_type::floating_point_number;
1568}
1569
1570// Never read at src_end or beyond
1571simdjson_unused simdjson_inline simdjson_result<double> parse_double(const uint8_t * src, const uint8_t * const src_end) noexcept {
1572 if(src == src_end) { return NUMBER_ERROR; }
1573 //
1574 // Check for minus sign
1575 //
1576 bool negative = (*src == '-');
1577 src += uint8_t(negative);
1578
1579 //
1580 // Parse the integer part.
1581 //
1582 uint64_t i = 0;
1583 const uint8_t *p = src;
1584 if(p == src_end) { return NUMBER_ERROR; }
1585 p += parse_digit(*p, i);
1586 bool leading_zero = (i == 0);
1587 while ((p != src_end) && parse_digit(*p, i)) { p++; }
1588 // no integer digits, or 0123 (zero must be solo)
1589 if ( p == src ) { return INCORRECT_TYPE; }
1590 if ( (leading_zero && p != src+1)) { return NUMBER_ERROR; }
1591
1592 //
1593 // Parse the decimal part.
1594 //
1595 int64_t exponent = 0;
1596 bool overflow;
1597 if (simdjson_likely((p != src_end) && (*p == '.'))) {
1598 p++;
1599 const uint8_t *start_decimal_digits = p;
1600 if ((p == src_end) || !parse_digit(*p, i)) { return NUMBER_ERROR; } // no decimal digits
1601 p++;
1602 while ((p != src_end) && parse_digit(*p, i)) { p++; }
1603 exponent = -(p - start_decimal_digits);
1604
1605 // Overflow check. More than 19 digits (minus the decimal) may be overflow.
1606 overflow = p-src-1 > 19;
1607 if (simdjson_unlikely(overflow && leading_zero)) {
1608 // Skip leading 0.00000 and see if it still overflows
1609 const uint8_t *start_digits = src + 2;
1610 while (*start_digits == '0') { start_digits++; }
1611 overflow = start_digits-src > 19;
1612 }
1613 } else {
1614 overflow = p-src > 19;
1615 }
1616
1617 //
1618 // Parse the exponent
1619 //
1620 if ((p != src_end) && (*p == 'e' || *p == 'E')) {
1621 p++;
1622 if(p == src_end) { return NUMBER_ERROR; }
1623 bool exp_neg = *p == '-';
1624 p += exp_neg || *p == '+';
1625
1626 uint64_t exp = 0;
1627 const uint8_t *start_exp_digits = p;
1628 while ((p != src_end) && parse_digit(*p, exp)) { p++; }
1629 // no exp digits, or 20+ exp digits
1630 if (p-start_exp_digits == 0 || p-start_exp_digits > 19) { return NUMBER_ERROR; }
1631
1632 exponent += exp_neg ? 0-exp : exp;
1633 }
1634
1635 if ((p != src_end) && jsoncharutils::is_not_structural_or_whitespace(*p)) { return NUMBER_ERROR; }
1636
1637 overflow = overflow || exponent < simdjson::internal::smallest_power || exponent > simdjson::internal::largest_power;
1638
1639 //
1640 // Assemble (or slow-parse) the float
1641 //
1642 double d;
1643 if (simdjson_likely(!overflow)) {
1644 if (compute_float_64(exponent, i, negative, d)) { return d; }
1645 }
1646 if (!parse_float_fallback(src - uint8_t(negative), src_end, &d)) {
1647 return NUMBER_ERROR;
1648 }
1649 return d;
1650}
1651
1652simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept {
1653 //
1654 // Check for minus sign
1655 //
1656 bool negative = (*(src + 1) == '-');
1657 src += uint8_t(negative) + 1;
1658
1659 //
1660 // Parse the integer part.
1661 //
1662 uint64_t i = 0;
1663 const uint8_t *p = src;
1664 bool leading_zero;
1665 parse_float_integer_digits(p, i, leading_zero);
1666 // no integer digits, or 0123 (zero must be solo)
1667 if ( p == src ) {
1668#if SIMDJSON_ENABLE_NAN_INF
1669 // If there are no leading digits, attempt to parse numbers that are either
1670 // NaN or Infinity
1671 if (atomparsing::is_valid_inf_in_string(src)) {
1672 double inf = std::numeric_limits<double>::infinity();
1673 return negative ? -inf : inf;
1674 }
1675
1676 if (atomparsing::is_valid_nan_in_string(src)) {
1677 return std::numeric_limits<double>::quiet_NaN();
1678 }
1679#endif
1680
1681 return INCORRECT_TYPE;
1682 }
1683 if ( (leading_zero && p != src+1)) { return NUMBER_ERROR; }
1684
1685 //
1686 // Parse the decimal part.
1687 //
1688 int64_t exponent = 0;
1689 bool overflow;
1690 if (simdjson_likely(*p == '.')) {
1691 p++;
1692 const uint8_t *start_decimal_digits = p;
1693 parse_fraction_digits(p, i);
1694 if (p == start_decimal_digits) { return NUMBER_ERROR; } // no decimal digits
1695 exponent = -(p - start_decimal_digits);
1696
1697 // Overflow check. More than 19 digits (minus the decimal) may be overflow.
1698 overflow = p-src-1 > 19;
1699 if (simdjson_unlikely(overflow && leading_zero)) {
1700 // Skip leading 0.00000 and see if it still overflows
1701 const uint8_t *start_digits = src + 2;
1702 while (*start_digits == '0') { start_digits++; }
1703 overflow = p-start_digits > 19;
1704 }
1705 } else {
1706 overflow = p-src > 19;
1707 }
1708
1709 //
1710 // Parse the exponent
1711 //
1712 if (*p == 'e' || *p == 'E') {
1713 p++;
1714 bool exp_neg = *p == '-';
1715 p += exp_neg || *p == '+';
1716
1717 uint64_t exp = 0;
1718 const uint8_t *start_exp_digits = p;
1719 while (parse_digit(*p, exp)) { p++; }
1720 // no exp digits, or 20+ exp digits
1721 if (p-start_exp_digits == 0 || p-start_exp_digits > 19) { return NUMBER_ERROR; }
1722
1723 exponent += exp_neg ? 0-exp : exp;
1724 }
1725
1726 if (*p != '"') { return NUMBER_ERROR; }
1727
1728 overflow = overflow || exponent < simdjson::internal::smallest_power || exponent > simdjson::internal::largest_power;
1729
1730 //
1731 // Assemble (or slow-parse) the float
1732 //
1733 double d;
1734 if (simdjson_likely(!overflow)) {
1735 if (compute_float_64(exponent, i, negative, d)) { return d; }
1736 }
1737 if (!parse_float_fallback(src - uint8_t(negative), &d)) {
1738 return NUMBER_ERROR;
1739 }
1740 return d;
1741}
1742
1743// Parse a JSON number held inside a JSON string into a binary32 (float) value.
1744// See parse_float for why we do not simply round parse_double_in_string.
1745simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept {
1746 //
1747 // Check for minus sign
1748 //
1749 bool negative = (*(src + 1) == '-');
1750 src += uint8_t(negative) + 1;
1751
1752 //
1753 // Parse the integer part.
1754 //
1755 uint64_t i = 0;
1756 const uint8_t *p = src;
1757 bool leading_zero;
1758 parse_float_integer_digits(p, i, leading_zero);
1759 // no integer digits, or 0123 (zero must be solo)
1760 if ( p == src ) {
1761#if SIMDJSON_ENABLE_NAN_INF
1762 // If there are no leading digits, attempt to parse numbers that are either
1763 // NaN or Infinity
1764 if (atomparsing::is_valid_inf_in_string(src)) {
1765 float inf = std::numeric_limits<float>::infinity();
1766 return negative ? -inf : inf;
1767 }
1768
1769 if (atomparsing::is_valid_nan_in_string(src)) {
1770 return std::numeric_limits<float>::quiet_NaN();
1771 }
1772#endif
1773
1774 return INCORRECT_TYPE;
1775 }
1776 if ( (leading_zero && p != src+1)) { return NUMBER_ERROR; }
1777
1778 //
1779 // Parse the decimal part.
1780 //
1781 int64_t exponent = 0;
1782 bool overflow;
1783 if (simdjson_likely(*p == '.')) {
1784 p++;
1785 const uint8_t *start_decimal_digits = p;
1786 parse_fraction_digits(p, i);
1787 if (p == start_decimal_digits) { return NUMBER_ERROR; } // no decimal digits
1788 exponent = -(p - start_decimal_digits);
1789
1790 // Overflow check. More than 19 digits (minus the decimal) may be overflow.
1791 overflow = p-src-1 > 19;
1792 if (simdjson_unlikely(overflow && leading_zero)) {
1793 // Skip leading 0.00000 and see if it still overflows
1794 const uint8_t *start_digits = src + 2;
1795 while (*start_digits == '0') { start_digits++; }
1796 overflow = p-start_digits > 19;
1797 }
1798 } else {
1799 overflow = p-src > 19;
1800 }
1801
1802 //
1803 // Parse the exponent
1804 //
1805 if (*p == 'e' || *p == 'E') {
1806 p++;
1807 bool exp_neg = *p == '-';
1808 p += exp_neg || *p == '+';
1809
1810 uint64_t exp = 0;
1811 const uint8_t *start_exp_digits = p;
1812 while (parse_digit(*p, exp)) { p++; }
1813 // no exp digits, or 20+ exp digits
1814 if (p-start_exp_digits == 0 || p-start_exp_digits > 19) { return NUMBER_ERROR; }
1815
1816 exponent += exp_neg ? 0-exp : exp;
1817 }
1818
1819 if (*p != '"') { return NUMBER_ERROR; }
1820
1821 overflow = overflow || exponent < simdjson::internal::smallest_power || exponent > simdjson::internal::largest_power;
1822
1823 //
1824 // Assemble (or slow-parse) the float
1825 //
1826 float d;
1827 if (simdjson_likely(!overflow)) {
1828 if (compute_float_32(exponent, i, negative, d)) { return d; }
1829 }
1830 if (!parse_float_fallback(src - uint8_t(negative), &d)) {
1831 return NUMBER_ERROR;
1832 }
1833 return d;
1834}
1835
1836} // unnamed namespace
1837#endif // SIMDJSON_SKIPNUMBERPARSING
1838
1839} // namespace numberparsing
1840
1841inline std::ostream& operator<<(std::ostream& out, number_type type) noexcept {
1842 switch (type) {
1843 case number_type::signed_integer: out << "integer in [-9223372036854775808,9223372036854775808)"; break;
1844 case number_type::unsigned_integer: out << "unsigned integer in [9223372036854775808,18446744073709551616)"; break;
1845 case number_type::floating_point_number: out << "floating-point number (binary64)"; break;
1846 case number_type::big_integer: out << "big integer"; break;
1847 default: SIMDJSON_UNREACHABLE();
1848 }
1849 return out;
1850}
1851
1852} // namespace SIMDJSON_IMPLEMENTATION
1853} // namespace simdjson
1854
1855#endif // SIMDJSON_GENERIC_NUMBERPARSING_H
The top level simdjson namespace, containing everything the library provides.
Definition base.h:8
error_code
All possible errors returned by simdjson.
Definition error.h:19
@ INCORRECT_TYPE
JSON element has a different type than user expected.
Definition error.h:37
@ SUCCESS
No error.
Definition error.h:20
@ NUMBER_ERROR
Problem while parsing a number.
Definition error.h:29
constexpr size_t SIMDJSON_PADDING
The amount of padding needed in a buffer to parse JSON.
Definition base.h:42