Adding a unit test for HHWheelTimer exercising the default timeout functionality.
[folly.git] / folly / Conv.h
1 /*
2  * Copyright 2015 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
17 /**
18  * Converts anything to anything, with an emphasis on performance and
19  * safety.
20  *
21  * @author Andrei Alexandrescu (andrei.alexandrescu@fb.com)
22  */
23
24 #ifndef FOLLY_BASE_CONV_H_
25 #define FOLLY_BASE_CONV_H_
26
27 #include <folly/FBString.h>
28 #include <folly/Likely.h>
29 #include <folly/Preprocessor.h>
30 #include <folly/Range.h>
31
32 #include <boost/implicit_cast.hpp>
33 #include <algorithm>
34 #include <type_traits>
35 #include <limits>
36 #include <string>
37 #include <tuple>
38 #include <stdexcept>
39 #include <typeinfo>
40
41 #include <limits.h>
42
43 // V8 JavaScript implementation
44 #include <double-conversion/double-conversion.h>
45
46 #define FOLLY_RANGE_CHECK_STRINGIZE(x) #x
47 #define FOLLY_RANGE_CHECK_STRINGIZE2(x) FOLLY_RANGE_CHECK_STRINGIZE(x)
48
49 // Android doesn't support std::to_string so just use a placeholder there.
50 #ifdef __ANDROID__
51 #define FOLLY_RANGE_CHECK_TO_STRING(x) std::string("N/A")
52 #else
53 #define FOLLY_RANGE_CHECK_TO_STRING(x) std::to_string(x)
54 #endif
55
56 #define FOLLY_RANGE_CHECK(condition, message, src)                          \
57   ((condition) ? (void)0 : throw std::range_error(                          \
58     (std::string(__FILE__ "(" FOLLY_RANGE_CHECK_STRINGIZE2(__LINE__) "): ") \
59      + (message) + ": '" + (src) + "'").c_str()))
60
61 #define FOLLY_RANGE_CHECK_BEGIN_END(condition, message, b, e)    \
62   FOLLY_RANGE_CHECK(condition, message, std::string((b), (e) - (b)))
63
64 #define FOLLY_RANGE_CHECK_STRINGPIECE(condition, message, sp)    \
65   FOLLY_RANGE_CHECK(condition, message, std::string((sp).data(), (sp).size()))
66
67 namespace folly {
68
69 /**
70  * The identity conversion function.
71  * to<T>(T) returns itself for all types T.
72  */
73 template <class Tgt, class Src>
74 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
75 to(const Src & value) {
76   return value;
77 }
78
79 template <class Tgt, class Src>
80 typename std::enable_if<std::is_same<Tgt, Src>::value, Tgt>::type
81 to(Src && value) {
82   return std::move(value);
83 }
84
85 /*******************************************************************************
86  * Integral to integral
87  ******************************************************************************/
88
89 /**
90  * Checked conversion from integral to integral. The checks are only
91  * performed when meaningful, e.g. conversion from int to long goes
92  * unchecked.
93  */
94 template <class Tgt, class Src>
95 typename std::enable_if<
96   std::is_integral<Src>::value
97   && std::is_integral<Tgt>::value
98   && !std::is_same<Tgt, Src>::value,
99   Tgt>::type
100 to(const Src & value) {
101   /* static */ if (std::numeric_limits<Tgt>::max()
102                    < std::numeric_limits<Src>::max()) {
103     FOLLY_RANGE_CHECK(
104       (!greater_than<Tgt, std::numeric_limits<Tgt>::max()>(value)),
105       "Overflow",
106       FOLLY_RANGE_CHECK_TO_STRING(value));
107   }
108   /* static */ if (std::is_signed<Src>::value &&
109                    (!std::is_signed<Tgt>::value || sizeof(Src) > sizeof(Tgt))) {
110     FOLLY_RANGE_CHECK(
111       (!less_than<Tgt, std::numeric_limits<Tgt>::min()>(value)),
112       "Negative overflow",
113       FOLLY_RANGE_CHECK_TO_STRING(value));
114   }
115   return static_cast<Tgt>(value);
116 }
117
118 /*******************************************************************************
119  * Floating point to floating point
120  ******************************************************************************/
121
122 template <class Tgt, class Src>
123 typename std::enable_if<
124   std::is_floating_point<Tgt>::value
125   && std::is_floating_point<Src>::value
126   && !std::is_same<Tgt, Src>::value,
127   Tgt>::type
128 to(const Src & value) {
129   /* static */ if (std::numeric_limits<Tgt>::max() <
130                    std::numeric_limits<Src>::max()) {
131     FOLLY_RANGE_CHECK(value <= std::numeric_limits<Tgt>::max(),
132                       "Overflow",
133                       FOLLY_RANGE_CHECK_TO_STRING(value));
134     FOLLY_RANGE_CHECK(value >= -std::numeric_limits<Tgt>::max(),
135                       "Negative overflow",
136                       FOLLY_RANGE_CHECK_TO_STRING(value));
137   }
138   return boost::implicit_cast<Tgt>(value);
139 }
140
141 /*******************************************************************************
142  * Anything to string
143  ******************************************************************************/
144
145 namespace detail {
146
147 template <class T>
148 const T& getLastElement(const T & v) {
149   return v;
150 }
151
152 template <class T, class... Ts>
153 typename std::tuple_element<
154   sizeof...(Ts),
155   std::tuple<T, Ts...> >::type const&
156   getLastElement(const T&, const Ts&... vs) {
157   return getLastElement(vs...);
158 }
159
160 // This class exists to specialize away std::tuple_element in the case where we
161 // have 0 template arguments. Without this, Clang/libc++ will blow a
162 // static_assert even if tuple_element is protected by an enable_if.
163 template <class... Ts>
164 struct last_element {
165   typedef typename std::enable_if<
166     sizeof...(Ts) >= 1,
167     typename std::tuple_element<
168       sizeof...(Ts) - 1, std::tuple<Ts...>
169     >::type>::type type;
170 };
171
172 template <>
173 struct last_element<> {
174   typedef void type;
175 };
176
177 } // namespace detail
178
179 /*******************************************************************************
180  * Conversions from integral types to string types.
181  ******************************************************************************/
182
183 #if FOLLY_HAVE_INT128_T
184 namespace detail {
185
186 template <typename IntegerType>
187 constexpr unsigned int
188 digitsEnough() {
189   return ceil((double(sizeof(IntegerType) * CHAR_BIT) * M_LN2) / M_LN10);
190 }
191
192 inline size_t
193 unsafeTelescope128(char * buffer, size_t room, unsigned __int128 x) {
194   typedef unsigned __int128 Usrc;
195   size_t p = room - 1;
196
197   while (x >= (Usrc(1) << 64)) { // Using 128-bit division while needed
198     const auto y = x / 10;
199     const auto digit = x % 10;
200
201     buffer[p--] = '0' + digit;
202     x = y;
203   }
204
205   uint64_t xx = x; // Moving to faster 64-bit division thereafter
206
207   while (xx >= 10) {
208     const auto y = xx / 10ULL;
209     const auto digit = xx % 10ULL;
210
211     buffer[p--] = '0' + digit;
212     xx = y;
213   }
214
215   buffer[p] = '0' + xx;
216
217   return p;
218 }
219
220 }
221 #endif
222
223 /**
224  * Returns the number of digits in the base 10 representation of an
225  * uint64_t. Useful for preallocating buffers and such. It's also used
226  * internally, see below. Measurements suggest that defining a
227  * separate overload for 32-bit integers is not worthwhile.
228  */
229
230 inline uint32_t digits10(uint64_t v) {
231 #ifdef __x86_64__
232
233   // For this arch we can get a little help from specialized CPU instructions
234   // which can count leading zeroes; 64 minus that is appx. log (base 2).
235   // Use that to approximate base-10 digits (log_10) and then adjust if needed.
236
237   // 10^i, defined for i 0 through 19.
238   // This is 20 * 8 == 160 bytes, which fits neatly into 5 cache lines
239   // (assuming a cache line size of 64).
240   static const uint64_t powersOf10[20] FOLLY_ALIGNED(64) = {
241     1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
242     10000000000, 100000000000, 1000000000000, 10000000000000, 100000000000000,
243     1000000000000000, 10000000000000000, 100000000000000000,
244     1000000000000000000, 10000000000000000000UL
245   };
246
247   // "count leading zeroes" operation not valid; for 0; special case this.
248   if UNLIKELY (! v) {
249     return 1;
250   }
251
252   // bits is in the ballpark of log_2(v).
253   const uint8_t leadingZeroes = __builtin_clzll(v);
254   const auto bits = 63 - leadingZeroes;
255
256   // approximate log_10(v) == log_10(2) * bits.
257   // Integer magic below: 77/256 is appx. 0.3010 (log_10(2)).
258   // The +1 is to make this the ceiling of the log_10 estimate.
259   const uint32_t minLength = 1 + ((bits * 77) >> 8);
260
261   // return that log_10 lower bound, plus adjust if input >= 10^(that bound)
262   // in case there's a small error and we misjudged length.
263   return minLength + (uint32_t) (UNLIKELY (v >= powersOf10[minLength]));
264
265 #else
266
267   uint32_t result = 1;
268   for (;;) {
269     if (LIKELY(v < 10)) return result;
270     if (LIKELY(v < 100)) return result + 1;
271     if (LIKELY(v < 1000)) return result + 2;
272     if (LIKELY(v < 10000)) return result + 3;
273     // Skip ahead by 4 orders of magnitude
274     v /= 10000U;
275     result += 4;
276   }
277
278 #endif
279 }
280
281 /**
282  * Copies the ASCII base 10 representation of v into buffer and
283  * returns the number of bytes written. Does NOT append a \0. Assumes
284  * the buffer points to digits10(v) bytes of valid memory. Note that
285  * uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes,
286  * uint16_t needs at most 5 bytes, and so on. Measurements suggest
287  * that defining a separate overload for 32-bit integers is not
288  * worthwhile.
289  *
290  * This primitive is unsafe because it makes the size assumption and
291  * because it does not add a terminating \0.
292  */
293
294 inline uint32_t uint64ToBufferUnsafe(uint64_t v, char *const buffer) {
295   auto const result = digits10(v);
296   // WARNING: using size_t or pointer arithmetic for pos slows down
297   // the loop below 20x. This is because several 32-bit ops can be
298   // done in parallel, but only fewer 64-bit ones.
299   uint32_t pos = result - 1;
300   while (v >= 10) {
301     // Keep these together so a peephole optimization "sees" them and
302     // computes them in one shot.
303     auto const q = v / 10;
304     auto const r = static_cast<uint32_t>(v % 10);
305     buffer[pos--] = '0' + r;
306     v = q;
307   }
308   // Last digit is trivial to handle
309   buffer[pos] = static_cast<uint32_t>(v) + '0';
310   return result;
311 }
312
313 /**
314  * A single char gets appended.
315  */
316 template <class Tgt>
317 void toAppend(char value, Tgt * result) {
318   *result += value;
319 }
320
321 template<class T>
322 constexpr typename std::enable_if<
323   std::is_same<T, char>::value,
324   size_t>::type
325 estimateSpaceNeeded(T) {
326   return 1;
327 }
328
329 /**
330  * Ubiquitous helper template for writing string appenders
331  */
332 template <class T> struct IsSomeString {
333   enum { value = std::is_same<T, std::string>::value
334          || std::is_same<T, fbstring>::value };
335 };
336
337 /**
338  * Everything implicitly convertible to const char* gets appended.
339  */
340 template <class Tgt, class Src>
341 typename std::enable_if<
342   std::is_convertible<Src, const char*>::value
343   && IsSomeString<Tgt>::value>::type
344 toAppend(Src value, Tgt * result) {
345   // Treat null pointers like an empty string, as in:
346   // operator<<(std::ostream&, const char*).
347   const char* c = value;
348   if (c) {
349     result->append(value);
350   }
351 }
352
353 template<class Src>
354 typename std::enable_if<
355   std::is_convertible<Src, const char*>::value,
356   size_t>::type
357 estimateSpaceNeeded(Src value) {
358   const char *c = value;
359   if (c) {
360     return folly::StringPiece(value).size();
361   };
362   return 0;
363 }
364
365 template<class Src>
366 typename std::enable_if<
367   (std::is_convertible<Src, folly::StringPiece>::value ||
368   IsSomeString<Src>::value) &&
369   !std::is_convertible<Src, const char*>::value,
370   size_t>::type
371 estimateSpaceNeeded(Src value) {
372   return folly::StringPiece(value).size();
373 }
374
375 template<class Src>
376 typename std::enable_if<
377   std::is_pointer<Src>::value &&
378   IsSomeString<std::remove_pointer<Src>>::value,
379   size_t>::type
380 estimateSpaceNeeded(Src value) {
381   return value->size();
382 }
383
384 /**
385  * Strings get appended, too.
386  */
387 template <class Tgt, class Src>
388 typename std::enable_if<
389   IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type
390 toAppend(const Src& value, Tgt * result) {
391   result->append(value);
392 }
393
394 /**
395  * and StringPiece objects too
396  */
397 template <class Tgt>
398 typename std::enable_if<
399    IsSomeString<Tgt>::value>::type
400 toAppend(StringPiece value, Tgt * result) {
401   result->append(value.data(), value.size());
402 }
403
404 /**
405  * There's no implicit conversion from fbstring to other string types,
406  * so make a specialization.
407  */
408 template <class Tgt>
409 typename std::enable_if<
410    IsSomeString<Tgt>::value>::type
411 toAppend(const fbstring& value, Tgt * result) {
412   result->append(value.data(), value.size());
413 }
414
415 #if FOLLY_HAVE_INT128_T
416 /**
417  * Special handling for 128 bit integers.
418  */
419
420 template <class Tgt>
421 void
422 toAppend(__int128 value, Tgt * result) {
423   typedef unsigned __int128 Usrc;
424   char buffer[detail::digitsEnough<unsigned __int128>() + 1];
425   size_t p;
426
427   if (value < 0) {
428     p = detail::unsafeTelescope128(buffer, sizeof(buffer), Usrc(-value));
429     buffer[--p] = '-';
430   } else {
431     p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
432   }
433
434   result->append(buffer + p, buffer + sizeof(buffer));
435 }
436
437 template <class Tgt>
438 void
439 toAppend(unsigned __int128 value, Tgt * result) {
440   char buffer[detail::digitsEnough<unsigned __int128>()];
441   size_t p;
442
443   p = detail::unsafeTelescope128(buffer, sizeof(buffer), value);
444
445   result->append(buffer + p, buffer + sizeof(buffer));
446 }
447
448 template<class T>
449 constexpr typename std::enable_if<
450   std::is_same<T, __int128>::value,
451   size_t>::type
452 estimateSpaceNeeded(T) {
453   return detail::digitsEnough<__int128>();
454 }
455
456 template<class T>
457 constexpr typename std::enable_if<
458   std::is_same<T, unsigned __int128>::value,
459   size_t>::type
460 estimateSpaceNeeded(T) {
461   return detail::digitsEnough<unsigned __int128>();
462 }
463
464 #endif
465
466 /**
467  * int32_t and int64_t to string (by appending) go through here. The
468  * result is APPENDED to a preexisting string passed as the second
469  * parameter. This should be efficient with fbstring because fbstring
470  * incurs no dynamic allocation below 23 bytes and no number has more
471  * than 22 bytes in its textual representation (20 for digits, one for
472  * sign, one for the terminating 0).
473  */
474 template <class Tgt, class Src>
475 typename std::enable_if<
476   std::is_integral<Src>::value && std::is_signed<Src>::value &&
477   IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
478 toAppend(Src value, Tgt * result) {
479   char buffer[20];
480   if (value < 0) {
481     result->push_back('-');
482     result->append(buffer, uint64ToBufferUnsafe(-uint64_t(value), buffer));
483   } else {
484     result->append(buffer, uint64ToBufferUnsafe(value, buffer));
485   }
486 }
487
488 template <class Src>
489 typename std::enable_if<
490   std::is_integral<Src>::value && std::is_signed<Src>::value
491   && sizeof(Src) >= 4 && sizeof(Src) < 16,
492   size_t>::type
493 estimateSpaceNeeded(Src value) {
494   if (value < 0) {
495     return 1 + digits10(static_cast<uint64_t>(-value));
496   }
497
498   return digits10(static_cast<uint64_t>(value));
499 }
500
501 /**
502  * As above, but for uint32_t and uint64_t.
503  */
504 template <class Tgt, class Src>
505 typename std::enable_if<
506   std::is_integral<Src>::value && !std::is_signed<Src>::value
507   && IsSomeString<Tgt>::value && sizeof(Src) >= 4>::type
508 toAppend(Src value, Tgt * result) {
509   char buffer[20];
510   result->append(buffer, buffer + uint64ToBufferUnsafe(value, buffer));
511 }
512
513 template <class Src>
514 typename std::enable_if<
515   std::is_integral<Src>::value && !std::is_signed<Src>::value
516   && sizeof(Src) >= 4 && sizeof(Src) < 16,
517   size_t>::type
518 estimateSpaceNeeded(Src value) {
519   return digits10(value);
520 }
521
522 /**
523  * All small signed and unsigned integers to string go through 32-bit
524  * types int32_t and uint32_t, respectively.
525  */
526 template <class Tgt, class Src>
527 typename std::enable_if<
528   std::is_integral<Src>::value
529   && IsSomeString<Tgt>::value && sizeof(Src) < 4>::type
530 toAppend(Src value, Tgt * result) {
531   typedef typename
532     std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
533     Intermediate;
534   toAppend<Tgt>(static_cast<Intermediate>(value), result);
535 }
536
537 template <class Src>
538 typename std::enable_if<
539   std::is_integral<Src>::value
540   && sizeof(Src) < 4
541   && !std::is_same<Src, char>::value,
542   size_t>::type
543 estimateSpaceNeeded(Src value) {
544   typedef typename
545     std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>::type
546     Intermediate;
547   return estimateSpaceNeeded(static_cast<Intermediate>(value));
548 }
549
550 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
551 // std::underlying_type became available by gcc 4.7.0
552
553 /**
554  * Enumerated values get appended as integers.
555  */
556 template <class Tgt, class Src>
557 typename std::enable_if<
558   std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
559 toAppend(Src value, Tgt * result) {
560   toAppend(
561       static_cast<typename std::underlying_type<Src>::type>(value), result);
562 }
563
564 template <class Src>
565 typename std::enable_if<
566   std::is_enum<Src>::value, size_t>::type
567 estimateSpaceNeeded(Src value) {
568   return estimateSpaceNeeded(
569       static_cast<typename std::underlying_type<Src>::type>(value));
570 }
571
572 #else
573
574 /**
575  * Enumerated values get appended as integers.
576  */
577 template <class Tgt, class Src>
578 typename std::enable_if<
579   std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
580 toAppend(Src value, Tgt * result) {
581   /* static */ if (Src(-1) < 0) {
582     /* static */ if (sizeof(Src) <= sizeof(int)) {
583       toAppend(static_cast<int>(value), result);
584     } else {
585       toAppend(static_cast<long>(value), result);
586     }
587   } else {
588     /* static */ if (sizeof(Src) <= sizeof(int)) {
589       toAppend(static_cast<unsigned int>(value), result);
590     } else {
591       toAppend(static_cast<unsigned long>(value), result);
592     }
593   }
594 }
595
596 template <class Src>
597 typename std::enable_if<
598   std::is_enum<Src>::value, size_t>::type
599 estimateSpaceNeeded(Src value) {
600   /* static */ if (Src(-1) < 0) {
601     /* static */ if (sizeof(Src) <= sizeof(int)) {
602       return estimateSpaceNeeded(static_cast<int>(value));
603     } else {
604       return estimateSpaceNeeded(static_cast<long>(value));
605     }
606   } else {
607     /* static */ if (sizeof(Src) <= sizeof(int)) {
608       return estimateSpaceNeeded(static_cast<unsigned int>(value));
609     } else {
610       return estimateSpaceNeeded(static_cast<unsigned long>(value));
611     }
612   }
613 }
614
615 #endif // gcc 4.7 onwards
616
617 /*******************************************************************************
618  * Conversions from floating-point types to string types.
619  ******************************************************************************/
620
621 namespace detail {
622 constexpr int kConvMaxDecimalInShortestLow = -6;
623 constexpr int kConvMaxDecimalInShortestHigh = 21;
624 } // folly::detail
625
626 /** Wrapper around DoubleToStringConverter **/
627 template <class Tgt, class Src>
628 typename std::enable_if<
629   std::is_floating_point<Src>::value
630   && IsSomeString<Tgt>::value>::type
631 toAppend(
632   Src value,
633   Tgt * result,
634   double_conversion::DoubleToStringConverter::DtoaMode mode,
635   unsigned int numDigits) {
636   using namespace double_conversion;
637   DoubleToStringConverter
638     conv(DoubleToStringConverter::NO_FLAGS,
639          "Infinity", "NaN", 'E',
640          detail::kConvMaxDecimalInShortestLow,
641          detail::kConvMaxDecimalInShortestHigh,
642          6,   // max leading padding zeros
643          1);  // max trailing padding zeros
644   char buffer[256];
645   StringBuilder builder(buffer, sizeof(buffer));
646   switch (mode) {
647     case DoubleToStringConverter::SHORTEST:
648       conv.ToShortest(value, &builder);
649       break;
650     case DoubleToStringConverter::FIXED:
651       conv.ToFixed(value, numDigits, &builder);
652       break;
653     default:
654       CHECK(mode == DoubleToStringConverter::PRECISION);
655       conv.ToPrecision(value, numDigits, &builder);
656       break;
657   }
658   const size_t length = builder.position();
659   builder.Finalize();
660   result->append(buffer, length);
661 }
662
663 /**
664  * As above, but for floating point
665  */
666 template <class Tgt, class Src>
667 typename std::enable_if<
668   std::is_floating_point<Src>::value
669   && IsSomeString<Tgt>::value>::type
670 toAppend(Src value, Tgt * result) {
671   toAppend(
672     value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
673 }
674
675 /**
676  * Upper bound of the length of the output from
677  * DoubleToStringConverter::ToShortest(double, StringBuilder*),
678  * as used in toAppend(double, string*).
679  */
680 template <class Src>
681 typename std::enable_if<
682   std::is_floating_point<Src>::value, size_t>::type
683 estimateSpaceNeeded(Src value) {
684   // kBase10MaximalLength is 17. We add 1 for decimal point,
685   // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
686   constexpr int kMaxMantissaSpace =
687     double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
688   // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
689   constexpr int kMaxExponentSpace = 2 + 3;
690   static const int kMaxPositiveSpace = std::max({
691       // E.g. 1.1111111111111111E-100.
692       kMaxMantissaSpace + kMaxExponentSpace,
693       // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
694       kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
695       // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
696       // number > 1 which ToShortest outputs in exponential notation,
697       // so 21 is the longest non-exponential number > 1.
698       detail::kConvMaxDecimalInShortestHigh
699     });
700   return kMaxPositiveSpace + (value < 0);  // +1 for minus sign, if negative
701 }
702
703 /**
704  * This can be specialized, together with adding specialization
705  * for estimateSpaceNeed for your type, so that we allocate
706  * as much as you need instead of the default
707  */
708 template<class Src>
709 struct HasLengthEstimator : std::false_type {};
710
711 template <class Src>
712 constexpr typename std::enable_if<
713   !std::is_fundamental<Src>::value
714 #ifdef FOLLY_HAVE_INT128_T
715   // On OSX 10.10, is_fundamental<__int128> is false :-O
716   && !std::is_same<__int128, Src>::value
717   && !std::is_same<unsigned __int128, Src>::value
718 #endif
719   && !IsSomeString<Src>::value
720   && !std::is_convertible<Src, const char*>::value
721   && !std::is_convertible<Src, StringPiece>::value
722   && !std::is_enum<Src>::value
723   && !HasLengthEstimator<Src>::value,
724   size_t>::type
725 estimateSpaceNeeded(const Src&) {
726   return sizeof(Src) + 1; // dumbest best effort ever?
727 }
728
729 namespace detail {
730
731 inline size_t estimateSpaceToReserve(size_t sofar) {
732   return sofar;
733 }
734
735 template <class T, class... Ts>
736 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
737   return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
738 }
739
740 template<class T>
741 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
742   return sofar + estimateSpaceNeeded(v);
743 }
744
745 template<class...Ts>
746 void reserveInTarget(const Ts&...vs) {
747   getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
748 }
749
750 template<class Delimiter, class...Ts>
751 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
752   static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
753   size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
754   getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
755 }
756
757 /**
758  * Variadic base case: append one element
759  */
760 template <class T, class Tgt>
761 typename std::enable_if<
762   IsSomeString<typename std::remove_pointer<Tgt>::type>
763   ::value>::type
764 toAppendStrImpl(const T& v, Tgt result) {
765   toAppend(v, result);
766 }
767
768 template <class T, class... Ts>
769 typename std::enable_if<sizeof...(Ts) >= 2
770   && IsSomeString<
771   typename std::remove_pointer<
772     typename detail::last_element<Ts...>::type
773   >::type>::value>::type
774 toAppendStrImpl(const T& v, const Ts&... vs) {
775   toAppend(v, getLastElement(vs...));
776   toAppendStrImpl(vs...);
777 }
778
779 template <class Delimiter, class T, class Tgt>
780 typename std::enable_if<
781   IsSomeString<typename std::remove_pointer<Tgt>::type>
782   ::value>::type
783 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
784   toAppend(v, result);
785 }
786
787 template <class Delimiter, class T, class... Ts>
788 typename std::enable_if<sizeof...(Ts) >= 2
789   && IsSomeString<
790   typename std::remove_pointer<
791     typename detail::last_element<Ts...>::type
792   >::type>::value>::type
793 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
794   // we are really careful here, calling toAppend with just one element does
795   // not try to estimate space needed (as we already did that). If we call
796   // toAppend(v, delim, ....) we would do unnecesary size calculation
797   toAppend(v, detail::getLastElement(vs...));
798   toAppend(delim, detail::getLastElement(vs...));
799   toAppendDelimStrImpl(delim, vs...);
800 }
801 } // folly::detail
802
803
804 /**
805  * Variadic conversion to string. Appends each element in turn.
806  * If we have two or more things to append, we it will not reserve
807  * the space for them and will depend on strings exponential growth.
808  * If you just append once consider using toAppendFit which reserves
809  * the space needed (but does not have exponential as a result).
810  */
811 template <class... Ts>
812 typename std::enable_if<sizeof...(Ts) >= 3
813   && IsSomeString<
814   typename std::remove_pointer<
815     typename detail::last_element<Ts...>::type
816   >::type>::value>::type
817 toAppend(const Ts&... vs) {
818   ::folly::detail::toAppendStrImpl(vs...);
819 }
820
821 /**
822  * Special version of the call that preallocates exaclty as much memory
823  * as need for arguments to be stored in target. This means we are
824  * not doing exponential growth when we append. If you are using it
825  * in a loop you are aiming at your foot with a big perf-destroying
826  * bazooka.
827  * On the other hand if you are appending to a string once, this
828  * will probably save a few calls to malloc.
829  */
830 template <class... Ts>
831 typename std::enable_if<
832   IsSomeString<
833   typename std::remove_pointer<
834     typename detail::last_element<Ts...>::type
835   >::type>::value>::type
836 toAppendFit(const Ts&... vs) {
837   ::folly::detail::reserveInTarget(vs...);
838   toAppend(vs...);
839 }
840
841 template <class Ts>
842 void toAppendFit(const Ts&) {}
843
844 /**
845  * Variadic base case: do nothing.
846  */
847 template <class Tgt>
848 typename std::enable_if<IsSomeString<Tgt>::value>::type
849 toAppend(Tgt* result) {
850 }
851
852 /**
853  * Variadic base case: do nothing.
854  */
855 template <class Delimiter, class Tgt>
856 typename std::enable_if<IsSomeString<Tgt>::value>::type
857 toAppendDelim(const Delimiter& delim, Tgt* result) {
858 }
859
860 /**
861  * 1 element: same as toAppend.
862  */
863 template <class Delimiter, class T, class Tgt>
864 typename std::enable_if<IsSomeString<Tgt>::value>::type
865 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
866   toAppend(v, tgt);
867 }
868
869 /**
870  * Append to string with a delimiter in between elements. Check out
871  * comments for toAppend for details about memory allocation.
872  */
873 template <class Delimiter, class... Ts>
874 typename std::enable_if<sizeof...(Ts) >= 3
875   && IsSomeString<
876   typename std::remove_pointer<
877     typename detail::last_element<Ts...>::type
878   >::type>::value>::type
879 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
880   detail::toAppendDelimStrImpl(delim, vs...);
881 }
882
883 /**
884  * Detail in comment for toAppendFit
885  */
886 template <class Delimiter, class... Ts>
887 typename std::enable_if<
888   IsSomeString<
889   typename std::remove_pointer<
890     typename detail::last_element<Ts...>::type
891   >::type>::value>::type
892 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
893   detail::reserveInTargetDelim(delim, vs...);
894   toAppendDelim(delim, vs...);
895 }
896
897 template <class De, class Ts>
898 void toAppendDelimFit(const De&, const Ts&) {}
899
900 /**
901  * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
902  * for all types.
903  */
904 template <class Tgt, class... Ts>
905 typename std::enable_if<
906   IsSomeString<Tgt>::value && (
907     sizeof...(Ts) != 1 ||
908     !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
909   Tgt>::type
910 to(const Ts&... vs) {
911   Tgt result;
912   toAppendFit(vs..., &result);
913   return result;
914 }
915
916 /**
917  * toDelim<SomeString>(SomeString str) returns itself.
918  */
919 template <class Tgt, class Delim, class Src>
920 typename std::enable_if<
921   IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
922   Tgt>::type
923 toDelim(const Delim& delim, const Src & value) {
924   return value;
925 }
926
927 /**
928  * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
929  * back-end for all types.
930  */
931 template <class Tgt, class Delim, class... Ts>
932 typename std::enable_if<
933   IsSomeString<Tgt>::value && (
934     sizeof...(Ts) != 1 ||
935     !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
936   Tgt>::type
937 toDelim(const Delim& delim, const Ts&... vs) {
938   Tgt result;
939   toAppendDelimFit(delim, vs..., &result);
940   return result;
941 }
942
943 /*******************************************************************************
944  * Conversions from string types to integral types.
945  ******************************************************************************/
946
947 namespace detail {
948
949 /**
950  * Finds the first non-digit in a string. The number of digits
951  * searched depends on the precision of the Tgt integral. Assumes the
952  * string starts with NO whitespace and NO sign.
953  *
954  * The semantics of the routine is:
955  *   for (;; ++b) {
956  *     if (b >= e || !isdigit(*b)) return b;
957  *   }
958  *
959  *  Complete unrolling marks bottom-line (i.e. entire conversion)
960  *  improvements of 20%.
961  */
962   template <class Tgt>
963   const char* findFirstNonDigit(const char* b, const char* e) {
964     for (; b < e; ++b) {
965       auto const c = static_cast<unsigned>(*b) - '0';
966       if (c >= 10) break;
967     }
968     return b;
969   }
970
971   // Maximum value of number when represented as a string
972   template <class T> struct MaxString {
973     static const char*const value;
974   };
975
976
977 /*
978  * Lookup tables that converts from a decimal character value to an integral
979  * binary value, shifted by a decimal "shift" multiplier.
980  * For all character values in the range '0'..'9', the table at those
981  * index locations returns the actual decimal value shifted by the multiplier.
982  * For all other values, the lookup table returns an invalid OOR value.
983  */
984 // Out-of-range flag value, larger than the largest value that can fit in
985 // four decimal bytes (9999), but four of these added up together should
986 // still not overflow uint16_t.
987 constexpr int32_t OOR = 10000;
988
989 FOLLY_ALIGNED(16) constexpr uint16_t shift1[] = {
990   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
991   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
992   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
993   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
994   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
995   1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
996   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
997   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
998   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
999   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
1000   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
1001   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
1002   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
1003   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
1004   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
1005   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
1006   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
1007   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
1008   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
1009   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
1010   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
1011   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
1012   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
1013   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
1014   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
1015   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
1016 };
1017
1018 FOLLY_ALIGNED(16) constexpr uint16_t shift10[] = {
1019   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
1020   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
1021   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
1022   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
1023   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
1024   10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
1025   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
1026   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
1027   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
1028   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
1029   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
1030   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
1031   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
1032   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
1033   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
1034   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
1035   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
1036   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
1037   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
1038   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
1039   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
1040   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
1041   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
1042   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
1043   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
1044   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
1045 };
1046
1047 FOLLY_ALIGNED(16) constexpr uint16_t shift100[] = {
1048   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
1049   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
1050   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
1051   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
1052   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
1053   100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1054   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
1055   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
1056   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
1057   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
1058   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
1059   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
1060   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
1061   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
1062   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
1063   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
1064   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
1065   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
1066   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
1067   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
1068   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
1069   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
1070   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
1071   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
1072   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
1073   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
1074 };
1075
1076 FOLLY_ALIGNED(16) constexpr uint16_t shift1000[] = {
1077   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
1078   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
1079   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
1080   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
1081   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
1082   1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1083   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
1084   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
1085   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
1086   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
1087   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
1088   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
1089   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
1090   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
1091   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
1092   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
1093   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
1094   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
1095   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
1096   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
1097   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
1098   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
1099   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
1100   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
1101   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
1102   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
1103 };
1104
1105 /**
1106  * String represented as a pair of pointers to char to unsigned
1107  * integrals. Assumes NO whitespace before or after, and also that the
1108  * string is composed entirely of digits. Tgt must be unsigned, and no
1109  * sign is allowed in the string (even it's '+'). String may be empty,
1110  * in which case digits_to throws.
1111  */
1112   template <class Tgt>
1113   Tgt digits_to(const char * b, const char * e) {
1114
1115     static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1116     assert(b <= e);
1117
1118     const size_t size = e - b;
1119
1120     /* Although the string is entirely made of digits, we still need to
1121      * check for overflow.
1122      */
1123     if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1124       // Leading zeros? If so, recurse to keep things simple
1125       if (b < e && *b == '0') {
1126         for (++b;; ++b) {
1127           if (b == e) return 0; // just zeros, e.g. "0000"
1128           if (*b != '0') return digits_to<Tgt>(b, e);
1129         }
1130       }
1131       FOLLY_RANGE_CHECK_BEGIN_END(
1132         size == std::numeric_limits<Tgt>::digits10 + 1 &&
1133         strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1134         "Numeric overflow upon conversion", b, e);
1135     }
1136
1137     // Here we know that the number won't overflow when
1138     // converted. Proceed without checks.
1139
1140     Tgt result = 0;
1141
1142     for (; e - b >= 4; b += 4) {
1143       result *= 10000;
1144       const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1145       const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1146       const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1147       const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1148       const auto sum = r0 + r1 + r2 + r3;
1149       assert(sum < OOR && "Assumption: string only has digits");
1150       result += sum;
1151     }
1152
1153     switch (e - b) {
1154       case 3: {
1155         const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1156         const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1157         const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1158         const auto sum = r0 + r1 + r2;
1159         assert(sum < OOR && "Assumption: string only has digits");
1160         return result * 1000 + sum;
1161       }
1162       case 2: {
1163         const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1164         const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1165         const auto sum = r0 + r1;
1166         assert(sum < OOR && "Assumption: string only has digits");
1167         return result * 100 + sum;
1168       }
1169       case 1: {
1170         const int32_t sum = shift1[static_cast<size_t>(b[0])];
1171         assert(sum < OOR && "Assumption: string only has digits");
1172         return result * 10 + sum;
1173       }
1174     }
1175
1176     assert(b == e);
1177     FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1178                                 "Found no digits to convert in input", b, e);
1179     return result;
1180   }
1181
1182
1183   bool str_to_bool(StringPiece * src);
1184
1185 }                                 // namespace detail
1186
1187 /**
1188  * String represented as a pair of pointers to char to unsigned
1189  * integrals. Assumes NO whitespace before or after.
1190  */
1191 template <class Tgt>
1192 typename std::enable_if<
1193   std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1194   && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1195   Tgt>::type
1196 to(const char * b, const char * e) {
1197   return detail::digits_to<Tgt>(b, e);
1198 }
1199
1200 /**
1201  * String represented as a pair of pointers to char to signed
1202  * integrals. Assumes NO whitespace before or after. Allows an
1203  * optional leading sign.
1204  */
1205 template <class Tgt>
1206 typename std::enable_if<
1207   std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1208   Tgt>::type
1209 to(const char * b, const char * e) {
1210   FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1211                     to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1212   if (!isdigit(*b)) {
1213     if (*b == '-') {
1214       Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1215       FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1216       return result;
1217     }
1218     FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1219     ++b;
1220   }
1221   Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1222   FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1223   return result;
1224 }
1225
1226 /**
1227  * Parsing strings to integrals. These routines differ from
1228  * to<integral>(string) in that they take a POINTER TO a StringPiece
1229  * and alter that StringPiece to reflect progress information.
1230  */
1231
1232 /**
1233  * StringPiece to integrals, with progress information. Alters the
1234  * StringPiece parameter to munch the already-parsed characters.
1235  */
1236 template <class Tgt>
1237 typename std::enable_if<
1238   std::is_integral<Tgt>::value
1239   && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1240   Tgt>::type
1241 to(StringPiece * src) {
1242
1243   auto b = src->data(), past = src->data() + src->size();
1244   for (;; ++b) {
1245     FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1246                                   "No digits found in input string", *src);
1247     if (!isspace(*b)) break;
1248   }
1249
1250   auto m = b;
1251
1252   // First digit is customized because we test for sign
1253   bool negative = false;
1254   /* static */ if (std::is_signed<Tgt>::value) {
1255     if (!isdigit(*m)) {
1256       if (*m == '-') {
1257         negative = true;
1258       } else {
1259         FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1260                                       "conversion to integral", *src);
1261       }
1262       ++b;
1263       ++m;
1264     }
1265   }
1266   FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1267                                 *src);
1268   FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1269   m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1270
1271   Tgt result;
1272   /* static */ if (!std::is_signed<Tgt>::value) {
1273     result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1274   } else {
1275     auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1276     if (negative) {
1277       result = -t;
1278       FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1279                                     "Negative overflow", *src);
1280     } else {
1281       result = t;
1282       FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1283     }
1284   }
1285   src->advance(m - src->data());
1286   return result;
1287 }
1288
1289 /**
1290  * StringPiece to bool, with progress information. Alters the
1291  * StringPiece parameter to munch the already-parsed characters.
1292  */
1293 template <class Tgt>
1294 typename std::enable_if<
1295   std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1296   Tgt>::type
1297 to(StringPiece * src) {
1298   return detail::str_to_bool(src);
1299 }
1300
1301 namespace detail {
1302
1303 /**
1304  * Enforce that the suffix following a number is made up only of whitespace.
1305  */
1306 inline void enforceWhitespace(const char* b, const char* e) {
1307   for (; b != e; ++b) {
1308     FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1309                                 to<std::string>("Non-whitespace: ", *b),
1310                                 b, e);
1311   }
1312 }
1313
1314 }  // namespace detail
1315
1316 /**
1317  * String or StringPiece to integrals. Accepts leading and trailing
1318  * whitespace, but no non-space trailing characters.
1319  */
1320 template <class Tgt>
1321 typename std::enable_if<
1322   std::is_integral<Tgt>::value,
1323   Tgt>::type
1324 to(StringPiece src) {
1325   Tgt result = to<Tgt>(&src);
1326   detail::enforceWhitespace(src.data(), src.data() + src.size());
1327   return result;
1328 }
1329
1330 /*******************************************************************************
1331  * Conversions from string types to floating-point types.
1332  ******************************************************************************/
1333
1334 /**
1335  * StringPiece to double, with progress information. Alters the
1336  * StringPiece parameter to munch the already-parsed characters.
1337  */
1338 template <class Tgt>
1339 inline typename std::enable_if<
1340   std::is_floating_point<Tgt>::value,
1341   Tgt>::type
1342 to(StringPiece *const src) {
1343   using namespace double_conversion;
1344   static StringToDoubleConverter
1345     conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1346          | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1347          0.0,
1348          // return this for junk input string
1349          std::numeric_limits<double>::quiet_NaN(),
1350          nullptr, nullptr);
1351
1352   FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1353                                 "No digits found in input string", *src);
1354
1355   int length;
1356   auto result = conv.StringToDouble(src->data(),
1357                                     static_cast<int>(src->size()),
1358                                     &length); // processed char count
1359
1360   if (!std::isnan(result)) {
1361     src->advance(length);
1362     return result;
1363   }
1364
1365   for (;; src->advance(1)) {
1366     if (src->empty()) {
1367       throw std::range_error("Unable to convert an empty string"
1368                              " to a floating point value.");
1369     }
1370     if (!isspace(src->front())) {
1371       break;
1372     }
1373   }
1374
1375   // Was that "inf[inity]"?
1376   if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1377         && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1378     if (src->size() >= 8 &&
1379         toupper((*src)[3]) == 'I' &&
1380         toupper((*src)[4]) == 'N' &&
1381         toupper((*src)[5]) == 'I' &&
1382         toupper((*src)[6]) == 'T' &&
1383         toupper((*src)[7]) == 'Y') {
1384       src->advance(8);
1385     } else {
1386       src->advance(3);
1387     }
1388     return std::numeric_limits<Tgt>::infinity();
1389   }
1390
1391   // Was that "-inf[inity]"?
1392   if (src->size() >= 4 && toupper((*src)[0]) == '-'
1393       && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1394       && toupper((*src)[3]) == 'F') {
1395     if (src->size() >= 9 &&
1396         toupper((*src)[4]) == 'I' &&
1397         toupper((*src)[5]) == 'N' &&
1398         toupper((*src)[6]) == 'I' &&
1399         toupper((*src)[7]) == 'T' &&
1400         toupper((*src)[8]) == 'Y') {
1401       src->advance(9);
1402     } else {
1403       src->advance(4);
1404     }
1405     return -std::numeric_limits<Tgt>::infinity();
1406   }
1407
1408   // "nan"?
1409   if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1410         && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1411     src->advance(3);
1412     return std::numeric_limits<Tgt>::quiet_NaN();
1413   }
1414
1415   // "-nan"?
1416   if (src->size() >= 4 &&
1417       toupper((*src)[0]) == '-' &&
1418       toupper((*src)[1]) == 'N' &&
1419       toupper((*src)[2]) == 'A' &&
1420       toupper((*src)[3]) == 'N') {
1421     src->advance(4);
1422     return -std::numeric_limits<Tgt>::quiet_NaN();
1423   }
1424
1425   // All bets are off
1426   throw std::range_error("Unable to convert \"" + src->toString()
1427                          + "\" to a floating point value.");
1428 }
1429
1430 /**
1431  * Any string, const char*, or StringPiece to double.
1432  */
1433 template <class Tgt>
1434 typename std::enable_if<
1435   std::is_floating_point<Tgt>::value,
1436   Tgt>::type
1437 to(StringPiece src) {
1438   Tgt result = to<double>(&src);
1439   detail::enforceWhitespace(src.data(), src.data() + src.size());
1440   return result;
1441 }
1442
1443 /*******************************************************************************
1444  * Integral to floating point and back
1445  ******************************************************************************/
1446
1447 /**
1448  * Checked conversion from integral to flating point and back. The
1449  * result must be convertible back to the source type without loss of
1450  * precision. This seems Draconian but sometimes is what's needed, and
1451  * complements existing routines nicely. For various rounding
1452  * routines, see <math>.
1453  */
1454 template <class Tgt, class Src>
1455 typename std::enable_if<
1456   (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1457   ||
1458   (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1459   Tgt>::type
1460 to(const Src & value) {
1461   Tgt result = value;
1462   auto witness = static_cast<Src>(result);
1463   if (value != witness) {
1464     throw std::range_error(
1465       to<std::string>("to<>: loss of precision when converting ", value,
1466 #ifdef FOLLY_HAS_RTTI
1467                       " to type ", typeid(Tgt).name()
1468 #else
1469                       " to other type"
1470 #endif
1471                       ).c_str());
1472   }
1473   return result;
1474 }
1475
1476 /*******************************************************************************
1477  * Enum to anything and back
1478  ******************************************************************************/
1479
1480 #if defined(__clang__) || __GNUC_PREREQ(4, 7)
1481 // std::underlying_type became available by gcc 4.7.0
1482
1483 template <class Tgt, class Src>
1484 typename std::enable_if<
1485   std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1486 to(const Src & value) {
1487   return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1488 }
1489
1490 template <class Tgt, class Src>
1491 typename std::enable_if<
1492   std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1493 to(const Src & value) {
1494   return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1495 }
1496
1497 #else
1498
1499 template <class Tgt, class Src>
1500 typename std::enable_if<
1501   std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1502 to(const Src & value) {
1503   /* static */ if (Src(-1) < 0) {
1504     /* static */ if (sizeof(Src) <= sizeof(int)) {
1505       return to<Tgt>(static_cast<int>(value));
1506     } else {
1507       return to<Tgt>(static_cast<long>(value));
1508     }
1509   } else {
1510     /* static */ if (sizeof(Src) <= sizeof(int)) {
1511       return to<Tgt>(static_cast<unsigned int>(value));
1512     } else {
1513       return to<Tgt>(static_cast<unsigned long>(value));
1514     }
1515   }
1516 }
1517
1518 template <class Tgt, class Src>
1519 typename std::enable_if<
1520   std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1521 to(const Src & value) {
1522   /* static */ if (Tgt(-1) < 0) {
1523     /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1524       return static_cast<Tgt>(to<int>(value));
1525     } else {
1526       return static_cast<Tgt>(to<long>(value));
1527     }
1528   } else {
1529     /* static */ if (sizeof(Tgt) <= sizeof(int)) {
1530       return static_cast<Tgt>(to<unsigned int>(value));
1531     } else {
1532       return static_cast<Tgt>(to<unsigned long>(value));
1533     }
1534   }
1535 }
1536
1537 #endif // gcc 4.7 onwards
1538
1539 } // namespace folly
1540
1541 // FOLLY_CONV_INTERNAL is defined by Conv.cpp.  Keep the FOLLY_RANGE_CHECK
1542 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1543 // to avoid defining this global macro name in other files that include Conv.h.
1544 #ifndef FOLLY_CONV_INTERNAL
1545 #undef FOLLY_RANGE_CHECK
1546 #undef FOLLY_RANGE_CHECK_BEGIN_END
1547 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1548 #undef FOLLY_RANGE_CHECK_STRINGIZE
1549 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1550 #endif
1551
1552 #endif /* FOLLY_BASE_CONV_H_ */