simdjson  3.3.0
Ridiculously Fast JSON
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/internal/numberparsing_tables.h"
8 #endif // SIMDJSON_CONDITIONAL_INCLUDE
9 
10 #include <limits>
11 #include <ostream>
12 #include <cstring>
13 
14 namespace simdjson {
15 namespace SIMDJSON_IMPLEMENTATION {
16 namespace numberparsing {
17 
18 #ifdef JSON_TEST_NUMBERS
19 #define INVALID_NUMBER(SRC) (found_invalid_number((SRC)), NUMBER_ERROR)
20 #define WRITE_INTEGER(VALUE, SRC, WRITER) (found_integer((VALUE), (SRC)), (WRITER).append_s64((VALUE)))
21 #define WRITE_UNSIGNED(VALUE, SRC, WRITER) (found_unsigned_integer((VALUE), (SRC)), (WRITER).append_u64((VALUE)))
22 #define WRITE_DOUBLE(VALUE, SRC, WRITER) (found_float((VALUE), (SRC)), (WRITER).append_double((VALUE)))
23 #else
24 #define INVALID_NUMBER(SRC) (NUMBER_ERROR)
25 #define WRITE_INTEGER(VALUE, SRC, WRITER) (WRITER).append_s64((VALUE))
26 #define WRITE_UNSIGNED(VALUE, SRC, WRITER) (WRITER).append_u64((VALUE))
27 #define WRITE_DOUBLE(VALUE, SRC, WRITER) (WRITER).append_double((VALUE))
28 #endif
29 
30 namespace {
31 
32 // Convert a mantissa, an exponent and a sign bit into an ieee64 double.
33 // The real_exponent needs to be in [0, 2046] (technically real_exponent = 2047 would be acceptable).
34 // The mantissa should be in [0,1<<53). The bit at index (1ULL << 52) while be zeroed.
35 simdjson_inline double to_double(uint64_t mantissa, uint64_t real_exponent, bool negative) {
36  double d;
37  mantissa &= ~(1ULL << 52);
38  mantissa |= real_exponent << 52;
39  mantissa |= ((static_cast<uint64_t>(negative)) << 63);
40  std::memcpy(&d, &mantissa, sizeof(d));
41  return d;
42 }
43 
44 // Attempts to compute i * 10^(power) exactly; and if "negative" is
45 // true, negate the result.
46 // This function will only work in some cases, when it does not work, success is
47 // set to false. This should work *most of the time* (like 99% of the time).
48 // We assume that power is in the [smallest_power,
49 // largest_power] interval: the caller is responsible for this check.
50 simdjson_inline bool compute_float_64(int64_t power, uint64_t i, bool negative, double &d) {
51  // we start with a fast path
52  // It was described in
53  // Clinger WD. How to read floating point numbers accurately.
54  // ACM SIGPLAN Notices. 1990
55 #ifndef FLT_EVAL_METHOD
56 #error "FLT_EVAL_METHOD should be defined, please include cfloat."
57 #endif
58 #if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0)
59  // We cannot be certain that x/y is rounded to nearest.
60  if (0 <= power && power <= 22 && i <= 9007199254740991)
61 #else
62  if (-22 <= power && power <= 22 && i <= 9007199254740991)
63 #endif
64  {
65  // convert the integer into a double. This is lossless since
66  // 0 <= i <= 2^53 - 1.
67  d = double(i);
68  //
69  // The general idea is as follows.
70  // If 0 <= s < 2^53 and if 10^0 <= p <= 10^22 then
71  // 1) Both s and p can be represented exactly as 64-bit floating-point
72  // values
73  // (binary64).
74  // 2) Because s and p can be represented exactly as floating-point values,
75  // then s * p
76  // and s / p will produce correctly rounded values.
77  //
78  if (power < 0) {
79  d = d / simdjson::internal::power_of_ten[-power];
80  } else {
81  d = d * simdjson::internal::power_of_ten[power];
82  }
83  if (negative) {
84  d = -d;
85  }
86  return true;
87  }
88  // When 22 < power && power < 22 + 16, we could
89  // hope for another, secondary fast path. It was
90  // described by David M. Gay in "Correctly rounded
91  // binary-decimal and decimal-binary conversions." (1990)
92  // If you need to compute i * 10^(22 + x) for x < 16,
93  // first compute i * 10^x, if you know that result is exact
94  // (e.g., when i * 10^x < 2^53),
95  // then you can still proceed and do (i * 10^x) * 10^22.
96  // Is this worth your time?
97  // You need 22 < power *and* power < 22 + 16 *and* (i * 10^(x-22) < 2^53)
98  // for this second fast path to work.
99  // If you you have 22 < power *and* power < 22 + 16, and then you
100  // optimistically compute "i * 10^(x-22)", there is still a chance that you
101  // have wasted your time if i * 10^(x-22) >= 2^53. It makes the use cases of
102  // this optimization maybe less common than we would like. Source:
103  // http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
104  // also used in RapidJSON: https://rapidjson.org/strtod_8h_source.html
105 
106  // The fast path has now failed, so we are failing back on the slower path.
107 
108  // In the slow path, we need to adjust i so that it is > 1<<63 which is always
109  // possible, except if i == 0, so we handle i == 0 separately.
110  if(i == 0) {
111  d = negative ? -0.0 : 0.0;
112  return true;
113  }
114 
115 
116  // The exponent is 1024 + 63 + power
117  // + floor(log(5**power)/log(2)).
118  // The 1024 comes from the ieee64 standard.
119  // The 63 comes from the fact that we use a 64-bit word.
120  //
121  // Computing floor(log(5**power)/log(2)) could be
122  // slow. Instead we use a fast function.
123  //
124  // For power in (-400,350), we have that
125  // (((152170 + 65536) * power ) >> 16);
126  // is equal to
127  // floor(log(5**power)/log(2)) + power when power >= 0
128  // and it is equal to
129  // ceil(log(5**-power)/log(2)) + power when power < 0
130  //
131  // The 65536 is (1<<16) and corresponds to
132  // (65536 * power) >> 16 ---> power
133  //
134  // ((152170 * power ) >> 16) is equal to
135  // floor(log(5**power)/log(2))
136  //
137  // Note that this is not magic: 152170/(1<<16) is
138  // approximatively equal to log(5)/log(2).
139  // The 1<<16 value is a power of two; we could use a
140  // larger power of 2 if we wanted to.
141  //
142  int64_t exponent = (((152170 + 65536) * power) >> 16) + 1024 + 63;
143 
144 
145  // We want the most significant bit of i to be 1. Shift if needed.
146  int lz = leading_zeroes(i);
147  i <<= lz;
148 
149 
150  // We are going to need to do some 64-bit arithmetic to get a precise product.
151  // We use a table lookup approach.
152  // It is safe because
153  // power >= smallest_power
154  // and power <= largest_power
155  // We recover the mantissa of the power, it has a leading 1. It is always
156  // rounded down.
157  //
158  // We want the most significant 64 bits of the product. We know
159  // this will be non-zero because the most significant bit of i is
160  // 1.
161  const uint32_t index = 2 * uint32_t(power - simdjson::internal::smallest_power);
162  // 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.)
163  //
164  // The full_multiplication function computes the 128-bit product of two 64-bit words
165  // with a returned value of type value128 with a "low component" corresponding to the
166  // 64-bit least significant bits of the product and with a "high component" corresponding
167  // to the 64-bit most significant bits of the product.
168  simdjson::internal::value128 firstproduct = full_multiplication(i, simdjson::internal::power_of_five_128[index]);
169  // Both i and power_of_five_128[index] have their most significant bit set to 1 which
170  // implies that the either the most or the second most significant bit of the product
171  // is 1. We pack values in this manner for efficiency reasons: it maximizes the use
172  // we make of the product. It also makes it easy to reason about the product: there
173  // is 0 or 1 leading zero in the product.
174 
175  // Unless the least significant 9 bits of the high (64-bit) part of the full
176  // product are all 1s, then we know that the most significant 55 bits are
177  // exact and no further work is needed. Having 55 bits is necessary because
178  // we need 53 bits for the mantissa but we have to have one rounding bit and
179  // we can waste a bit if the most significant bit of the product is zero.
180  if((firstproduct.high & 0x1FF) == 0x1FF) {
181  // We want to compute i * 5^q, but only care about the top 55 bits at most.
182  // Consider the scenario where q>=0. Then 5^q may not fit in 64-bits. Doing
183  // the full computation is wasteful. So we do what is called a "truncated
184  // multiplication".
185  // We take the most significant 64-bits, and we put them in
186  // power_of_five_128[index]. Usually, that's good enough to approximate i * 5^q
187  // to the desired approximation using one multiplication. Sometimes it does not suffice.
188  // Then we store the next most significant 64 bits in power_of_five_128[index + 1], and
189  // then we get a better approximation to i * 5^q.
190  //
191  // That's for when q>=0. The logic for q<0 is somewhat similar but it is somewhat
192  // more complicated.
193  //
194  // There is an extra layer of complexity in that we need more than 55 bits of
195  // accuracy in the round-to-even scenario.
196  //
197  // The full_multiplication function computes the 128-bit product of two 64-bit words
198  // with a returned value of type value128 with a "low component" corresponding to the
199  // 64-bit least significant bits of the product and with a "high component" corresponding
200  // to the 64-bit most significant bits of the product.
201  simdjson::internal::value128 secondproduct = full_multiplication(i, simdjson::internal::power_of_five_128[index + 1]);
202  firstproduct.low += secondproduct.high;
203  if(secondproduct.high > firstproduct.low) { firstproduct.high++; }
204  // As it has been proven by Noble Mushtak and Daniel Lemire in "Fast Number Parsing Without
205  // Fallback" (https://arxiv.org/abs/2212.06644), at this point we are sure that the product
206  // is sufficiently accurate, and more computation is not needed.
207  }
208  uint64_t lower = firstproduct.low;
209  uint64_t upper = firstproduct.high;
210  // The final mantissa should be 53 bits with a leading 1.
211  // We shift it so that it occupies 54 bits with a leading 1.
213  uint64_t upperbit = upper >> 63;
214  uint64_t mantissa = upper >> (upperbit + 9);
215  lz += int(1 ^ upperbit);
216 
217  // Here we have mantissa < (1<<54).
218  int64_t real_exponent = exponent - lz;
219  if (simdjson_unlikely(real_exponent <= 0)) { // we have a subnormal?
220  // Here have that real_exponent <= 0 so -real_exponent >= 0
221  if(-real_exponent + 1 >= 64) { // if we have more than 64 bits below the minimum exponent, you have a zero for sure.
222  d = negative ? -0.0 : 0.0;
223  return true;
224  }
225  // next line is safe because -real_exponent + 1 < 0
226  mantissa >>= -real_exponent + 1;
227  // Thankfully, we can't have both "round-to-even" and subnormals because
228  // "round-to-even" only occurs for powers close to 0.
229  mantissa += (mantissa & 1); // round up
230  mantissa >>= 1;
231  // There is a weird scenario where we don't have a subnormal but just.
232  // Suppose we start with 2.2250738585072013e-308, we end up
233  // with 0x3fffffffffffff x 2^-1023-53 which is technically subnormal
234  // whereas 0x40000000000000 x 2^-1023-53 is normal. Now, we need to round
235  // up 0x3fffffffffffff x 2^-1023-53 and once we do, we are no longer
236  // subnormal, but we can only know this after rounding.
237  // So we only declare a subnormal if we are smaller than the threshold.
238  real_exponent = (mantissa < (uint64_t(1) << 52)) ? 0 : 1;
239  d = to_double(mantissa, real_exponent, negative);
240  return true;
241  }
242  // We have to round to even. The "to even" part
243  // is only a problem when we are right in between two floats
244  // which we guard against.
245  // If we have lots of trailing zeros, we may fall right between two
246  // floating-point values.
247  //
248  // The round-to-even cases take the form of a number 2m+1 which is in (2^53,2^54]
249  // times a power of two. That is, it is right between a number with binary significand
250  // m and another number with binary significand m+1; and it must be the case
251  // that it cannot be represented by a float itself.
252  //
253  // We must have that w * 10 ^q == (2m+1) * 2^p for some power of two 2^p.
254  // Recall that 10^q = 5^q * 2^q.
255  // When q >= 0, we must have that (2m+1) is divible by 5^q, so 5^q <= 2^54. We have that
256  // 5^23 <= 2^54 and it is the last power of five to qualify, so q <= 23.
257  // When q<0, we have w >= (2m+1) x 5^{-q}. We must have that w<2^{64} so
258  // (2m+1) x 5^{-q} < 2^{64}. We have that 2m+1>2^{53}. Hence, we must have
259  // 2^{53} x 5^{-q} < 2^{64}.
260  // Hence we have 5^{-q} < 2^{11}$ or q>= -4.
261  //
262  // We require lower <= 1 and not lower == 0 because we could not prove that
263  // that lower == 0 is implied; but we could prove that lower <= 1 is a necessary and sufficient test.
264  if (simdjson_unlikely((lower <= 1) && (power >= -4) && (power <= 23) && ((mantissa & 3) == 1))) {
265  if((mantissa << (upperbit + 64 - 53 - 2)) == upper) {
266  mantissa &= ~1; // flip it so that we do not round up
267  }
268  }
269 
270  mantissa += mantissa & 1;
271  mantissa >>= 1;
272 
273  // Here we have mantissa < (1<<53), unless there was an overflow
274  if (mantissa >= (1ULL << 53)) {
276  // This will happen when parsing values such as 7.2057594037927933e+16
278  mantissa = (1ULL << 52);
279  real_exponent++;
280  }
281  mantissa &= ~(1ULL << 52);
282  // we have to check that real_exponent is in range, otherwise we bail out
283  if (simdjson_unlikely(real_exponent > 2046)) {
284  // We have an infinite value!!! We could actually throw an error here if we could.
285  return false;
286  }
287  d = to_double(mantissa, real_exponent, negative);
288  return true;
289 }
290 
291 // We call a fallback floating-point parser that might be slow. Note
292 // it will accept JSON numbers, but the JSON spec. is more restrictive so
293 // before you call parse_float_fallback, you need to have validated the input
294 // string with the JSON grammar.
295 // It will return an error (false) if the parsed number is infinite.
296 // The string parsing itself always succeeds. We know that there is at least
297 // one digit.
298 static bool parse_float_fallback(const uint8_t *ptr, double *outDouble) {
299  *outDouble = simdjson::internal::from_chars(reinterpret_cast<const char *>(ptr));
300  // We do not accept infinite values.
301 
302  // Detecting finite values in a portable manner is ridiculously hard, ideally
303  // we would want to do:
304  // return !std::isfinite(*outDouble);
305  // but that mysteriously fails under legacy/old libc++ libraries, see
306  // https://github.com/simdjson/simdjson/issues/1286
307  //
308  // Therefore, fall back to this solution (the extra parens are there
309  // to handle that max may be a macro on windows).
310  return !(*outDouble > (std::numeric_limits<double>::max)() || *outDouble < std::numeric_limits<double>::lowest());
311 }
312 
313 static bool parse_float_fallback(const uint8_t *ptr, const uint8_t *end_ptr, double *outDouble) {
314  *outDouble = simdjson::internal::from_chars(reinterpret_cast<const char *>(ptr), reinterpret_cast<const char *>(end_ptr));
315  // We do not accept infinite values.
316 
317  // Detecting finite values in a portable manner is ridiculously hard, ideally
318  // we would want to do:
319  // return !std::isfinite(*outDouble);
320  // but that mysteriously fails under legacy/old libc++ libraries, see
321  // https://github.com/simdjson/simdjson/issues/1286
322  //
323  // Therefore, fall back to this solution (the extra parens are there
324  // to handle that max may be a macro on windows).
325  return !(*outDouble > (std::numeric_limits<double>::max)() || *outDouble < std::numeric_limits<double>::lowest());
326 }
327 
328 // check quickly whether the next 8 chars are made of digits
329 // at a glance, it looks better than Mula's
330 // http://0x80.pl/articles/swar-digits-validate.html
331 simdjson_inline bool is_made_of_eight_digits_fast(const uint8_t *chars) {
332  uint64_t val;
333  // this can read up to 7 bytes beyond the buffer size, but we require
334  // SIMDJSON_PADDING of padding
335  static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7");
336  std::memcpy(&val, chars, 8);
337  // a branchy method might be faster:
338  // return (( val & 0xF0F0F0F0F0F0F0F0 ) == 0x3030303030303030)
339  // && (( (val + 0x0606060606060606) & 0xF0F0F0F0F0F0F0F0 ) ==
340  // 0x3030303030303030);
341  return (((val & 0xF0F0F0F0F0F0F0F0) |
342  (((val + 0x0606060606060606) & 0xF0F0F0F0F0F0F0F0) >> 4)) ==
343  0x3333333333333333);
344 }
345 
346 template<typename I>
347 SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later
348 simdjson_inline bool parse_digit(const uint8_t c, I &i) {
349  const uint8_t digit = static_cast<uint8_t>(c - '0');
350  if (digit > 9) {
351  return false;
352  }
353  // PERF NOTE: multiplication by 10 is cheaper than arbitrary integer multiplication
354  i = 10 * i + digit; // might overflow, we will handle the overflow later
355  return true;
356 }
357 
358 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) {
359  // we continue with the fiction that we have an integer. If the
360  // floating point number is representable as x * 10^z for some integer
361  // z that fits in 53 bits, then we will be able to convert back the
362  // the integer into a float in a lossless manner.
363  const uint8_t *const first_after_period = p;
364 
365 #ifdef SIMDJSON_SWAR_NUMBER_PARSING
366 #if SIMDJSON_SWAR_NUMBER_PARSING
367  // this helps if we have lots of decimals!
368  // this turns out to be frequent enough.
369  if (is_made_of_eight_digits_fast(p)) {
370  i = i * 100000000 + parse_eight_digits_unrolled(p);
371  p += 8;
372  }
373 #endif // SIMDJSON_SWAR_NUMBER_PARSING
374 #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING
375  // Unrolling the first digit makes a small difference on some implementations (e.g. westmere)
376  if (parse_digit(*p, i)) { ++p; }
377  while (parse_digit(*p, i)) { p++; }
378  exponent = first_after_period - p;
379  // Decimal without digits (123.) is illegal
380  if (exponent == 0) {
381  return INVALID_NUMBER(src);
382  }
383  return SUCCESS;
384 }
385 
386 simdjson_inline error_code parse_exponent(simdjson_unused const uint8_t *const src, const uint8_t *&p, int64_t &exponent) {
387  // Exp Sign: -123.456e[-]78
388  bool neg_exp = ('-' == *p);
389  if (neg_exp || '+' == *p) { p++; } // Skip + as well
390 
391  // Exponent: -123.456e-[78]
392  auto start_exp = p;
393  int64_t exp_number = 0;
394  while (parse_digit(*p, exp_number)) { ++p; }
395  // It is possible for parse_digit to overflow.
396  // In particular, it could overflow to INT64_MIN, and we cannot do - INT64_MIN.
397  // Thus we *must* check for possible overflow before we negate exp_number.
398 
399  // Performance notes: it may seem like combining the two "simdjson_unlikely checks" below into
400  // a single simdjson_unlikely path would be faster. The reasoning is sound, but the compiler may
401  // not oblige and may, in fact, generate two distinct paths in any case. It might be
402  // possible to do uint64_t(p - start_exp - 1) >= 18 but it could end up trading off
403  // instructions for a simdjson_likely branch, an unconclusive gain.
404 
405  // If there were no digits, it's an error.
406  if (simdjson_unlikely(p == start_exp)) {
407  return INVALID_NUMBER(src);
408  }
409  // We have a valid positive exponent in exp_number at this point, except that
410  // it may have overflowed.
411 
412  // If there were more than 18 digits, we may have overflowed the integer. We have to do
413  // something!!!!
414  if (simdjson_unlikely(p > start_exp+18)) {
415  // Skip leading zeroes: 1e000000000000000000001 is technically valid and doesn't overflow
416  while (*start_exp == '0') { start_exp++; }
417  // 19 digits could overflow int64_t and is kind of absurd anyway. We don't
418  // support exponents smaller than -999,999,999,999,999,999 and bigger
419  // than 999,999,999,999,999,999.
420  // We can truncate.
421  // Note that 999999999999999999 is assuredly too large. The maximal ieee64 value before
422  // infinity is ~1.8e308. The smallest subnormal is ~5e-324. So, actually, we could
423  // truncate at 324.
424  // Note that there is no reason to fail per se at this point in time.
425  // E.g., 0e999999999999999999999 is a fine number.
426  if (p > start_exp+18) { exp_number = 999999999999999999; }
427  }
428  // At this point, we know that exp_number is a sane, positive, signed integer.
429  // It is <= 999,999,999,999,999,999. As long as 'exponent' is in
430  // [-8223372036854775808, 8223372036854775808], we won't overflow. Because 'exponent'
431  // is bounded in magnitude by the size of the JSON input, we are fine in this universe.
432  // To sum it up: the next line should never overflow.
433  exponent += (neg_exp ? -exp_number : exp_number);
434  return SUCCESS;
435 }
436 
437 simdjson_inline size_t significant_digits(const uint8_t * start_digits, size_t digit_count) {
438  // It is possible that the integer had an overflow.
439  // We have to handle the case where we have 0.0000somenumber.
440  const uint8_t *start = start_digits;
441  while ((*start == '0') || (*start == '.')) { ++start; }
442  // we over-decrement by one when there is a '.'
443  return digit_count - size_t(start - start_digits);
444 }
445 
446 } // unnamed namespace
447 
449 template<typename W>
450 error_code slow_float_parsing(simdjson_unused const uint8_t * src, W writer) {
451  double d;
452  if (parse_float_fallback(src, &d)) {
453  writer.append_double(d);
454  return SUCCESS;
455  }
456  return INVALID_NUMBER(src);
457 }
458 
460 template<typename W>
461 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) {
462  // If we frequently had to deal with long strings of digits,
463  // we could extend our code by using a 128-bit integer instead
464  // of a 64-bit integer. However, this is uncommon in practice.
465  //
466  // 9999999999999999999 < 2**64 so we can accommodate 19 digits.
467  // If we have a decimal separator, then digit_count - 1 is the number of digits, but we
468  // may not have a decimal separator!
469  if (simdjson_unlikely(digit_count > 19 && significant_digits(start_digits, digit_count) > 19)) {
470  // Ok, chances are good that we had an overflow!
471  // this is almost never going to get called!!!
472  // we start anew, going slowly!!!
473  // This will happen in the following examples:
474  // 10000000000000000000000000000000000000000000e+308
475  // 3.1415926535897932384626433832795028841971693993751
476  //
477  // NOTE: This makes a *copy* of the writer and passes it to slow_float_parsing. This happens
478  // because slow_float_parsing is a non-inlined function. If we passed our writer reference to
479  // it, it would force it to be stored in memory, preventing the compiler from picking it apart
480  // and putting into registers. i.e. if we pass it as reference, it gets slow.
481  // This is what forces the skip_double, as well.
482  error_code error = slow_float_parsing(src, writer);
483  writer.skip_double();
484  return error;
485  }
486  // NOTE: it's weird that the simdjson_unlikely() only wraps half the if, but it seems to get slower any other
487  // way we've tried: https://github.com/simdjson/simdjson/pull/990#discussion_r448497331
488  // To future reader: we'd love if someone found a better way, or at least could explain this result!
489  if (simdjson_unlikely(exponent < simdjson::internal::smallest_power) || (exponent > simdjson::internal::largest_power)) {
490  //
491  // Important: smallest_power is such that it leads to a zero value.
492  // Observe that 18446744073709551615e-343 == 0, i.e. (2**64 - 1) e -343 is zero
493  // so something x 10^-343 goes to zero, but not so with something x 10^-342.
494  static_assert(simdjson::internal::smallest_power <= -342, "smallest_power is not small enough");
495  //
496  if((exponent < simdjson::internal::smallest_power) || (i == 0)) {
497  // E.g. Parse "-0.0e-999" into the same value as "-0.0". See https://en.wikipedia.org/wiki/Signed_zero
498  WRITE_DOUBLE(negative ? -0.0 : 0.0, src, writer);
499  return SUCCESS;
500  } else { // (exponent > largest_power) and (i != 0)
501  // We have, for sure, an infinite value and simdjson refuses to parse infinite values.
502  return INVALID_NUMBER(src);
503  }
504  }
505  double d;
506  if (!compute_float_64(exponent, i, negative, d)) {
507  // we are almost never going to get here.
508  if (!parse_float_fallback(src, &d)) { return INVALID_NUMBER(src); }
509  }
510  WRITE_DOUBLE(d, src, writer);
511  return SUCCESS;
512 }
513 
514 // for performance analysis, it is sometimes useful to skip parsing
515 #ifdef SIMDJSON_SKIPNUMBERPARSING
516 
517 template<typename W>
518 simdjson_inline error_code parse_number(const uint8_t *const, W &writer) {
519  writer.append_s64(0); // always write zero
520  return SUCCESS; // always succeeds
521 }
522 
523 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const uint8_t * const src) noexcept { return 0; }
524 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uint8_t * const src) noexcept { return 0; }
525 simdjson_unused simdjson_inline simdjson_result<double> parse_double(const uint8_t * const src) noexcept { return 0; }
526 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { return 0; }
527 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t * const src) noexcept { return 0; }
528 simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * const src) noexcept { return 0; }
529 simdjson_unused simdjson_inline bool is_negative(const uint8_t * src) noexcept { return false; }
530 simdjson_unused simdjson_inline simdjson_result<bool> is_integer(const uint8_t * src) noexcept { return false; }
531 simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(const uint8_t * src) noexcept { return number_type::signed_integer; }
532 #else
533 
534 // parse the number at src
535 // define JSON_TEST_NUMBERS for unit testing
536 //
537 // It is assumed that the number is followed by a structural ({,},],[) character
538 // or a white space character. If that is not the case (e.g., when the JSON
539 // document is made of a single number), then it is necessary to copy the
540 // content and append a space before calling this function.
541 //
542 // Our objective is accurate parsing (ULP of 0) at high speed.
543 template<typename W>
544 simdjson_inline error_code parse_number(const uint8_t *const src, W &writer) {
545 
546  //
547  // Check for minus sign
548  //
549  bool negative = (*src == '-');
550  const uint8_t *p = src + uint8_t(negative);
551 
552  //
553  // Parse the integer part.
554  //
555  // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
556  const uint8_t *const start_digits = p;
557  uint64_t i = 0;
558  while (parse_digit(*p, i)) { p++; }
559 
560  // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
561  // Optimization note: size_t is expected to be unsigned.
562  size_t digit_count = size_t(p - start_digits);
563  if (digit_count == 0 || ('0' == *start_digits && digit_count > 1)) { return INVALID_NUMBER(src); }
564 
565  //
566  // Handle floats if there is a . or e (or both)
567  //
568  int64_t exponent = 0;
569  bool is_float = false;
570  if ('.' == *p) {
571  is_float = true;
572  ++p;
573  SIMDJSON_TRY( parse_decimal_after_separator(src, p, i, exponent) );
574  digit_count = int(p - start_digits); // used later to guard against overflows
575  }
576  if (('e' == *p) || ('E' == *p)) {
577  is_float = true;
578  ++p;
579  SIMDJSON_TRY( parse_exponent(src, p, exponent) );
580  }
581  if (is_float) {
582  const bool dirty_end = jsoncharutils::is_not_structural_or_whitespace(*p);
583  SIMDJSON_TRY( write_float(src, negative, i, start_digits, digit_count, exponent, writer) );
584  if (dirty_end) { return INVALID_NUMBER(src); }
585  return SUCCESS;
586  }
587 
588  // The longest negative 64-bit number is 19 digits.
589  // The longest positive 64-bit number is 20 digits.
590  // We do it this way so we don't trigger this branch unless we must.
591  size_t longest_digit_count = negative ? 19 : 20;
592  if (digit_count > longest_digit_count) { return INVALID_NUMBER(src); }
593  if (digit_count == longest_digit_count) {
594  if (negative) {
595  // Anything negative above INT64_MAX+1 is invalid
596  if (i > uint64_t(INT64_MAX)+1) { return INVALID_NUMBER(src); }
597  WRITE_INTEGER(~i+1, src, writer);
598  if (jsoncharutils::is_not_structural_or_whitespace(*p)) { return INVALID_NUMBER(src); }
599  return SUCCESS;
600  // Positive overflow check:
601  // - A 20 digit number starting with 2-9 is overflow, because 18,446,744,073,709,551,615 is the
602  // biggest uint64_t.
603  // - A 20 digit number starting with 1 is overflow if it is less than INT64_MAX.
604  // If we got here, it's a 20 digit number starting with the digit "1".
605  // - If a 20 digit number starting with 1 overflowed (i*10+digit), the result will be smaller
606  // than 1,553,255,926,290,448,384.
607  // - That is smaller than the smallest possible 20-digit number the user could write:
608  // 10,000,000,000,000,000,000.
609  // - Therefore, if the number is positive and lower than that, it's overflow.
610  // - The value we are looking at is less than or equal to INT64_MAX.
611  //
612  } else if (src[0] != uint8_t('1') || i <= uint64_t(INT64_MAX)) { return INVALID_NUMBER(src); }
613  }
614 
615  // Write unsigned if it doesn't fit in a signed integer.
616  if (i > uint64_t(INT64_MAX)) {
617  WRITE_UNSIGNED(i, src, writer);
618  } else {
619  WRITE_INTEGER(negative ? (~i+1) : i, src, writer);
620  }
621  if (jsoncharutils::is_not_structural_or_whitespace(*p)) { return INVALID_NUMBER(src); }
622  return SUCCESS;
623 }
624 
625 // Inlineable functions
626 namespace {
627 
628 // This table can be used to characterize the final character of an integer
629 // string. For JSON structural character and allowable white space characters,
630 // we return SUCCESS. For 'e', '.' and 'E', we return INCORRECT_TYPE. Otherwise
631 // we return NUMBER_ERROR.
632 // Optimization note: we could easily reduce the size of the table by half (to 128)
633 // at the cost of an extra branch.
634 // Optimization note: we want the values to use at most 8 bits (not, e.g., 32 bits):
635 static_assert(error_code(uint8_t(NUMBER_ERROR))== NUMBER_ERROR, "bad NUMBER_ERROR cast");
636 static_assert(error_code(uint8_t(SUCCESS))== SUCCESS, "bad NUMBER_ERROR cast");
637 static_assert(error_code(uint8_t(INCORRECT_TYPE))== INCORRECT_TYPE, "bad NUMBER_ERROR cast");
638 
639 const uint8_t integer_string_finisher[256] = {
691  NUMBER_ERROR};
692 
693 // Parse any number from 0 to 18,446,744,073,709,551,615
694 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const uint8_t * const src) noexcept {
695  const uint8_t *p = src;
696  //
697  // Parse the integer part.
698  //
699  // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
700  const uint8_t *const start_digits = p;
701  uint64_t i = 0;
702  while (parse_digit(*p, i)) { p++; }
703 
704  // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
705  // Optimization note: size_t is expected to be unsigned.
706  size_t digit_count = size_t(p - start_digits);
707  // The longest positive 64-bit number is 20 digits.
708  // We do it this way so we don't trigger this branch unless we must.
709  // Optimization note: the compiler can probably merge
710  // ((digit_count == 0) || (digit_count > 20))
711  // into a single branch since digit_count is unsigned.
712  if ((digit_count == 0) || (digit_count > 20)) { return INCORRECT_TYPE; }
713  // Here digit_count > 0.
714  if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
715  // We can do the following...
716  // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
717  // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
718  // }
719  // as a single table lookup:
720  if (integer_string_finisher[*p] != SUCCESS) { return error_code(integer_string_finisher[*p]); }
721 
722  if (digit_count == 20) {
723  // Positive overflow check:
724  // - A 20 digit number starting with 2-9 is overflow, because 18,446,744,073,709,551,615 is the
725  // biggest uint64_t.
726  // - A 20 digit number starting with 1 is overflow if it is less than INT64_MAX.
727  // If we got here, it's a 20 digit number starting with the digit "1".
728  // - If a 20 digit number starting with 1 overflowed (i*10+digit), the result will be smaller
729  // than 1,553,255,926,290,448,384.
730  // - That is smaller than the smallest possible 20-digit number the user could write:
731  // 10,000,000,000,000,000,000.
732  // - Therefore, if the number is positive and lower than that, it's overflow.
733  // - The value we are looking at is less than or equal to INT64_MAX.
734  //
735  if (src[0] != uint8_t('1') || i <= uint64_t(INT64_MAX)) { return INCORRECT_TYPE; }
736  }
737 
738  return i;
739 }
740 
741 
742 // Parse any number from 0 to 18,446,744,073,709,551,615
743 // Never read at src_end or beyond
744 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const uint8_t * const src, const uint8_t * const src_end) noexcept {
745  const uint8_t *p = src;
746  //
747  // Parse the integer part.
748  //
749  // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
750  const uint8_t *const start_digits = p;
751  uint64_t i = 0;
752  while ((p != src_end) && parse_digit(*p, i)) { p++; }
753 
754  // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
755  // Optimization note: size_t is expected to be unsigned.
756  size_t digit_count = size_t(p - start_digits);
757  // The longest positive 64-bit number is 20 digits.
758  // We do it this way so we don't trigger this branch unless we must.
759  // Optimization note: the compiler can probably merge
760  // ((digit_count == 0) || (digit_count > 20))
761  // into a single branch since digit_count is unsigned.
762  if ((digit_count == 0) || (digit_count > 20)) { return INCORRECT_TYPE; }
763  // Here digit_count > 0.
764  if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
765  // We can do the following...
766  // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
767  // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
768  // }
769  // as a single table lookup:
770  if ((p != src_end) && integer_string_finisher[*p] != SUCCESS) { return error_code(integer_string_finisher[*p]); }
771 
772  if (digit_count == 20) {
773  // Positive overflow check:
774  // - A 20 digit number starting with 2-9 is overflow, because 18,446,744,073,709,551,615 is the
775  // biggest uint64_t.
776  // - A 20 digit number starting with 1 is overflow if it is less than INT64_MAX.
777  // If we got here, it's a 20 digit number starting with the digit "1".
778  // - If a 20 digit number starting with 1 overflowed (i*10+digit), the result will be smaller
779  // than 1,553,255,926,290,448,384.
780  // - That is smaller than the smallest possible 20-digit number the user could write:
781  // 10,000,000,000,000,000,000.
782  // - Therefore, if the number is positive and lower than that, it's overflow.
783  // - The value we are looking at is less than or equal to INT64_MAX.
784  //
785  if (src[0] != uint8_t('1') || i <= uint64_t(INT64_MAX)) { return INCORRECT_TYPE; }
786  }
787 
788  return i;
789 }
790 
791 // Parse any number from 0 to 18,446,744,073,709,551,615
792 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept {
793  const uint8_t *p = src + 1;
794  //
795  // Parse the integer part.
796  //
797  // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
798  const uint8_t *const start_digits = p;
799  uint64_t i = 0;
800  while (parse_digit(*p, i)) { p++; }
801 
802  // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
803  // Optimization note: size_t is expected to be unsigned.
804  size_t digit_count = size_t(p - start_digits);
805  // The longest positive 64-bit number is 20 digits.
806  // We do it this way so we don't trigger this branch unless we must.
807  // Optimization note: the compiler can probably merge
808  // ((digit_count == 0) || (digit_count > 20))
809  // into a single branch since digit_count is unsigned.
810  if ((digit_count == 0) || (digit_count > 20)) { return INCORRECT_TYPE; }
811  // Here digit_count > 0.
812  if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
813  // We can do the following...
814  // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
815  // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
816  // }
817  // as a single table lookup:
818  if (*p != '"') { return NUMBER_ERROR; }
819 
820  if (digit_count == 20) {
821  // Positive overflow check:
822  // - A 20 digit number starting with 2-9 is overflow, because 18,446,744,073,709,551,615 is the
823  // biggest uint64_t.
824  // - A 20 digit number starting with 1 is overflow if it is less than INT64_MAX.
825  // If we got here, it's a 20 digit number starting with the digit "1".
826  // - If a 20 digit number starting with 1 overflowed (i*10+digit), the result will be smaller
827  // than 1,553,255,926,290,448,384.
828  // - That is smaller than the smallest possible 20-digit number the user could write:
829  // 10,000,000,000,000,000,000.
830  // - Therefore, if the number is positive and lower than that, it's overflow.
831  // - The value we are looking at is less than or equal to INT64_MAX.
832  //
833  // Note: we use src[1] and not src[0] because src[0] is the quote character in this
834  // instance.
835  if (src[1] != uint8_t('1') || i <= uint64_t(INT64_MAX)) { return INCORRECT_TYPE; }
836  }
837 
838  return i;
839 }
840 
841 // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
842 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uint8_t *src) noexcept {
843  //
844  // Check for minus sign
845  //
846  bool negative = (*src == '-');
847  const uint8_t *p = src + uint8_t(negative);
848 
849  //
850  // Parse the integer part.
851  //
852  // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
853  const uint8_t *const start_digits = p;
854  uint64_t i = 0;
855  while (parse_digit(*p, i)) { p++; }
856 
857  // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
858  // Optimization note: size_t is expected to be unsigned.
859  size_t digit_count = size_t(p - start_digits);
860  // We go from
861  // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
862  // so we can never represent numbers that have more than 19 digits.
863  size_t longest_digit_count = 19;
864  // Optimization note: the compiler can probably merge
865  // ((digit_count == 0) || (digit_count > longest_digit_count))
866  // into a single branch since digit_count is unsigned.
867  if ((digit_count == 0) || (digit_count > longest_digit_count)) { return INCORRECT_TYPE; }
868  // Here digit_count > 0.
869  if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
870  // We can do the following...
871  // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
872  // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
873  // }
874  // as a single table lookup:
875  if(integer_string_finisher[*p] != SUCCESS) { return error_code(integer_string_finisher[*p]); }
876  // Negative numbers have can go down to - INT64_MAX - 1 whereas positive numbers are limited to INT64_MAX.
877  // Performance note: This check is only needed when digit_count == longest_digit_count but it is
878  // so cheap that we might as well always make it.
879  if(i > uint64_t(INT64_MAX) + uint64_t(negative)) { return INCORRECT_TYPE; }
880  return negative ? (~i+1) : i;
881 }
882 
883 // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
884 // Never read at src_end or beyond
885 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uint8_t * const src, const uint8_t * const src_end) noexcept {
886  //
887  // Check for minus sign
888  //
889  if(src == src_end) { return NUMBER_ERROR; }
890  bool negative = (*src == '-');
891  const uint8_t *p = src + uint8_t(negative);
892 
893  //
894  // Parse the integer part.
895  //
896  // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
897  const uint8_t *const start_digits = p;
898  uint64_t i = 0;
899  while ((p != src_end) && parse_digit(*p, i)) { p++; }
900 
901  // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
902  // Optimization note: size_t is expected to be unsigned.
903  size_t digit_count = size_t(p - start_digits);
904  // We go from
905  // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
906  // so we can never represent numbers that have more than 19 digits.
907  size_t longest_digit_count = 19;
908  // Optimization note: the compiler can probably merge
909  // ((digit_count == 0) || (digit_count > longest_digit_count))
910  // into a single branch since digit_count is unsigned.
911  if ((digit_count == 0) || (digit_count > longest_digit_count)) { return INCORRECT_TYPE; }
912  // Here digit_count > 0.
913  if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
914  // We can do the following...
915  // if (!jsoncharutils::is_structural_or_whitespace(*p)) {
916  // return (*p == '.' || *p == 'e' || *p == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
917  // }
918  // as a single table lookup:
919  if((p != src_end) && integer_string_finisher[*p] != SUCCESS) { return error_code(integer_string_finisher[*p]); }
920  // Negative numbers have can go down to - INT64_MAX - 1 whereas positive numbers are limited to INT64_MAX.
921  // Performance note: This check is only needed when digit_count == longest_digit_count but it is
922  // so cheap that we might as well always make it.
923  if(i > uint64_t(INT64_MAX) + uint64_t(negative)) { return INCORRECT_TYPE; }
924  return negative ? (~i+1) : i;
925 }
926 
927 // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
928 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept {
929  //
930  // Check for minus sign
931  //
932  bool negative = (*(src + 1) == '-');
933  src += uint8_t(negative) + 1;
934 
935  //
936  // Parse the integer part.
937  //
938  // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare
939  const uint8_t *const start_digits = src;
940  uint64_t i = 0;
941  while (parse_digit(*src, i)) { src++; }
942 
943  // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error.
944  // Optimization note: size_t is expected to be unsigned.
945  size_t digit_count = size_t(src - start_digits);
946  // We go from
947  // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
948  // so we can never represent numbers that have more than 19 digits.
949  size_t longest_digit_count = 19;
950  // Optimization note: the compiler can probably merge
951  // ((digit_count == 0) || (digit_count > longest_digit_count))
952  // into a single branch since digit_count is unsigned.
953  if ((digit_count == 0) || (digit_count > longest_digit_count)) { return INCORRECT_TYPE; }
954  // Here digit_count > 0.
955  if (('0' == *start_digits) && (digit_count > 1)) { return NUMBER_ERROR; }
956  // We can do the following...
957  // if (!jsoncharutils::is_structural_or_whitespace(*src)) {
958  // return (*src == '.' || *src == 'e' || *src == 'E') ? INCORRECT_TYPE : NUMBER_ERROR;
959  // }
960  // as a single table lookup:
961  if(*src != '"') { return NUMBER_ERROR; }
962  // Negative numbers have can go down to - INT64_MAX - 1 whereas positive numbers are limited to INT64_MAX.
963  // Performance note: This check is only needed when digit_count == longest_digit_count but it is
964  // so cheap that we might as well always make it.
965  if(i > uint64_t(INT64_MAX) + uint64_t(negative)) { return INCORRECT_TYPE; }
966  return negative ? (~i+1) : i;
967 }
968 
969 simdjson_unused simdjson_inline simdjson_result<double> parse_double(const uint8_t * src) noexcept {
970  //
971  // Check for minus sign
972  //
973  bool negative = (*src == '-');
974  src += uint8_t(negative);
975 
976  //
977  // Parse the integer part.
978  //
979  uint64_t i = 0;
980  const uint8_t *p = src;
981  p += parse_digit(*p, i);
982  bool leading_zero = (i == 0);
983  while (parse_digit(*p, i)) { p++; }
984  // no integer digits, or 0123 (zero must be solo)
985  if ( p == src ) { return INCORRECT_TYPE; }
986  if ( (leading_zero && p != src+1)) { return NUMBER_ERROR; }
987 
988  //
989  // Parse the decimal part.
990  //
991  int64_t exponent = 0;
992  bool overflow;
993  if (simdjson_likely(*p == '.')) {
994  p++;
995  const uint8_t *start_decimal_digits = p;
996  if (!parse_digit(*p, i)) { return NUMBER_ERROR; } // no decimal digits
997  p++;
998  while (parse_digit(*p, i)) { p++; }
999  exponent = -(p - start_decimal_digits);
1000 
1001  // Overflow check. More than 19 digits (minus the decimal) may be overflow.
1002  overflow = p-src-1 > 19;
1003  if (simdjson_unlikely(overflow && leading_zero)) {
1004  // Skip leading 0.00000 and see if it still overflows
1005  const uint8_t *start_digits = src + 2;
1006  while (*start_digits == '0') { start_digits++; }
1007  overflow = start_digits-src > 19;
1008  }
1009  } else {
1010  overflow = p-src > 19;
1011  }
1012 
1013  //
1014  // Parse the exponent
1015  //
1016  if (*p == 'e' || *p == 'E') {
1017  p++;
1018  bool exp_neg = *p == '-';
1019  p += exp_neg || *p == '+';
1020 
1021  uint64_t exp = 0;
1022  const uint8_t *start_exp_digits = p;
1023  while (parse_digit(*p, exp)) { p++; }
1024  // no exp digits, or 20+ exp digits
1025  if (p-start_exp_digits == 0 || p-start_exp_digits > 19) { return NUMBER_ERROR; }
1026 
1027  exponent += exp_neg ? 0-exp : exp;
1028  }
1029 
1030  if (jsoncharutils::is_not_structural_or_whitespace(*p)) { return NUMBER_ERROR; }
1031 
1032  overflow = overflow || exponent < simdjson::internal::smallest_power || exponent > simdjson::internal::largest_power;
1033 
1034  //
1035  // Assemble (or slow-parse) the float
1036  //
1037  double d;
1038  if (simdjson_likely(!overflow)) {
1039  if (compute_float_64(exponent, i, negative, d)) { return d; }
1040  }
1041  if (!parse_float_fallback(src - uint8_t(negative), &d)) {
1042  return NUMBER_ERROR;
1043  }
1044  return d;
1045 }
1046 
1047 simdjson_unused simdjson_inline bool is_negative(const uint8_t * src) noexcept {
1048  return (*src == '-');
1049 }
1050 
1051 simdjson_unused simdjson_inline simdjson_result<bool> is_integer(const uint8_t * src) noexcept {
1052  bool negative = (*src == '-');
1053  src += uint8_t(negative);
1054  const uint8_t *p = src;
1055  while(static_cast<uint8_t>(*p - '0') <= 9) { p++; }
1056  if ( p == src ) { return NUMBER_ERROR; }
1057  if (jsoncharutils::is_structural_or_whitespace(*p)) { return true; }
1058  return false;
1059 }
1060 
1061 simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(const uint8_t * src) noexcept {
1062  bool negative = (*src == '-');
1063  src += uint8_t(negative);
1064  const uint8_t *p = src;
1065  while(static_cast<uint8_t>(*p - '0') <= 9) { p++; }
1066  if ( p == src ) { return NUMBER_ERROR; }
1067  if (jsoncharutils::is_structural_or_whitespace(*p)) {
1068  // We have an integer.
1069  // If the number is negative and valid, it must be a signed integer.
1070  if(negative) { return number_type::signed_integer; }
1071  // We want values larger or equal to 9223372036854775808 to be unsigned
1072  // integers, and the other values to be signed integers.
1073  int digit_count = int(p - src);
1074  if(digit_count >= 19) {
1075  const uint8_t * smaller_big_integer = reinterpret_cast<const uint8_t *>("9223372036854775808");
1076  if((digit_count >= 20) || (memcmp(src, smaller_big_integer, 19) >= 0)) {
1077  return number_type::unsigned_integer;
1078  }
1079  }
1080  return number_type::signed_integer;
1081  }
1082  // Hopefully, we have 'e' or 'E' or '.'.
1083  return number_type::floating_point_number;
1084 }
1085 
1086 // Never read at src_end or beyond
1087 simdjson_unused simdjson_inline simdjson_result<double> parse_double(const uint8_t * src, const uint8_t * const src_end) noexcept {
1088  if(src == src_end) { return NUMBER_ERROR; }
1089  //
1090  // Check for minus sign
1091  //
1092  bool negative = (*src == '-');
1093  src += uint8_t(negative);
1094 
1095  //
1096  // Parse the integer part.
1097  //
1098  uint64_t i = 0;
1099  const uint8_t *p = src;
1100  if(p == src_end) { return NUMBER_ERROR; }
1101  p += parse_digit(*p, i);
1102  bool leading_zero = (i == 0);
1103  while ((p != src_end) && parse_digit(*p, i)) { p++; }
1104  // no integer digits, or 0123 (zero must be solo)
1105  if ( p == src ) { return INCORRECT_TYPE; }
1106  if ( (leading_zero && p != src+1)) { return NUMBER_ERROR; }
1107 
1108  //
1109  // Parse the decimal part.
1110  //
1111  int64_t exponent = 0;
1112  bool overflow;
1113  if (simdjson_likely((p != src_end) && (*p == '.'))) {
1114  p++;
1115  const uint8_t *start_decimal_digits = p;
1116  if ((p == src_end) || !parse_digit(*p, i)) { return NUMBER_ERROR; } // no decimal digits
1117  p++;
1118  while ((p != src_end) && parse_digit(*p, i)) { p++; }
1119  exponent = -(p - start_decimal_digits);
1120 
1121  // Overflow check. More than 19 digits (minus the decimal) may be overflow.
1122  overflow = p-src-1 > 19;
1123  if (simdjson_unlikely(overflow && leading_zero)) {
1124  // Skip leading 0.00000 and see if it still overflows
1125  const uint8_t *start_digits = src + 2;
1126  while (*start_digits == '0') { start_digits++; }
1127  overflow = start_digits-src > 19;
1128  }
1129  } else {
1130  overflow = p-src > 19;
1131  }
1132 
1133  //
1134  // Parse the exponent
1135  //
1136  if ((p != src_end) && (*p == 'e' || *p == 'E')) {
1137  p++;
1138  if(p == src_end) { return NUMBER_ERROR; }
1139  bool exp_neg = *p == '-';
1140  p += exp_neg || *p == '+';
1141 
1142  uint64_t exp = 0;
1143  const uint8_t *start_exp_digits = p;
1144  while ((p != src_end) && parse_digit(*p, exp)) { p++; }
1145  // no exp digits, or 20+ exp digits
1146  if (p-start_exp_digits == 0 || p-start_exp_digits > 19) { return NUMBER_ERROR; }
1147 
1148  exponent += exp_neg ? 0-exp : exp;
1149  }
1150 
1151  if ((p != src_end) && jsoncharutils::is_not_structural_or_whitespace(*p)) { return NUMBER_ERROR; }
1152 
1153  overflow = overflow || exponent < simdjson::internal::smallest_power || exponent > simdjson::internal::largest_power;
1154 
1155  //
1156  // Assemble (or slow-parse) the float
1157  //
1158  double d;
1159  if (simdjson_likely(!overflow)) {
1160  if (compute_float_64(exponent, i, negative, d)) { return d; }
1161  }
1162  if (!parse_float_fallback(src - uint8_t(negative), src_end, &d)) {
1163  return NUMBER_ERROR;
1164  }
1165  return d;
1166 }
1167 
1168 simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept {
1169  //
1170  // Check for minus sign
1171  //
1172  bool negative = (*(src + 1) == '-');
1173  src += uint8_t(negative) + 1;
1174 
1175  //
1176  // Parse the integer part.
1177  //
1178  uint64_t i = 0;
1179  const uint8_t *p = src;
1180  p += parse_digit(*p, i);
1181  bool leading_zero = (i == 0);
1182  while (parse_digit(*p, i)) { p++; }
1183  // no integer digits, or 0123 (zero must be solo)
1184  if ( p == src ) { return INCORRECT_TYPE; }
1185  if ( (leading_zero && p != src+1)) { return NUMBER_ERROR; }
1186 
1187  //
1188  // Parse the decimal part.
1189  //
1190  int64_t exponent = 0;
1191  bool overflow;
1192  if (simdjson_likely(*p == '.')) {
1193  p++;
1194  const uint8_t *start_decimal_digits = p;
1195  if (!parse_digit(*p, i)) { return NUMBER_ERROR; } // no decimal digits
1196  p++;
1197  while (parse_digit(*p, i)) { p++; }
1198  exponent = -(p - start_decimal_digits);
1199 
1200  // Overflow check. More than 19 digits (minus the decimal) may be overflow.
1201  overflow = p-src-1 > 19;
1202  if (simdjson_unlikely(overflow && leading_zero)) {
1203  // Skip leading 0.00000 and see if it still overflows
1204  const uint8_t *start_digits = src + 2;
1205  while (*start_digits == '0') { start_digits++; }
1206  overflow = start_digits-src > 19;
1207  }
1208  } else {
1209  overflow = p-src > 19;
1210  }
1211 
1212  //
1213  // Parse the exponent
1214  //
1215  if (*p == 'e' || *p == 'E') {
1216  p++;
1217  bool exp_neg = *p == '-';
1218  p += exp_neg || *p == '+';
1219 
1220  uint64_t exp = 0;
1221  const uint8_t *start_exp_digits = p;
1222  while (parse_digit(*p, exp)) { p++; }
1223  // no exp digits, or 20+ exp digits
1224  if (p-start_exp_digits == 0 || p-start_exp_digits > 19) { return NUMBER_ERROR; }
1225 
1226  exponent += exp_neg ? 0-exp : exp;
1227  }
1228 
1229  if (*p != '"') { return NUMBER_ERROR; }
1230 
1231  overflow = overflow || exponent < simdjson::internal::smallest_power || exponent > simdjson::internal::largest_power;
1232 
1233  //
1234  // Assemble (or slow-parse) the float
1235  //
1236  double d;
1237  if (simdjson_likely(!overflow)) {
1238  if (compute_float_64(exponent, i, negative, d)) { return d; }
1239  }
1240  if (!parse_float_fallback(src - uint8_t(negative), &d)) {
1241  return NUMBER_ERROR;
1242  }
1243  return d;
1244 }
1245 
1246 } // unnamed namespace
1247 #endif // SIMDJSON_SKIPNUMBERPARSING
1248 
1249 } // namespace numberparsing
1250 
1251 inline std::ostream& operator<<(std::ostream& out, number_type type) noexcept {
1252  switch (type) {
1253  case number_type::signed_integer: out << "integer in [-9223372036854775808,9223372036854775808)"; break;
1254  case number_type::unsigned_integer: out << "unsigned integer in [9223372036854775808,18446744073709551616)"; break;
1255  case number_type::floating_point_number: out << "floating-point number (binary64)"; break;
1256  default: SIMDJSON_UNREACHABLE();
1257  }
1258  return out;
1259 }
1260 
1261 } // namespace SIMDJSON_IMPLEMENTATION
1262 } // namespace simdjson
1263 
1264 #endif // SIMDJSON_GENERIC_NUMBERPARSING_H
The top level simdjson namespace, containing everything the library provides.
Definition: base.h:8
std::ostream & operator<<(std::ostream &out, error_code error) noexcept
Write the error message to the output stream.
Definition: error-inl.h:35
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:36
@ 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:31