Fix fibers gdb utils script
[folly.git] / folly / Conv.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/Conv.h>
17 #include <array>
18
19 namespace folly {
20 namespace detail {
21
22 namespace {
23
24 /**
25  * Finds the first non-digit in a string. The number of digits
26  * searched depends on the precision of the Tgt integral. Assumes the
27  * string starts with NO whitespace and NO sign.
28  *
29  * The semantics of the routine is:
30  *   for (;; ++b) {
31  *     if (b >= e || !isdigit(*b)) return b;
32  *   }
33  *
34  *  Complete unrolling marks bottom-line (i.e. entire conversion)
35  *  improvements of 20%.
36  */
37 inline const char* findFirstNonDigit(const char* b, const char* e) {
38   for (; b < e; ++b) {
39     auto const c = static_cast<unsigned>(*b) - '0';
40     if (c >= 10) {
41       break;
42     }
43   }
44   return b;
45 }
46
47 // Maximum value of number when represented as a string
48 template <class T>
49 struct MaxString {
50   static const char* const value;
51 };
52
53 template <> const char *const MaxString<uint8_t>::value = "255";
54 template <> const char *const MaxString<uint16_t>::value = "65535";
55 template <> const char *const MaxString<uint32_t>::value = "4294967295";
56 #if __SIZEOF_LONG__ == 4
57 template <> const char *const MaxString<unsigned long>::value =
58   "4294967295";
59 #else
60 template <> const char *const MaxString<unsigned long>::value =
61   "18446744073709551615";
62 #endif
63 static_assert(sizeof(unsigned long) >= 4,
64               "Wrong value for MaxString<unsigned long>::value,"
65               " please update.");
66 template <> const char *const MaxString<unsigned long long>::value =
67   "18446744073709551615";
68 static_assert(sizeof(unsigned long long) >= 8,
69               "Wrong value for MaxString<unsigned long long>::value"
70               ", please update.");
71
72 #if FOLLY_HAVE_INT128_T
73 template <> const char *const MaxString<__uint128_t>::value =
74   "340282366920938463463374607431768211455";
75 #endif
76
77 /*
78  * Lookup tables that converts from a decimal character value to an integral
79  * binary value, shifted by a decimal "shift" multiplier.
80  * For all character values in the range '0'..'9', the table at those
81  * index locations returns the actual decimal value shifted by the multiplier.
82  * For all other values, the lookup table returns an invalid OOR value.
83  */
84 // Out-of-range flag value, larger than the largest value that can fit in
85 // four decimal bytes (9999), but four of these added up together should
86 // still not overflow uint16_t.
87 constexpr int32_t OOR = 10000;
88
89 FOLLY_ALIGNED(16) constexpr uint16_t shift1[] = {
90   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
91   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
92   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
93   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
94   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
95   1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
96   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
97   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
98   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
99   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
100   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
101   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
102   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
103   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
104   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
105   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
106   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
107   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
108   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
109   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
110   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
111   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
112   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
113   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
114   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
115   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
116 };
117
118 FOLLY_ALIGNED(16) constexpr uint16_t shift10[] = {
119   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
120   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
121   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
122   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
123   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
124   10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
125   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
126   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
127   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
128   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
129   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
130   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
131   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
132   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
133   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
134   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
135   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
136   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
137   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
138   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
139   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
140   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
141   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
142   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
143   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
144   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
145 };
146
147 FOLLY_ALIGNED(16) constexpr uint16_t shift100[] = {
148   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
149   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
150   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
151   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
152   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
153   100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
154   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
155   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
156   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
157   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
158   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
159   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
160   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
161   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
162   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
163   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
164   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
165   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
166   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
167   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
168   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
169   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
170   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
171   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
172   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
173   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
174 };
175
176 FOLLY_ALIGNED(16) constexpr uint16_t shift1000[] = {
177   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
178   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
179   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
180   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
181   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
182   1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
183   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
184   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
185   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
186   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
187   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
188   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
189   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
190   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
191   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
192   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
193   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
194   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
195   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
196   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
197   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
198   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
199   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
200   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
201   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
202   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
203 };
204
205 struct ErrorString {
206   const char* string;
207   bool quote;
208 };
209
210 // Keep this in sync with ConversionCode in Conv.h
211 constexpr const std::array<
212     ErrorString,
213     static_cast<std::size_t>(ConversionCode::NUM_ERROR_CODES)>
214     kErrorStrings{{
215         {"Success", true},
216         {"Empty input string", true},
217         {"No digits found in input string", true},
218         {"Integer overflow when parsing bool (must be 0 or 1)", true},
219         {"Invalid value for bool", true},
220         {"Non-digit character found", true},
221         {"Invalid leading character", true},
222         {"Overflow during conversion", true},
223         {"Negative overflow during conversion", true},
224         {"Unable to convert string to floating point value", true},
225         {"Non-whitespace character found after end of conversion", true},
226         {"Overflow during arithmetic conversion", false},
227         {"Negative overflow during arithmetic conversion", false},
228         {"Loss of precision during arithmetic conversion", false},
229     }};
230
231 // Check if ASCII is really ASCII
232 using IsAscii = std::
233     integral_constant<bool, 'A' == 65 && 'Z' == 90 && 'a' == 97 && 'z' == 122>;
234
235 // The code in this file that uses tolower() really only cares about
236 // 7-bit ASCII characters, so we can take a nice shortcut here.
237 inline char tolower_ascii(char in) {
238   return IsAscii::value ? in | 0x20 : std::tolower(in);
239 }
240
241 inline bool bool_str_cmp(const char** b, size_t len, const char* value) {
242   // Can't use strncasecmp, since we want to ensure that the full value matches
243   const char* p = *b;
244   const char* e = *b + len;
245   const char* v = value;
246   while (*v != '\0') {
247     if (p == e || tolower_ascii(*p) != *v) { // value is already lowercase
248       return false;
249     }
250     ++p;
251     ++v;
252   }
253
254   *b = p;
255   return true;
256 }
257
258 } // anonymous namespace
259
260 Expected<bool, ConversionCode> str_to_bool(StringPiece* src) noexcept {
261   auto b = src->begin(), e = src->end();
262   for (;; ++b) {
263     if (b >= e) {
264       return makeUnexpected(ConversionCode::EMPTY_INPUT_STRING);
265     }
266     if (!std::isspace(*b)) {
267       break;
268     }
269   }
270
271   bool result;
272   size_t len = e - b;
273   switch (*b) {
274     case '0':
275     case '1': {
276       result = false;
277       for (; b < e && isdigit(*b); ++b) {
278         if (result || (*b != '0' && *b != '1')) {
279           return makeUnexpected(ConversionCode::BOOL_OVERFLOW);
280         }
281         result = (*b == '1');
282       }
283       break;
284     }
285     case 'y':
286     case 'Y':
287       result = true;
288       if (!bool_str_cmp(&b, len, "yes")) {
289         ++b;  // accept the single 'y' character
290       }
291       break;
292     case 'n':
293     case 'N':
294       result = false;
295       if (!bool_str_cmp(&b, len, "no")) {
296         ++b;
297       }
298       break;
299     case 't':
300     case 'T':
301       result = true;
302       if (!bool_str_cmp(&b, len, "true")) {
303         ++b;
304       }
305       break;
306     case 'f':
307     case 'F':
308       result = false;
309       if (!bool_str_cmp(&b, len, "false")) {
310         ++b;
311       }
312       break;
313     case 'o':
314     case 'O':
315       if (bool_str_cmp(&b, len, "on")) {
316         result = true;
317       } else if (bool_str_cmp(&b, len, "off")) {
318         result = false;
319       } else {
320         return makeUnexpected(ConversionCode::BOOL_INVALID_VALUE);
321       }
322       break;
323     default:
324       return makeUnexpected(ConversionCode::BOOL_INVALID_VALUE);
325   }
326
327   src->assign(b, e);
328
329   return result;
330 }
331
332 /**
333  * StringPiece to double, with progress information. Alters the
334  * StringPiece parameter to munch the already-parsed characters.
335  */
336 template <class Tgt>
337 Expected<Tgt, ConversionCode> str_to_floating(StringPiece* src) noexcept {
338   using namespace double_conversion;
339   static StringToDoubleConverter
340     conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
341          | StringToDoubleConverter::ALLOW_LEADING_SPACES,
342          0.0,
343          // return this for junk input string
344          std::numeric_limits<double>::quiet_NaN(),
345          nullptr, nullptr);
346
347   if (src->empty()) {
348     return makeUnexpected(ConversionCode::EMPTY_INPUT_STRING);
349   }
350
351   int length;
352   auto result = conv.StringToDouble(src->data(),
353                                     static_cast<int>(src->size()),
354                                     &length); // processed char count
355
356   if (!std::isnan(result)) {
357     // If we get here with length = 0, the input string is empty.
358     // If we get here with result = 0.0, it's either because the string
359     // contained only whitespace, or because we had an actual zero value
360     // (with potential trailing junk). If it was only whitespace, we
361     // want to raise an error; length will point past the last character
362     // that was processed, so we need to check if that character was
363     // whitespace or not.
364     if (length == 0 || (result == 0.0 && std::isspace((*src)[length - 1]))) {
365       return makeUnexpected(ConversionCode::EMPTY_INPUT_STRING);
366     }
367     src->advance(length);
368     return result;
369   }
370
371   auto* e = src->end();
372   auto* b =
373       std::find_if_not(src->begin(), e, [](char c) { return std::isspace(c); });
374
375   // There must be non-whitespace, otherwise we would have caught this above
376   assert(b < e);
377   size_t size = e - b;
378
379   bool negative = false;
380   if (*b == '-') {
381     negative = true;
382     ++b;
383     --size;
384   }
385
386   result = 0.0;
387
388   switch (tolower_ascii(*b)) {
389     case 'i':
390       if (size >= 3 && tolower_ascii(b[1]) == 'n' &&
391           tolower_ascii(b[2]) == 'f') {
392         if (size >= 8 && tolower_ascii(b[3]) == 'i' &&
393             tolower_ascii(b[4]) == 'n' && tolower_ascii(b[5]) == 'i' &&
394             tolower_ascii(b[6]) == 't' && tolower_ascii(b[7]) == 'y') {
395           b += 8;
396         } else {
397           b += 3;
398         }
399         result = std::numeric_limits<Tgt>::infinity();
400       }
401       break;
402
403     case 'n':
404       if (size >= 3 && tolower_ascii(b[1]) == 'a' &&
405           tolower_ascii(b[2]) == 'n') {
406         b += 3;
407         result = std::numeric_limits<Tgt>::quiet_NaN();
408       }
409       break;
410
411     default:
412       break;
413   }
414
415   if (result == 0.0) {
416     // All bets are off
417     return makeUnexpected(ConversionCode::STRING_TO_FLOAT_ERROR);
418   }
419
420   if (negative) {
421     result = -result;
422   }
423
424   src->assign(b, e);
425
426   return result;
427 }
428
429 template Expected<float, ConversionCode> str_to_floating<float>(
430     StringPiece* src) noexcept;
431 template Expected<double, ConversionCode> str_to_floating<double>(
432     StringPiece* src) noexcept;
433
434 /**
435  * This class takes care of additional processing needed for signed values,
436  * like leading sign character and overflow checks.
437  */
438 template <typename T, bool IsSigned = std::is_signed<T>::value>
439 class SignedValueHandler;
440
441 template <typename T>
442 class SignedValueHandler<T, true> {
443  public:
444   ConversionCode init(const char*& b) {
445     negative_ = false;
446     if (!std::isdigit(*b)) {
447       if (*b == '-') {
448         negative_ = true;
449       } else if (UNLIKELY(*b != '+')) {
450         return ConversionCode::INVALID_LEADING_CHAR;
451       }
452       ++b;
453     }
454     return ConversionCode::SUCCESS;
455   }
456
457   ConversionCode overflow() {
458     return negative_ ? ConversionCode::NEGATIVE_OVERFLOW
459                      : ConversionCode::POSITIVE_OVERFLOW;
460   }
461
462   template <typename U>
463   Expected<T, ConversionCode> finalize(U value) {
464     T rv;
465     if (negative_) {
466       rv = -value;
467       if (UNLIKELY(rv > 0)) {
468         return makeUnexpected(ConversionCode::NEGATIVE_OVERFLOW);
469       }
470     } else {
471       rv = value;
472       if (UNLIKELY(rv < 0)) {
473         return makeUnexpected(ConversionCode::POSITIVE_OVERFLOW);
474       }
475     }
476     return rv;
477   }
478
479  private:
480   bool negative_;
481 };
482
483 // For unsigned types, we don't need any extra processing
484 template <typename T>
485 class SignedValueHandler<T, false> {
486  public:
487   ConversionCode init(const char*&) {
488     return ConversionCode::SUCCESS;
489   }
490
491   ConversionCode overflow() {
492     return ConversionCode::POSITIVE_OVERFLOW;
493   }
494
495   Expected<T, ConversionCode> finalize(T value) {
496     return value;
497   }
498 };
499
500 /**
501  * String represented as a pair of pointers to char to signed/unsigned
502  * integrals. Assumes NO whitespace before or after, and also that the
503  * string is composed entirely of digits (and an optional sign only for
504  * signed types). String may be empty, in which case digits_to returns
505  * an appropriate error.
506  */
507 template <class Tgt>
508 inline Expected<Tgt, ConversionCode> digits_to(
509     const char* b,
510     const char* const e) noexcept {
511   using UT = typename std::make_unsigned<Tgt>::type;
512   assert(b <= e);
513
514   SignedValueHandler<Tgt> sgn;
515
516   auto err = sgn.init(b);
517   if (UNLIKELY(err != ConversionCode::SUCCESS)) {
518     return makeUnexpected(err);
519   }
520
521   size_t size = e - b;
522
523   /* Although the string is entirely made of digits, we still need to
524    * check for overflow.
525    */
526   if (size > std::numeric_limits<UT>::digits10) {
527     // Leading zeros?
528     if (b < e && *b == '0') {
529       for (++b;; ++b) {
530         if (b == e) {
531           return Tgt(0); // just zeros, e.g. "0000"
532         }
533         if (*b != '0') {
534           size = e - b;
535           break;
536         }
537       }
538     }
539     if (size > std::numeric_limits<UT>::digits10 &&
540         (size != std::numeric_limits<UT>::digits10 + 1 ||
541          strncmp(b, MaxString<UT>::value, size) > 0)) {
542       return makeUnexpected(sgn.overflow());
543     }
544   }
545
546   // Here we know that the number won't overflow when
547   // converted. Proceed without checks.
548
549   UT result = 0;
550
551   for (; e - b >= 4; b += 4) {
552     result *= 10000;
553     const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
554     const int32_t r1 = shift100[static_cast<size_t>(b[1])];
555     const int32_t r2 = shift10[static_cast<size_t>(b[2])];
556     const int32_t r3 = shift1[static_cast<size_t>(b[3])];
557     const auto sum = r0 + r1 + r2 + r3;
558     if (sum >= OOR) {
559       goto outOfRange;
560     }
561     result += sum;
562   }
563
564   switch (e - b) {
565   case 3: {
566     const int32_t r0 = shift100[static_cast<size_t>(b[0])];
567     const int32_t r1 = shift10[static_cast<size_t>(b[1])];
568     const int32_t r2 = shift1[static_cast<size_t>(b[2])];
569     const auto sum = r0 + r1 + r2;
570     if (sum >= OOR) {
571       goto outOfRange;
572     }
573     result = 1000 * result + sum;
574     break;
575   }
576   case 2: {
577     const int32_t r0 = shift10[static_cast<size_t>(b[0])];
578     const int32_t r1 = shift1[static_cast<size_t>(b[1])];
579     const auto sum = r0 + r1;
580     if (sum >= OOR) {
581       goto outOfRange;
582     }
583     result = 100 * result + sum;
584     break;
585   }
586   case 1: {
587     const int32_t sum = shift1[static_cast<size_t>(b[0])];
588     if (sum >= OOR) {
589       goto outOfRange;
590     }
591     result = 10 * result + sum;
592     break;
593   }
594   default:
595     assert(b == e);
596     if (size == 0) {
597       return makeUnexpected(ConversionCode::NO_DIGITS);
598     }
599     break;
600   }
601
602   return sgn.finalize(result);
603
604 outOfRange:
605   return makeUnexpected(ConversionCode::NON_DIGIT_CHAR);
606 }
607
608 template Expected<char, ConversionCode> digits_to<char>(
609     const char*,
610     const char*) noexcept;
611 template Expected<signed char, ConversionCode> digits_to<signed char>(
612     const char*,
613     const char*) noexcept;
614 template Expected<unsigned char, ConversionCode> digits_to<unsigned char>(
615     const char*,
616     const char*) noexcept;
617
618 template Expected<short, ConversionCode> digits_to<short>(
619     const char*,
620     const char*) noexcept;
621 template Expected<unsigned short, ConversionCode> digits_to<unsigned short>(
622     const char*,
623     const char*) noexcept;
624
625 template Expected<int, ConversionCode> digits_to<int>(
626     const char*,
627     const char*) noexcept;
628 template Expected<unsigned int, ConversionCode> digits_to<unsigned int>(
629     const char*,
630     const char*) noexcept;
631
632 template Expected<long, ConversionCode> digits_to<long>(
633     const char*,
634     const char*) noexcept;
635 template Expected<unsigned long, ConversionCode> digits_to<unsigned long>(
636     const char*,
637     const char*) noexcept;
638
639 template Expected<long long, ConversionCode> digits_to<long long>(
640     const char*,
641     const char*) noexcept;
642 template Expected<unsigned long long, ConversionCode>
643 digits_to<unsigned long long>(const char*, const char*) noexcept;
644
645 #if FOLLY_HAVE_INT128_T
646 template Expected<__int128, ConversionCode> digits_to<__int128>(
647     const char*,
648     const char*) noexcept;
649 template Expected<unsigned __int128, ConversionCode>
650 digits_to<unsigned __int128>(const char*, const char*) noexcept;
651 #endif
652
653 /**
654  * StringPiece to integrals, with progress information. Alters the
655  * StringPiece parameter to munch the already-parsed characters.
656  */
657 template <class Tgt>
658 Expected<Tgt, ConversionCode> str_to_integral(StringPiece* src) noexcept {
659   using UT = typename std::make_unsigned<Tgt>::type;
660
661   auto b = src->data(), past = src->data() + src->size();
662
663   for (;; ++b) {
664     if (UNLIKELY(b >= past)) {
665       return makeUnexpected(ConversionCode::EMPTY_INPUT_STRING);
666     }
667     if (!std::isspace(*b)) {
668       break;
669     }
670   }
671
672   SignedValueHandler<Tgt> sgn;
673   auto err = sgn.init(b);
674
675   if (UNLIKELY(err != ConversionCode::SUCCESS)) {
676     return makeUnexpected(err);
677   }
678   if (std::is_signed<Tgt>::value && UNLIKELY(b >= past)) {
679     return makeUnexpected(ConversionCode::NO_DIGITS);
680   }
681   if (UNLIKELY(!isdigit(*b))) {
682     return makeUnexpected(ConversionCode::NON_DIGIT_CHAR);
683   }
684
685   auto m = findFirstNonDigit(b + 1, past);
686
687   auto tmp = digits_to<UT>(b, m);
688
689   if (UNLIKELY(!tmp.hasValue())) {
690     return makeUnexpected(
691         tmp.error() == ConversionCode::POSITIVE_OVERFLOW ? sgn.overflow()
692                                                          : tmp.error());
693   }
694
695   auto res = sgn.finalize(tmp.value());
696
697   if (res.hasValue()) {
698     src->advance(m - src->data());
699   }
700
701   return res;
702 }
703
704 template Expected<char, ConversionCode> str_to_integral<char>(
705     StringPiece* src) noexcept;
706 template Expected<signed char, ConversionCode> str_to_integral<signed char>(
707     StringPiece* src) noexcept;
708 template Expected<unsigned char, ConversionCode> str_to_integral<unsigned char>(
709     StringPiece* src) noexcept;
710
711 template Expected<short, ConversionCode> str_to_integral<short>(
712     StringPiece* src) noexcept;
713 template Expected<unsigned short, ConversionCode>
714 str_to_integral<unsigned short>(StringPiece* src) noexcept;
715
716 template Expected<int, ConversionCode> str_to_integral<int>(
717     StringPiece* src) noexcept;
718 template Expected<unsigned int, ConversionCode> str_to_integral<unsigned int>(
719     StringPiece* src) noexcept;
720
721 template Expected<long, ConversionCode> str_to_integral<long>(
722     StringPiece* src) noexcept;
723 template Expected<unsigned long, ConversionCode> str_to_integral<unsigned long>(
724     StringPiece* src) noexcept;
725
726 template Expected<long long, ConversionCode> str_to_integral<long long>(
727     StringPiece* src) noexcept;
728 template Expected<unsigned long long, ConversionCode>
729 str_to_integral<unsigned long long>(StringPiece* src) noexcept;
730
731 #if FOLLY_HAVE_INT128_T
732 template Expected<__int128, ConversionCode> str_to_integral<__int128>(
733     StringPiece* src) noexcept;
734 template Expected<unsigned __int128, ConversionCode>
735 str_to_integral<unsigned __int128>(StringPiece* src) noexcept;
736 #endif
737
738 } // namespace detail
739
740 ConversionError makeConversionError(ConversionCode code, StringPiece input) {
741   using namespace detail;
742   static_assert(
743       std::is_unsigned<std::underlying_type<ConversionCode>::type>::value,
744       "ConversionCode should be unsigned");
745   assert((std::size_t)code < kErrorStrings.size());
746   const ErrorString& err = kErrorStrings[(std::size_t)code];
747   if (code == ConversionCode::EMPTY_INPUT_STRING && input.empty()) {
748     return {err.string, code};
749   }
750   std::string tmp(err.string);
751   tmp.append(": ");
752   if (err.quote) {
753     tmp.append(1, '"');
754   }
755   if (input.size() > 0) {
756     tmp.append(input.data(), input.size());
757   }
758   if (err.quote) {
759     tmp.append(1, '"');
760   }
761   return {tmp, code};
762 }
763
764 } // namespace folly