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