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