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