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