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