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