Drop support for GCC < 4.8 in folly/Conv.h
[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 /**
551  * Enumerated values get appended as integers.
552  */
553 template <class Tgt, class Src>
554 typename std::enable_if<
555   std::is_enum<Src>::value && IsSomeString<Tgt>::value>::type
556 toAppend(Src value, Tgt * result) {
557   toAppend(
558       static_cast<typename std::underlying_type<Src>::type>(value), result);
559 }
560
561 template <class Src>
562 typename std::enable_if<
563   std::is_enum<Src>::value, size_t>::type
564 estimateSpaceNeeded(Src value) {
565   return estimateSpaceNeeded(
566       static_cast<typename std::underlying_type<Src>::type>(value));
567 }
568
569 /*******************************************************************************
570  * Conversions from floating-point types to string types.
571  ******************************************************************************/
572
573 namespace detail {
574 constexpr int kConvMaxDecimalInShortestLow = -6;
575 constexpr int kConvMaxDecimalInShortestHigh = 21;
576 } // folly::detail
577
578 /** Wrapper around DoubleToStringConverter **/
579 template <class Tgt, class Src>
580 typename std::enable_if<
581   std::is_floating_point<Src>::value
582   && IsSomeString<Tgt>::value>::type
583 toAppend(
584   Src value,
585   Tgt * result,
586   double_conversion::DoubleToStringConverter::DtoaMode mode,
587   unsigned int numDigits) {
588   using namespace double_conversion;
589   DoubleToStringConverter
590     conv(DoubleToStringConverter::NO_FLAGS,
591          "Infinity", "NaN", 'E',
592          detail::kConvMaxDecimalInShortestLow,
593          detail::kConvMaxDecimalInShortestHigh,
594          6,   // max leading padding zeros
595          1);  // max trailing padding zeros
596   char buffer[256];
597   StringBuilder builder(buffer, sizeof(buffer));
598   switch (mode) {
599     case DoubleToStringConverter::SHORTEST:
600       conv.ToShortest(value, &builder);
601       break;
602     case DoubleToStringConverter::FIXED:
603       conv.ToFixed(value, numDigits, &builder);
604       break;
605     default:
606       CHECK(mode == DoubleToStringConverter::PRECISION);
607       conv.ToPrecision(value, numDigits, &builder);
608       break;
609   }
610   const size_t length = builder.position();
611   builder.Finalize();
612   result->append(buffer, length);
613 }
614
615 /**
616  * As above, but for floating point
617  */
618 template <class Tgt, class Src>
619 typename std::enable_if<
620   std::is_floating_point<Src>::value
621   && IsSomeString<Tgt>::value>::type
622 toAppend(Src value, Tgt * result) {
623   toAppend(
624     value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);
625 }
626
627 /**
628  * Upper bound of the length of the output from
629  * DoubleToStringConverter::ToShortest(double, StringBuilder*),
630  * as used in toAppend(double, string*).
631  */
632 template <class Src>
633 typename std::enable_if<
634   std::is_floating_point<Src>::value, size_t>::type
635 estimateSpaceNeeded(Src value) {
636   // kBase10MaximalLength is 17. We add 1 for decimal point,
637   // e.g. 10.0/9 is 17 digits and 18 characters, including the decimal point.
638   constexpr int kMaxMantissaSpace =
639     double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1;
640   // strlen("E-") + digits10(numeric_limits<double>::max_exponent10)
641   constexpr int kMaxExponentSpace = 2 + 3;
642   static const int kMaxPositiveSpace = std::max({
643       // E.g. 1.1111111111111111E-100.
644       kMaxMantissaSpace + kMaxExponentSpace,
645       // E.g. 0.000001.1111111111111111, if kConvMaxDecimalInShortestLow is -6.
646       kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow,
647       // If kConvMaxDecimalInShortestHigh is 21, then 1e21 is the smallest
648       // number > 1 which ToShortest outputs in exponential notation,
649       // so 21 is the longest non-exponential number > 1.
650       detail::kConvMaxDecimalInShortestHigh
651     });
652   return kMaxPositiveSpace + (value < 0);  // +1 for minus sign, if negative
653 }
654
655 /**
656  * This can be specialized, together with adding specialization
657  * for estimateSpaceNeed for your type, so that we allocate
658  * as much as you need instead of the default
659  */
660 template<class Src>
661 struct HasLengthEstimator : std::false_type {};
662
663 template <class Src>
664 constexpr typename std::enable_if<
665   !std::is_fundamental<Src>::value
666 #ifdef FOLLY_HAVE_INT128_T
667   // On OSX 10.10, is_fundamental<__int128> is false :-O
668   && !std::is_same<__int128, Src>::value
669   && !std::is_same<unsigned __int128, Src>::value
670 #endif
671   && !IsSomeString<Src>::value
672   && !std::is_convertible<Src, const char*>::value
673   && !std::is_convertible<Src, StringPiece>::value
674   && !std::is_enum<Src>::value
675   && !HasLengthEstimator<Src>::value,
676   size_t>::type
677 estimateSpaceNeeded(const Src&) {
678   return sizeof(Src) + 1; // dumbest best effort ever?
679 }
680
681 namespace detail {
682
683 inline size_t estimateSpaceToReserve(size_t sofar) {
684   return sofar;
685 }
686
687 template <class T, class... Ts>
688 size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) {
689   return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);
690 }
691
692 template<class T>
693 size_t estimateSpaceToReserve(size_t sofar, const T& v) {
694   return sofar + estimateSpaceNeeded(v);
695 }
696
697 template<class...Ts>
698 void reserveInTarget(const Ts&...vs) {
699   getLastElement(vs...)->reserve(estimateSpaceToReserve(0, vs...));
700 }
701
702 template<class Delimiter, class...Ts>
703 void reserveInTargetDelim(const Delimiter& d, const Ts&...vs) {
704   static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
705   size_t fordelim = (sizeof...(vs) - 2) * estimateSpaceToReserve(0, d);
706   getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
707 }
708
709 /**
710  * Variadic base case: append one element
711  */
712 template <class T, class Tgt>
713 typename std::enable_if<
714   IsSomeString<typename std::remove_pointer<Tgt>::type>
715   ::value>::type
716 toAppendStrImpl(const T& v, Tgt result) {
717   toAppend(v, result);
718 }
719
720 template <class T, class... Ts>
721 typename std::enable_if<sizeof...(Ts) >= 2
722   && IsSomeString<
723   typename std::remove_pointer<
724     typename detail::last_element<Ts...>::type
725   >::type>::value>::type
726 toAppendStrImpl(const T& v, const Ts&... vs) {
727   toAppend(v, getLastElement(vs...));
728   toAppendStrImpl(vs...);
729 }
730
731 template <class Delimiter, class T, class Tgt>
732 typename std::enable_if<
733   IsSomeString<typename std::remove_pointer<Tgt>::type>
734   ::value>::type
735 toAppendDelimStrImpl(const Delimiter& delim, const T& v, Tgt result) {
736   toAppend(v, result);
737 }
738
739 template <class Delimiter, class T, class... Ts>
740 typename std::enable_if<sizeof...(Ts) >= 2
741   && IsSomeString<
742   typename std::remove_pointer<
743     typename detail::last_element<Ts...>::type
744   >::type>::value>::type
745 toAppendDelimStrImpl(const Delimiter& delim, const T& v, const Ts&... vs) {
746   // we are really careful here, calling toAppend with just one element does
747   // not try to estimate space needed (as we already did that). If we call
748   // toAppend(v, delim, ....) we would do unnecesary size calculation
749   toAppend(v, detail::getLastElement(vs...));
750   toAppend(delim, detail::getLastElement(vs...));
751   toAppendDelimStrImpl(delim, vs...);
752 }
753 } // folly::detail
754
755
756 /**
757  * Variadic conversion to string. Appends each element in turn.
758  * If we have two or more things to append, we it will not reserve
759  * the space for them and will depend on strings exponential growth.
760  * If you just append once consider using toAppendFit which reserves
761  * the space needed (but does not have exponential as a result).
762  */
763 template <class... Ts>
764 typename std::enable_if<sizeof...(Ts) >= 3
765   && IsSomeString<
766   typename std::remove_pointer<
767     typename detail::last_element<Ts...>::type
768   >::type>::value>::type
769 toAppend(const Ts&... vs) {
770   ::folly::detail::toAppendStrImpl(vs...);
771 }
772
773 /**
774  * Special version of the call that preallocates exaclty as much memory
775  * as need for arguments to be stored in target. This means we are
776  * not doing exponential growth when we append. If you are using it
777  * in a loop you are aiming at your foot with a big perf-destroying
778  * bazooka.
779  * On the other hand if you are appending to a string once, this
780  * will probably save a few calls to malloc.
781  */
782 template <class... Ts>
783 typename std::enable_if<
784   IsSomeString<
785   typename std::remove_pointer<
786     typename detail::last_element<Ts...>::type
787   >::type>::value>::type
788 toAppendFit(const Ts&... vs) {
789   ::folly::detail::reserveInTarget(vs...);
790   toAppend(vs...);
791 }
792
793 template <class Ts>
794 void toAppendFit(const Ts&) {}
795
796 /**
797  * Variadic base case: do nothing.
798  */
799 template <class Tgt>
800 typename std::enable_if<IsSomeString<Tgt>::value>::type
801 toAppend(Tgt* result) {
802 }
803
804 /**
805  * Variadic base case: do nothing.
806  */
807 template <class Delimiter, class Tgt>
808 typename std::enable_if<IsSomeString<Tgt>::value>::type
809 toAppendDelim(const Delimiter& delim, Tgt* result) {
810 }
811
812 /**
813  * 1 element: same as toAppend.
814  */
815 template <class Delimiter, class T, class Tgt>
816 typename std::enable_if<IsSomeString<Tgt>::value>::type
817 toAppendDelim(const Delimiter& delim, const T& v, Tgt* tgt) {
818   toAppend(v, tgt);
819 }
820
821 /**
822  * Append to string with a delimiter in between elements. Check out
823  * comments for toAppend for details about memory allocation.
824  */
825 template <class Delimiter, class... Ts>
826 typename std::enable_if<sizeof...(Ts) >= 3
827   && IsSomeString<
828   typename std::remove_pointer<
829     typename detail::last_element<Ts...>::type
830   >::type>::value>::type
831 toAppendDelim(const Delimiter& delim, const Ts&... vs) {
832   detail::toAppendDelimStrImpl(delim, vs...);
833 }
834
835 /**
836  * Detail in comment for toAppendFit
837  */
838 template <class Delimiter, class... Ts>
839 typename std::enable_if<
840   IsSomeString<
841   typename std::remove_pointer<
842     typename detail::last_element<Ts...>::type
843   >::type>::value>::type
844 toAppendDelimFit(const Delimiter& delim, const Ts&... vs) {
845   detail::reserveInTargetDelim(delim, vs...);
846   toAppendDelim(delim, vs...);
847 }
848
849 template <class De, class Ts>
850 void toAppendDelimFit(const De&, const Ts&) {}
851
852 /**
853  * to<SomeString>(v1, v2, ...) uses toAppend() (see below) as back-end
854  * for all types.
855  */
856 template <class Tgt, class... Ts>
857 typename std::enable_if<
858   IsSomeString<Tgt>::value && (
859     sizeof...(Ts) != 1 ||
860     !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
861   Tgt>::type
862 to(const Ts&... vs) {
863   Tgt result;
864   toAppendFit(vs..., &result);
865   return result;
866 }
867
868 /**
869  * toDelim<SomeString>(SomeString str) returns itself.
870  */
871 template <class Tgt, class Delim, class Src>
872 typename std::enable_if<
873   IsSomeString<Tgt>::value && std::is_same<Tgt, Src>::value,
874   Tgt>::type
875 toDelim(const Delim& delim, const Src & value) {
876   return value;
877 }
878
879 /**
880  * toDelim<SomeString>(delim, v1, v2, ...) uses toAppendDelim() as
881  * back-end for all types.
882  */
883 template <class Tgt, class Delim, class... Ts>
884 typename std::enable_if<
885   IsSomeString<Tgt>::value && (
886     sizeof...(Ts) != 1 ||
887     !std::is_same<Tgt, typename detail::last_element<Ts...>::type>::value),
888   Tgt>::type
889 toDelim(const Delim& delim, const Ts&... vs) {
890   Tgt result;
891   toAppendDelimFit(delim, vs..., &result);
892   return result;
893 }
894
895 /*******************************************************************************
896  * Conversions from string types to integral types.
897  ******************************************************************************/
898
899 namespace detail {
900
901 /**
902  * Finds the first non-digit in a string. The number of digits
903  * searched depends on the precision of the Tgt integral. Assumes the
904  * string starts with NO whitespace and NO sign.
905  *
906  * The semantics of the routine is:
907  *   for (;; ++b) {
908  *     if (b >= e || !isdigit(*b)) return b;
909  *   }
910  *
911  *  Complete unrolling marks bottom-line (i.e. entire conversion)
912  *  improvements of 20%.
913  */
914   template <class Tgt>
915   const char* findFirstNonDigit(const char* b, const char* e) {
916     for (; b < e; ++b) {
917       auto const c = static_cast<unsigned>(*b) - '0';
918       if (c >= 10) break;
919     }
920     return b;
921   }
922
923   // Maximum value of number when represented as a string
924   template <class T> struct MaxString {
925     static const char*const value;
926   };
927
928
929 /*
930  * Lookup tables that converts from a decimal character value to an integral
931  * binary value, shifted by a decimal "shift" multiplier.
932  * For all character values in the range '0'..'9', the table at those
933  * index locations returns the actual decimal value shifted by the multiplier.
934  * For all other values, the lookup table returns an invalid OOR value.
935  */
936 // Out-of-range flag value, larger than the largest value that can fit in
937 // four decimal bytes (9999), but four of these added up together should
938 // still not overflow uint16_t.
939 constexpr int32_t OOR = 10000;
940
941 FOLLY_ALIGNED(16) constexpr uint16_t shift1[] = {
942   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
943   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
944   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
945   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
946   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
947   1, 2, 3, 4, 5, 6, 7, 8, 9, OOR, OOR,
948   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
949   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
950   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
951   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
952   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
953   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
954   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
955   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
956   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
957   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
958   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
959   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
960   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
961   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
962   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
963   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
964   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
965   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
966   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
967   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
968 };
969
970 FOLLY_ALIGNED(16) constexpr uint16_t shift10[] = {
971   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
972   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
973   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
974   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
975   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
976   10, 20, 30, 40, 50, 60, 70, 80, 90, OOR, OOR,
977   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
978   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
979   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
980   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
981   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
982   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
983   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
984   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
985   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
986   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
987   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
988   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
989   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
990   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
991   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
992   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
993   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
994   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
995   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
996   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
997 };
998
999 FOLLY_ALIGNED(16) constexpr uint16_t shift100[] = {
1000   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
1001   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
1002   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
1003   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
1004   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
1005   100, 200, 300, 400, 500, 600, 700, 800, 900, OOR, OOR,
1006   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
1007   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
1008   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
1009   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
1010   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
1011   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
1012   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
1013   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
1014   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
1015   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
1016   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
1017   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
1018   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
1019   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
1020   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
1021   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
1022   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
1023   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
1024   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
1025   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
1026 };
1027
1028 FOLLY_ALIGNED(16) constexpr uint16_t shift1000[] = {
1029   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 0-9
1030   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  10
1031   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  20
1032   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  30
1033   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, 0,         //  40
1034   1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, OOR, OOR,
1035   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  60
1036   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  70
1037   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  80
1038   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  //  90
1039   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 100
1040   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 110
1041   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 120
1042   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 130
1043   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 140
1044   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 150
1045   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 160
1046   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 170
1047   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 180
1048   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 190
1049   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 200
1050   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 210
1051   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 220
1052   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 230
1053   OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR, OOR,  // 240
1054   OOR, OOR, OOR, OOR, OOR, OOR                       // 250
1055 };
1056
1057 /**
1058  * String represented as a pair of pointers to char to unsigned
1059  * integrals. Assumes NO whitespace before or after, and also that the
1060  * string is composed entirely of digits. Tgt must be unsigned, and no
1061  * sign is allowed in the string (even it's '+'). String may be empty,
1062  * in which case digits_to throws.
1063  */
1064   template <class Tgt>
1065   Tgt digits_to(const char * b, const char * e) {
1066
1067     static_assert(!std::is_signed<Tgt>::value, "Unsigned type expected");
1068     assert(b <= e);
1069
1070     const size_t size = e - b;
1071
1072     /* Although the string is entirely made of digits, we still need to
1073      * check for overflow.
1074      */
1075     if (size >= std::numeric_limits<Tgt>::digits10 + 1) {
1076       // Leading zeros? If so, recurse to keep things simple
1077       if (b < e && *b == '0') {
1078         for (++b;; ++b) {
1079           if (b == e) return 0; // just zeros, e.g. "0000"
1080           if (*b != '0') return digits_to<Tgt>(b, e);
1081         }
1082       }
1083       FOLLY_RANGE_CHECK_BEGIN_END(
1084         size == std::numeric_limits<Tgt>::digits10 + 1 &&
1085         strncmp(b, detail::MaxString<Tgt>::value, size) <= 0,
1086         "Numeric overflow upon conversion", b, e);
1087     }
1088
1089     // Here we know that the number won't overflow when
1090     // converted. Proceed without checks.
1091
1092     Tgt result = 0;
1093
1094     for (; e - b >= 4; b += 4) {
1095       result *= 10000;
1096       const int32_t r0 = shift1000[static_cast<size_t>(b[0])];
1097       const int32_t r1 = shift100[static_cast<size_t>(b[1])];
1098       const int32_t r2 = shift10[static_cast<size_t>(b[2])];
1099       const int32_t r3 = shift1[static_cast<size_t>(b[3])];
1100       const auto sum = r0 + r1 + r2 + r3;
1101       assert(sum < OOR && "Assumption: string only has digits");
1102       result += sum;
1103     }
1104
1105     switch (e - b) {
1106       case 3: {
1107         const int32_t r0 = shift100[static_cast<size_t>(b[0])];
1108         const int32_t r1 = shift10[static_cast<size_t>(b[1])];
1109         const int32_t r2 = shift1[static_cast<size_t>(b[2])];
1110         const auto sum = r0 + r1 + r2;
1111         assert(sum < OOR && "Assumption: string only has digits");
1112         return result * 1000 + sum;
1113       }
1114       case 2: {
1115         const int32_t r0 = shift10[static_cast<size_t>(b[0])];
1116         const int32_t r1 = shift1[static_cast<size_t>(b[1])];
1117         const auto sum = r0 + r1;
1118         assert(sum < OOR && "Assumption: string only has digits");
1119         return result * 100 + sum;
1120       }
1121       case 1: {
1122         const int32_t sum = shift1[static_cast<size_t>(b[0])];
1123         assert(sum < OOR && "Assumption: string only has digits");
1124         return result * 10 + sum;
1125       }
1126     }
1127
1128     assert(b == e);
1129     FOLLY_RANGE_CHECK_BEGIN_END(size > 0,
1130                                 "Found no digits to convert in input", b, e);
1131     return result;
1132   }
1133
1134
1135   bool str_to_bool(StringPiece * src);
1136
1137 }                                 // namespace detail
1138
1139 /**
1140  * String represented as a pair of pointers to char to unsigned
1141  * integrals. Assumes NO whitespace before or after.
1142  */
1143 template <class Tgt>
1144 typename std::enable_if<
1145   std::is_integral<Tgt>::value && !std::is_signed<Tgt>::value
1146   && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1147   Tgt>::type
1148 to(const char * b, const char * e) {
1149   return detail::digits_to<Tgt>(b, e);
1150 }
1151
1152 /**
1153  * String represented as a pair of pointers to char to signed
1154  * integrals. Assumes NO whitespace before or after. Allows an
1155  * optional leading sign.
1156  */
1157 template <class Tgt>
1158 typename std::enable_if<
1159   std::is_integral<Tgt>::value && std::is_signed<Tgt>::value,
1160   Tgt>::type
1161 to(const char * b, const char * e) {
1162   FOLLY_RANGE_CHECK(b < e, "Empty input string in conversion to integral",
1163                     to<std::string>("b: ", intptr_t(b), " e: ", intptr_t(e)));
1164   if (!isdigit(*b)) {
1165     if (*b == '-') {
1166       Tgt result = -to<typename std::make_unsigned<Tgt>::type>(b + 1, e);
1167       FOLLY_RANGE_CHECK_BEGIN_END(result <= 0, "Negative overflow.", b, e);
1168       return result;
1169     }
1170     FOLLY_RANGE_CHECK_BEGIN_END(*b == '+', "Invalid lead character", b, e);
1171     ++b;
1172   }
1173   Tgt result = to<typename std::make_unsigned<Tgt>::type>(b, e);
1174   FOLLY_RANGE_CHECK_BEGIN_END(result >= 0, "Overflow", b, e);
1175   return result;
1176 }
1177
1178 /**
1179  * Parsing strings to integrals. These routines differ from
1180  * to<integral>(string) in that they take a POINTER TO a StringPiece
1181  * and alter that StringPiece to reflect progress information.
1182  */
1183
1184 /**
1185  * StringPiece to integrals, with progress information. Alters the
1186  * StringPiece parameter to munch the already-parsed characters.
1187  */
1188 template <class Tgt>
1189 typename std::enable_if<
1190   std::is_integral<Tgt>::value
1191   && !std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1192   Tgt>::type
1193 to(StringPiece * src) {
1194
1195   auto b = src->data(), past = src->data() + src->size();
1196   for (;; ++b) {
1197     FOLLY_RANGE_CHECK_STRINGPIECE(b < past,
1198                                   "No digits found in input string", *src);
1199     if (!isspace(*b)) break;
1200   }
1201
1202   auto m = b;
1203
1204   // First digit is customized because we test for sign
1205   bool negative = false;
1206   /* static */ if (std::is_signed<Tgt>::value) {
1207     if (!isdigit(*m)) {
1208       if (*m == '-') {
1209         negative = true;
1210       } else {
1211         FOLLY_RANGE_CHECK_STRINGPIECE(*m == '+', "Invalid leading character in "
1212                                       "conversion to integral", *src);
1213       }
1214       ++b;
1215       ++m;
1216     }
1217   }
1218   FOLLY_RANGE_CHECK_STRINGPIECE(m < past, "No digits found in input string",
1219                                 *src);
1220   FOLLY_RANGE_CHECK_STRINGPIECE(isdigit(*m), "Non-digit character found", *src);
1221   m = detail::findFirstNonDigit<Tgt>(m + 1, past);
1222
1223   Tgt result;
1224   /* static */ if (!std::is_signed<Tgt>::value) {
1225     result = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1226   } else {
1227     auto t = detail::digits_to<typename std::make_unsigned<Tgt>::type>(b, m);
1228     if (negative) {
1229       result = -t;
1230       FOLLY_RANGE_CHECK_STRINGPIECE(is_non_positive(result),
1231                                     "Negative overflow", *src);
1232     } else {
1233       result = t;
1234       FOLLY_RANGE_CHECK_STRINGPIECE(is_non_negative(result), "Overflow", *src);
1235     }
1236   }
1237   src->advance(m - src->data());
1238   return result;
1239 }
1240
1241 /**
1242  * StringPiece to bool, with progress information. Alters the
1243  * StringPiece parameter to munch the already-parsed characters.
1244  */
1245 template <class Tgt>
1246 typename std::enable_if<
1247   std::is_same<typename std::remove_cv<Tgt>::type, bool>::value,
1248   Tgt>::type
1249 to(StringPiece * src) {
1250   return detail::str_to_bool(src);
1251 }
1252
1253 namespace detail {
1254
1255 /**
1256  * Enforce that the suffix following a number is made up only of whitespace.
1257  */
1258 inline void enforceWhitespace(const char* b, const char* e) {
1259   for (; b != e; ++b) {
1260     FOLLY_RANGE_CHECK_BEGIN_END(isspace(*b),
1261                                 to<std::string>("Non-whitespace: ", *b),
1262                                 b, e);
1263   }
1264 }
1265
1266 }  // namespace detail
1267
1268 /**
1269  * String or StringPiece to integrals. Accepts leading and trailing
1270  * whitespace, but no non-space trailing characters.
1271  */
1272 template <class Tgt>
1273 typename std::enable_if<
1274   std::is_integral<Tgt>::value,
1275   Tgt>::type
1276 to(StringPiece src) {
1277   Tgt result = to<Tgt>(&src);
1278   detail::enforceWhitespace(src.data(), src.data() + src.size());
1279   return result;
1280 }
1281
1282 /*******************************************************************************
1283  * Conversions from string types to floating-point types.
1284  ******************************************************************************/
1285
1286 /**
1287  * StringPiece to double, with progress information. Alters the
1288  * StringPiece parameter to munch the already-parsed characters.
1289  */
1290 template <class Tgt>
1291 inline typename std::enable_if<
1292   std::is_floating_point<Tgt>::value,
1293   Tgt>::type
1294 to(StringPiece *const src) {
1295   using namespace double_conversion;
1296   static StringToDoubleConverter
1297     conv(StringToDoubleConverter::ALLOW_TRAILING_JUNK
1298          | StringToDoubleConverter::ALLOW_LEADING_SPACES,
1299          0.0,
1300          // return this for junk input string
1301          std::numeric_limits<double>::quiet_NaN(),
1302          nullptr, nullptr);
1303
1304   FOLLY_RANGE_CHECK_STRINGPIECE(!src->empty(),
1305                                 "No digits found in input string", *src);
1306
1307   int length;
1308   auto result = conv.StringToDouble(src->data(),
1309                                     static_cast<int>(src->size()),
1310                                     &length); // processed char count
1311
1312   if (!std::isnan(result)) {
1313     src->advance(length);
1314     return result;
1315   }
1316
1317   for (;; src->advance(1)) {
1318     if (src->empty()) {
1319       throw std::range_error("Unable to convert an empty string"
1320                              " to a floating point value.");
1321     }
1322     if (!isspace(src->front())) {
1323       break;
1324     }
1325   }
1326
1327   // Was that "inf[inity]"?
1328   if (src->size() >= 3 && toupper((*src)[0]) == 'I'
1329         && toupper((*src)[1]) == 'N' && toupper((*src)[2]) == 'F') {
1330     if (src->size() >= 8 &&
1331         toupper((*src)[3]) == 'I' &&
1332         toupper((*src)[4]) == 'N' &&
1333         toupper((*src)[5]) == 'I' &&
1334         toupper((*src)[6]) == 'T' &&
1335         toupper((*src)[7]) == 'Y') {
1336       src->advance(8);
1337     } else {
1338       src->advance(3);
1339     }
1340     return std::numeric_limits<Tgt>::infinity();
1341   }
1342
1343   // Was that "-inf[inity]"?
1344   if (src->size() >= 4 && toupper((*src)[0]) == '-'
1345       && toupper((*src)[1]) == 'I' && toupper((*src)[2]) == 'N'
1346       && toupper((*src)[3]) == 'F') {
1347     if (src->size() >= 9 &&
1348         toupper((*src)[4]) == 'I' &&
1349         toupper((*src)[5]) == 'N' &&
1350         toupper((*src)[6]) == 'I' &&
1351         toupper((*src)[7]) == 'T' &&
1352         toupper((*src)[8]) == 'Y') {
1353       src->advance(9);
1354     } else {
1355       src->advance(4);
1356     }
1357     return -std::numeric_limits<Tgt>::infinity();
1358   }
1359
1360   // "nan"?
1361   if (src->size() >= 3 && toupper((*src)[0]) == 'N'
1362         && toupper((*src)[1]) == 'A' && toupper((*src)[2]) == 'N') {
1363     src->advance(3);
1364     return std::numeric_limits<Tgt>::quiet_NaN();
1365   }
1366
1367   // "-nan"?
1368   if (src->size() >= 4 &&
1369       toupper((*src)[0]) == '-' &&
1370       toupper((*src)[1]) == 'N' &&
1371       toupper((*src)[2]) == 'A' &&
1372       toupper((*src)[3]) == 'N') {
1373     src->advance(4);
1374     return -std::numeric_limits<Tgt>::quiet_NaN();
1375   }
1376
1377   // All bets are off
1378   throw std::range_error("Unable to convert \"" + src->toString()
1379                          + "\" to a floating point value.");
1380 }
1381
1382 /**
1383  * Any string, const char*, or StringPiece to double.
1384  */
1385 template <class Tgt>
1386 typename std::enable_if<
1387   std::is_floating_point<Tgt>::value,
1388   Tgt>::type
1389 to(StringPiece src) {
1390   Tgt result = to<double>(&src);
1391   detail::enforceWhitespace(src.data(), src.data() + src.size());
1392   return result;
1393 }
1394
1395 /*******************************************************************************
1396  * Integral to floating point and back
1397  ******************************************************************************/
1398
1399 /**
1400  * Checked conversion from integral to flating point and back. The
1401  * result must be convertible back to the source type without loss of
1402  * precision. This seems Draconian but sometimes is what's needed, and
1403  * complements existing routines nicely. For various rounding
1404  * routines, see <math>.
1405  */
1406 template <class Tgt, class Src>
1407 typename std::enable_if<
1408   (std::is_integral<Src>::value && std::is_floating_point<Tgt>::value)
1409   ||
1410   (std::is_floating_point<Src>::value && std::is_integral<Tgt>::value),
1411   Tgt>::type
1412 to(const Src & value) {
1413   Tgt result = value;
1414   auto witness = static_cast<Src>(result);
1415   if (value != witness) {
1416     throw std::range_error(
1417       to<std::string>("to<>: loss of precision when converting ", value,
1418 #ifdef FOLLY_HAS_RTTI
1419                       " to type ", typeid(Tgt).name()
1420 #else
1421                       " to other type"
1422 #endif
1423                       ).c_str());
1424   }
1425   return result;
1426 }
1427
1428 /*******************************************************************************
1429  * Enum to anything and back
1430  ******************************************************************************/
1431
1432 template <class Tgt, class Src>
1433 typename std::enable_if<
1434   std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1435 to(const Src & value) {
1436   return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1437 }
1438
1439 template <class Tgt, class Src>
1440 typename std::enable_if<
1441   std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type
1442 to(const Src & value) {
1443   return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1444 }
1445
1446 } // namespace folly
1447
1448 // FOLLY_CONV_INTERNAL is defined by Conv.cpp.  Keep the FOLLY_RANGE_CHECK
1449 // macro for use in Conv.cpp, but #undefine it everywhere else we are included,
1450 // to avoid defining this global macro name in other files that include Conv.h.
1451 #ifndef FOLLY_CONV_INTERNAL
1452 #undef FOLLY_RANGE_CHECK
1453 #undef FOLLY_RANGE_CHECK_BEGIN_END
1454 #undef FOLLY_RANGE_CHECK_STRINGPIECE
1455 #undef FOLLY_RANGE_CHECK_STRINGIZE
1456 #undef FOLLY_RANGE_CHECK_STRINGIZE2
1457 #endif
1458
1459 #endif /* FOLLY_BASE_CONV_H_ */